Javascript Functions
📣 Sponsor
As in most languages, a function in Javascript is a way to do a very specific thing, which you can run many times over in your code. Functions are useful for pieces of code you reuse over and over again. Within functions, we have a different scope. As such, we will also be covering scope in this tutorial.
Functions
Consider you are writing a program, and want to keep adding 5 to a specific number over and over again, and if the number is more than 200, then multiply it by Pi. Functions allow us to do this and then run it easily again and again. If we want to write that function, we'd do something like this:
// Call our function addFiveThenPi, and give it a number variable.
function addFiveThenPi(number) {
// Add 5 to the number
let newNumber = number + 5;
// If newNumber is more than 200, then multiply it by PI.
if(newNumber > 200) {
newNumber *= Math.PI;
}
// The output of this function is newNumber, so we return it.
return newNumber;
}
To define a function, we can use the keyword function
, followed by the name of our function and round brackets, i.e. function addFiveThenPi()
. Within the round brackets, we can define variables which can be defined when we call our function. Within the curly brackets {}
, we have the actual set of instructions the function will carry out when it is called.
Sometimes a function has a return value, which we define by using the return
keyword. If you don't add return
to your function, Javascript will return undefined
for that function by default. The above function returns the value of newNumber
. That means, after running the function, we will get an output of whatever the value after return
is. Let's try running our function. Well console log its value, so we can see it:
function addFiveThenPi(number) { // Add 5 to the number let newNumber = number + 5; // If newNumber is more than 200, then multiply it by PI. if(newNumber > 200) { newNumber *= Math.PI; } // The output of this function is newNumber, so we return it. return newNumber; } let calculateVariable = addFiveThenPi(5); console.log(calculateVariable);
Walking through this, the above will take the number 5 and add 5 (i.e. 10) - and since this is less than 200, we won't multiply it by Pi. We can call this function multiple times. Functions are reusable, so we can call them multiple times and get multiple different returns:
let example1 = addFiveThenPi(5);
let example2 = addFiveThenPi(100);
let example3 = addFiveThenPi(200);
This gives us flexibility to run a complicated set of instructions multiple times. Since our function returns a value, we can also use it pretty much anywhere - for example, directly in an if statement:
if(addFiveThenPi(10) < 1000) {
console.log('Well done!');
}
Variable Functions
Javascript has a few different ways to write functions. One way is to write it in the form of a variable which stores a function. These can still be called in exactly the same way as a normal function:
const myFunction = function(number) {
// Contents of the function goes here
}
Anonymous Functions
Javascript also gives us the option to define a variable without a name. These functions can then only be ran once. In the example below, we pass 5 as the value of number:
(function(number) {
// Content of the function goes here
})(5);
Arrow Notation Functions
Arrow notations let us create functions without the need to use the function keyword.
const myFunction = (number) => {
// Function goes here
}
Arrow functions don't have this
or super
, so when you call this
inside of them, you will get the this
of its parent.
As well, if you only have one line in an arrow function, you don't need brackets for the variables, and the piece after the arrow is automatically returned, i.e. this will return number * 10
:
const myFunction = number => number * 10;
Similarly, the below is valid:
const myFunction = (x, y) => x * y;
Scoping within Functions
Scope is how we determine if certain variables can be referenced or not, based on where we are writing them. Functions have a closed scope, meaning things inside of them cannot be used outside of them. For example:
let myFunction = function() {
let number = 2;
}
In the above code, number
cannot be called outside of myFunction. If you do try, it will be undefined. However, in the below example, since number is declared outside of the function, it can be called both within the function, and outside of it:
let number = 2;
let myFunction = function() {
// We could use "number" here
}
// And we can also use "number" here
As such, anything in the global, i.e. at the top level, outside of any functions or conditional statements, can be referred and called within functions and conditional statements.
More Tips and Tricks for Javascript
- Updating Object Key Values with Javascript
- Types may be coming to Javascript
- How the Javascript History API Works
- Javascript Dates and How they Work
- Creating a NodeJS Push Notification System with Service Workers
- Javascript Logical Statements and Loops
- What are NodeLists, and how do they work?
- Creating and Generating UUIDs with Javascript
- Javascript Array Slice Method
- Truthy and Falsy Values in Javascript