Functions in JavaScript

Functions allows you to create code that can be called repeatable in different areas of the code without having to rewrite the code. We can also pass parameters into function to allow us to get slightly different results. Imagine a multiplication or two numbers, it is the same operation but can be used with any two numbers that are supplied to the calculation/function.

In JavaScript we create functions by using the ‘function’ keyword followed by the name of the function. After the name comes two parenthesis that contain the argument, the function below has no arguments so there are empty parenthesis. Following the arguments are two curly brackets ‘{..}’. Within the two curly brackets is the body of the function, this is where the logic of the function is written. The below function simply logs a string to the console. The declaration of a function, when we create it, does not execute any code. We must call the function for the code within the function to be executed. The last two lines of the code snippet below show calling the function twice, meaning the string is logs twice. We call a function in JavaScript just by writing the name of the function followed by the arguments wrapped in parenthesis. Again, this function has not arguments so the parenthesis are empty.

Functions can also return values. This means when we call a function a value is return, similarly to multiplying two numbers we get a result. The below code snippet shows a function called ‘getNumber’ which returns the number 2. To return a value within a function in JavaScript we use the ‘return’ keyword followed by the value we want to return. The last three lines of the code below show calling this function. We create a variable called ‘a’ and assign it’s value to the result of the function ‘getNumber’. This means the value of ‘a’ will be the number 2. We can also just log out the result of a function, by calling it within the ‘console.log’ function. This means the value of 2 will be logged to the console.

The below function shows using arguments and a return value. The ‘multiply’ functions takes two arguments, called ‘a’ and ‘b’ and return the result of those two arguments multiplied together. The names given to the parameters are the names of the variables within a function, this is how we refer to the variables within the function body. We can then call the function and give two arguments, the numbers 2 and 4. The last line of the code below will print the number 8, as that is the return value from the function and the result o the number 2 multiplied by the number 4.

Functions can be difficult for new developers to understand. The important thing to understand is that a function is not executed until you call the function, creating a function does not execute any code. The function must be called for the function to be executed.

Leave a Reply