Functions
What is a function?
Functions are block of javascript code that can be executed when called. The block contains a series of statements that perform a specific task.
Functions can take in valid input values known as arguments, and can return the resulting variable as a return statement.
Why use a function?
Functions are useful for abiding to the DRY (don't repeat yourself) principle. You can create a function in one place, and call it from several locations. In programming, this is good practice, as it avoids writing the same chunks of code multiple times. Furthermore, this allows you to better manage your application and prevent bugs, as you won't need to update your logic in multiple places.
Declaring a function
A function is declared with the function
keyword, followed by its name and a set of paranthesis.
Just like with other variable names, function names must obey a set of rules.
- Functions must be made up of letters, numbers, _ and $.
- Functions cannot start with a number.
- Functions can't include any spaces or punctuations.
// Function that gets a random number from 1 to 100
function getRandomNumber() {
var randomNumber = Math.floor( Math.random() * 100 ) + 1;
alert(randomNumber);
}
Function hoisting
Previously we mentioned that JavaScript is a procedural language, meaning it executes code line-by-line. An exception to this methodology is with functions, which incorporate hoisting. In hoisting, the functions are moved to the top of the current scope. This allows functions to be called before they are declared.
Arguments and Parameters
Using function arguments
If you want to pass in values as part of your call to your function, you may place them between the parentheses. With multiple arguments, use commas.
// Write greeting
function writeGreeting(greeting) {
document.write(greeting);
}
// Function that gets the area of a square
function getArea(width, height) {
return width * height;
}
Parameter Rules
JavaScript, unlike other strongly typed languages, does not check specific data types when a parameter is passed onto the function. This means you can't restrict someone from passing in a String input when you want a numerical value.
Furthermore, JavaScript does not check for the number of arguments received. This means that you can pass as many or as little variables within a function as you want.
In the case where you have missing arguments, the values are set to undefined
. On the other hand, if you have too many arguments, the extraneous arguments can only be accessed wtih the arguments
object.
Arguments vs. Parameters
Parameters are the variables used before a function is called. In the case of the function getArea(width, height)
above, the width
and height
variables are the parameters.
Once we call the function, the parameters are turned into arguments.
getArea(5,6); // parameters 5 and 6
Arguments object
The arguments
object contains information on the arguments passed into a function. You can use this variable from within a function to access elements you may otherwise not have.
With this object, you can access all in an array-like fashion. Furthermore, you can find the number of arguments by accessing its length
property.
// Return minimum value
function findMin() {
var i, min = 0;
for (i = 0; i < arguments.length; i++) {
if (arguments[i] < min) {
min = arguments[i];
}
}
return min;
}
Primitive types are passed by Value, Objects by reference
Arguments are passed by value, meaning the actual value is passed in. Objects, on the other hand, pass in a reference to their address. This means that any changes on that object from within the function will retain those changes from outside.
Anonymous Functions
Conventional functions come with a name linked to its procedure. Anonymous functions, however, don't have a name.
Furthermore, the function is not processed until the statement which it is attached to is declared.
var area = function(width, height) {
return width * height;
}; // Anonymous function
var size = area(3, 4);
Anonymous Functions as Closures
A closure is a function that is passed into another function as an argument.
setTimeout(function() {
alert("Hello world!");
}, 1000);
The setTimeout
function will wait 1000 ms, then send an alert out to the user, displaying "Hello world!" This is an example of an anonymous funciton that is passed into a method as a closure.
Immediately invoked function expressions (IIFE)
Immediately Invoked Function Expressions (IIFE) pronounced iffy are executed once as the interpreter comes across them. These functions are used for a block of code that needs to be run only once.
var area = (function(n) {
return (n < 1) ? 1 : factorial(n-1) * n;
}(5));
Function Scope
Depending on where a variable is declared, it may or may not be accessible in certain segments of your code. The topic that deals with this is known as scope, and there are two main descriptors of scope - local and global.
Local
A local variable is one that is created inside a function with the var
keyword.
A local variable may only be accessed within its declared function.
global
A global variable is declared outside all functions, and is stored in memory as long as the web page is loaded into the web browser. Global varialbes have more overhead, since the browser has to remember them for however long the web page is loaded for.
Because a global variable is accessible to all areas in the code, there is a high risk of naming conflicts. Due to these reasons, global variables should be seldomly used.