Functions in JavaScript are based on the concept of functions in mathematics:
Given: f(x) = 3x + 1, f(2) would return the value 7, f(11) would return the value 34 …
f is the name of the function
x is a parameter
Programmer-defined functions
JavaScript lets you define your own functions. We might write a definition for the function above as follows:
The definition won’t do anything unless you call (or invoke) it:
As was the case with variable names, you typically want to use descriptive names for functions.
Name rules for functions are the same as for variables.
When you call (or invoke) a function, you can pass in literal values or variables.
You can define as many functions as you need and have functions call other functions.
You can define a function inside another function—but we’ll not deal with that now.
Functions can be simple as above or more complicated:
You can pass in several parameters:
Beyond math
Any data type (not just numbers!) can be used for parameters or the return value.
You don’t need parameters:
You don’t even need a return value:
Predefined functions
In addition to functions you write yourself, JavaScript has a large list of predefined functions.
Many of these are defined in JavaScript’s Math object.
These are technically methods, but we will let the distinction slide for now.
Some useful functions in the Math object are summarized below:
Math.round(x) — Returns the value of a number rounded to the nearest integer.
Math.floor(x) — Returns the largest integer less than or equal to a number.
Math.ceil(x) — Returns the smallest integer greater than or equal to a number.
You should take some time to familiarize yourself with the others.
Random numbers
One of the most useful things in the Math object for us is Math.random().
Math.random() returns a different random number between 0 (inclusive) and 1 (exclusive) each time it is called.
We can use this as a basis for creating our own function that returns a random integer between a lower and upper bound.
A real guessing game
Armed with the randomInt() function defined above, we can now modify our guessing game so the user needs to guess a different number each time he plays.
Here we define an additional function to make getting the user’s guess cleaner:
Scope
The following examples help to illustrate how scope works in JavaScript.
Consider the following example where we define a variable inside a function with same name as one outside the function:
And now with one small change—eliminating the variable declaration inside the function:
And another small change—removing the declaration outside the function:
Scope means “where a variable can be accessed.”
Variables can be global or local.
Variables declared outside a function are global variables and can be accessed anywhere.
Variables declared inside a function are local variables.
Local variables can only be accessed inside that function and things defined inside that function.
Parameters have the same scope as variables defined within the function.
If a variable is declared inside a function with a name that is same as one in an encompassing scope, then the variable defined in the function is the one that is accessed with the name.
The importance of var
If you use a name on the left side of an assignment that is not already the name of a variable that can be accessed, JavaScript will automatically create a new variable for you with that name.
Variables created in this way are automatically global variables. foo ='Some value';// Creates a new global variable foo if foo doesn't already exist.
Having all your names in the global namespace is a really bad idea—eventually you will accidentally think you are creating a new variable when in fact you are writing over a variable that is used someplace else.
Always, always, always use var unless you have a good reason not to.
Functions as values
So far, we have seen numbers, strings, Booleans, and the special values undefined and null used as values for variables.
In JavaScript, functions can also be used as the value of a variable:
Here is a (slightly) more useful example:
At first, the utility of this might seem limited, but this is a core JavaScript concept.
Function literals
There are some situations where you don’t need to give functions a name.
Function definitions without names are called function literals or anonymous functions. You will see them a lot.
You don’t need to provide a function a name if it is used as a variable’s value:
or a parameter’s value:
You will sometimes hear people refer to function literals as closures. These people are wrong. Closures are an unrelated concept and can be written with named functions or function literals.