Functions in Javascript
Published on
Updated on
Ever had a snippet of code that appears multiple times in different places in your program? Whenever you had to change that snippet, you end up playing this game of search and replace. Functions can help. They exist to abstract your code, making it not only easier to change that little snippet, but to read and debug your code as well.
How to create/execute a function {#how-to-create/execute-a-function}
To make a function
var doSomething = function() {
doStuff;
}
To call the above function to execute
doSomething();
Arguments
You can also add in arguments (parameters that go inside the paraenthesis next to the word function) for the functions to use.
var add = function(number1, number2) {
return number1 + number2;
}
And when you use the return
keyword, like the function above. You can store the value in a variable for future use.
var total = add(1, 3);
total here will equal 4
Scope
Functions create their own scope, which means that variables created inside the function will only be able available within that function.
The snippet below will output an error like total is not defined
var add = function(number1, number2) {
var total = number1 + number2;
}
console.log(total);
Below is a correct example of the concept
//Function below converts km/hr to m/s
var convert = function(speed) {
var metersPerHour = speed * 1000;
var metersPerSecound = metersPerHour / 3600;
return metersPerSecond;
}
var currentSpeed = convert(5);
It’s also important to note that functions can use variables outside of it; granted it resides in the same scope.
Here is an example of a variable that doesn’t reside in the same scope as the function. (The below code will fail)
var something = function() {
var x = 5;
var y = 2;
}
something();
var addXandY = function() {
console.log(x + y);
}
addXandY();
Below, is an example of where the variable does reside in the same scope as the function. Which allows this snippet to execute properly.
var x = 5;
var addX = function(a) {
return a + x;
}
var sum = addX(6);
sum here will equal 11
Conclusion
As long as you name them appropriately, functions are useful for abstracting your code, making them easier to understand. This concludes another lecture made for the members over at Math I/O. Until next week 🙂