3 Different Ways to Create Functions in Javascript

As a beginner to JS, one thing that confused me when I looked at others’ code was their use of different function syntaxes. To illustrate, here is the syntax I originally learned. This is a simple function that adds two numbers:

function add(num1, num2) {
	return num1 + num2;

Here is that same function with ES5 syntax. Note that this method assigns the function to a variable. You can then use that variable as a normal function:

var add = function(num1, num2) {
	return num1 + num2;

Also notice the semicolon after the statement. That is there because it is acting as a regular variable declaration statement.

Finally, here is the latest syntax as defined in the ES6 syntax:

const add = (num1, num2) => {
	return num1 + num2

However, if you only had one expression, the curly brackets aren’t required, like so:

const add = (num1, num2) => return num1 + num2;

In addition, if there is only one argument, you can dispose with the parentheses. This function returns the square of a variable:

const square = var => return var^2;

However, if there are no variables, the parenthesis are needed:

const hello_world = () => console.log('Hello World');


Using these different syntax’s for functions can make your functions more concise, in addition to making your code more up-to-date.