Introduction to JavaScript Functions

Syntax

Functions can be defined using two slightly different syntaxes. The arrow function notation is what we'll see most of in newer code bases, but the regular old function notation is still used in many places. They are mostly identical in behavior, though classes still have to be written using the regular function syntax.

Arrow function notation

The modern arrow function notation allow us write shorter more concise functions that remind us that functions aren't all that different from other value types.

We define an arrow function by binding a function to a let, const or var declaration.

// example arrow function
const functionName = (parameter1, parameter2, ...etc) => {
statement1/declaration1
statement2/declaration2
...
statementX/declarationX
return someValue
}

Code example: no input parameters

This function takes no input parameters and returns a single static value.

const pi = () => {
return 3.14
}

We can drop the braces and the return keyword if the function only has one line and we want to immediately return that value, as shown below.

const pi = () => 3.14

Code example: one parameter

This function takes one parameter and returns a value depending on the input parameter x.

function squared(x) {
return x * x
}

or written in a more idiomatic way

const squared = x => x * x

Regular

We define a function by using the keyword function followed by the function's name. The function's parameters comes afterwards surrounded by parentheses. The parantheses are mandatory even if the function doesn't take any input parameters. We can then start a new block using braces to define the function's body. The body consists of zero or more declarations and statements.

We return values using the return keyword followed by the value we want to return.

// example regular function
function functionName(parameter1, parameter2, ...etc) {
statement1/declaration1
statement2/declaration2
...
statementX/declarationX
return someValue
}

Code example: no input parameters

This function takes no input parameters and returns a single static value.

function pi() {
return 3.14
}

Code example: one parameter

This function takes one parameter and returns a value depending on the input parameter x.

function squared(x) {
return x * x
}