Functions are blocks of code that can be called repeatedly.
Functions are defined like variables but have parentheses following the function name.
The parentheses ()
are used to
There a two primary ways to create a function.
Notice how nothing happens after we declare the function. The function is defined, but the code won't run until it is called:
Arguments
A function can also be written with
Think of a function like a machine that performs a series of actions. The actions are always the same, but the outcome may change depending on the arguments, or parameters.
Think of a function as a blender. A blender is a machine that does one thing: It blends food together.
Depending on what food you put into it, the result will be different.
The ingredients you put in a blender are like arguments.
If I put ice, milk, berries and bananas in a blender, I'll get a banana-berry smoothie.
If I put kale, celery, apples and pineapples in a blender I'll get a green juice.
Let's write a function with arguments.
Now check what happens if we call the function with out arguments:
Why is this undefined, undefined
?
The variables that are created for the arguments of the function, in this case name
and greeting
and declared when the function is invoked.
So, even though we never wrote var name;
or var greeting;
they are created, and when a variable is declared but not assigned, it has the value undefined
. Because we did not call our function with the right arguments, those values stay undefined.
Return
Functions can also return
values. A return statement stops the function execution and returns a value to whatever variable the function is assigned to.
Anonymous functions
Regular JavaScript functions need to be called after they are declared. There are cases where we want a function to run immediately. These are anonymous functions, which call themselves.
Scope
A quick note on scope: Variables declared within a function are not available to other functions in our program. Any variables declared in the
Read more on scope.
Bad scope example:
Better scope example:
One common practice used to avoid this is to wrap all of the code in your script in a self invoking function, which will keep things out of the global scope. Another approach is to make a global object that has methods to access variables which allows your script to be accessible in other scripts without exposing all of your variables to the global scope.
More on functions.