Functions are a key part of JavaScript and allow you to write code that is efficient, without repeating yourself. Additionally, JavaScript treats functions as objects, so they can be passed around as variables (where the value of the variable is what the function returns).
Functions are declared in JavaScript using the function keyword, followed by () brackets to hold any parameters the function requires, and { } brackets, where the code that the function executes is held; and look somewhat similar to methods in Java. Functions are called simply by using their name, followed by () brackets containing any parameters they need passed in, and then a semi-colon. Below is a simple example...
// define the function...
function myFunction() {
// the following code is executed when myFunction is called...
console.log("Hello function world!");
}
// let's call myFunction...
myFunction();
Functions return values, although they don't have to. This means a variable can be set to the result of a function
// define the function...
function returnSomething() {
var x = 5;
// let's return x... (of type Number)
return x;
}
// let's set y to the result of the returnSomething function...
var y = returnSomething();
// y will now be equal to 5 (the returned value of the function)...
console.log(y);
If a function returns no value, it returns an undefined type. Functions can return only one value - to return multiple, look at returning an object populated with the values instead.
Functions can have values passed into them. They can then use these values within, and potentially manipulate them or use them to return a result. Below is a simple example of a 'square' function, where a number is passed into it, and the square of that number is returned...
// define the square function...
function square(numberToSquare) {
// multiply the number by itself to get its square...
var square = (numberToSquare * numberToSquare);
// return the square...
return square;
}
// let's square something...
var squareMe = square(5);
// squareMe will now be equal to 25 (5 squared)
console.log(squareMe);
Multiple parameters can be passed into one function, simply separate them by commas in the function declaration, and where the function is being called.
JavaScript allows functions to be used and passed around as variables. You can see this in action in the code example below...
// set a variable to a function...
var addThese = function(x, y) {
// add them and return...
return (x + y);
}
// variable addThese can now be used just like a function...
var result = addThese(5, 10);
// let's check it holds 15 (5 + 10)...
console.log(result);
Because functions can be treated as variables, they can also be stored in arrays, or as values within objects, so objects can be given methods - rather than just holding static values. The technical term for treating functions as variables is 'anonymous functions'.