Group 3 - Variables Data Types and Operators
Group 3 - Variables Data Types and Operators
to Functions in
JavaScript
How to Write a Function
There are three ways we can build a function. For this presentation, we will be
focusing on just the first one.
Anatomy of a Function
The function keyword is used to indicate to the JavaScript engine that you are
defining a function, and to associate the name you provide with the code that
follows. This name is what you will use to call the function later on.
Parameters
Function parameters are values that are passed into a function when it is called.
They allow you to provide input to a function, and to customize the behavior
of the function based on that input.
Arguments
The arguments object is an array-like object that contains the values of the
arguments passed into a function when it is called. It is automatically created
and populated by the JavaScript engine when a function is called, regardless of
whether or not the function definition explicitly includes parameters.
To use an argument, just put the data in the function call parentheses like so:
If you have more than one parameter, you will use more than one argument:
Scope
Function scope refers to the area of code where variables and functions defined
inside a function are visible and accessible. This means that variables and
functions defined inside a function can only be accessed within that function,
and are not visible outside of it.
Function Level Scope
Functions have something similar, known as function scope. Function scope
allows us to create variables inside of functions, that are essentially private to
that function. We can not reach into a function from the outside and get access
to these variables. But we are free to use these variables anywhere within our
function. Conversely, we DO have access to variables outside of the function. It
is a one-way street. Functions can reach out and grab variables outside of their
scope, but we can not reach into a function to get a variable.
Example:
The return Statement
The return statement is used to specify the value that a function should return
when it is called. The return statement can be used in any function, and allows
you to return a value to the code that called the function.