JavaScript Function Basics

Kelly M.
2 min readNov 10, 2019

Firstly, what is a function? A function one of the fundamental building blocks of JavaScript. Functions allow us to hold something in memory until we need to use it.

Function Declaration || Function Definition

function multiply(a, b){ 
return a * b;
}

Above is the syntax of what a function declaration, sometimes called function definition, looks like. We can test this function in our console by using console.log.

console.log(multiply(5,4)) // will return 20

The parameters passed in the function named ‘multiply’ are named (a, b) here. The names of these parameters don’t matter as much as their order. We can essentially name them anything, but there is a best practice when it comes to names.

When returning, you must return them in the correct order. The best practice for naming is to give parameters relevant names, so the next developer who comes in can be able to read your code. Keep human readability in mind when naming things. In this example, the function named ‘multiply’ is understandable, but the parameter names of (a, b) are not. Better parameter names would be (num1, num2).

In our console.log, we have one argument for each parameter. 5 being the argument of a, and 4 being the argument of b.

Function Expression || Anonymous Function

let add = function(num1, num2){ 
return num1 + num2;
}
console.log(add(4,4)) // 8

Above is the syntax for an anonymous function, sometimes called a function expression. Notice that this function has no name next to it, and is invoked by the value of the variable, add.

We are using a function on the right hand side of the assignment operator. Function expressions are used when we want to control its invocation, when we do not want to invoke it every time.

Arrow Functions

let add = (a, b) => { 
return a + b;
}
console.log(add(4,4)) // 8

Arrow functions are function expressions with different syntax. As you can see, they have a shorter syntax, however they do not bind the ‘this’ keyword. So in some cases, they are not the best thing to use, though they are often used in array methods.

Comparing its syntax to a regular function expression, we can see that all we did here was remove the word ‘function’ and introduced the => . We can actually get rid of even more syntax when using arrow function if we are only returning one value.

let add = (a,b) => a + b; 

console.log(add(4,4)) // 8

We don’t even need the curly brackets or the return statement because it is implied. Again, this further reduced version of an arrow function can be used when we are returning only one value.

--

--