# Functions

# User-defined functions

A user-defined function (e.g. function writeMessage()) starts with the keyword function, followed by ( )

The function code should be placed between { }

When a function with parameters is called (e.g. writePersonalMessage('John');), we need to supply arguments (John) to pass to the parameters (name). These parameters can be used inside your function in the same way as variables.

Because JavaScript is weakly typed, you do not need to provide a type for your parameters, only a name. You can set a parameter to have a default value if no argument is passed to the function, as in function writePersonalMessageWithDefault(name = 'Mr./Mrs.').

A function can return a value using the return statement, as illustrated in function average(number1, number2)

// Basic function
function writeMessage() {
  console.log("We hope you like this JavaScript course!");
}

writeMessage();


// Function with parameter
function writePersonalMessage(name) {
  console.log(`Dear ${name}, we hope you like this JavaScript course!`);
}

writePersonalMessage("John");


// Function with parameter and default value
function writePersonalMessageWithDefault(name = "Mr./Mrs.") {
  console.log(`Dear ${name}, we hope you like this JavaScript course!`);
}

// use the default value 'Mr./Mrs.'
writePersonalMessageWithDefault();
// use 'Jane' as the value
writePersonalMessageWithDefault("Jane");


// Function with return value
function average(number1, number2) {
  return (number1 + number2) / 2;
}

const av = average(5, 10);
console.log(av); // => 7.5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

# Function declaration vs expression

There are two different flavors of writing a named function in JavaScript

  • A function declaration always starts with the function keyword, followed by the name of the function
  • In a function expression, the function has no name (anonymous function) and is stored in a variable (which will/can be used to call the function later on)
// function declaration
function sum1(number1, number2) {
  return number1 + number2;
}

// function expression
const sum2 = function(number1, number2) {
  return number1 + number2;
};

console.log(sum1(5, 8)); // => 13
console.log(sum2(5, 8)); // => 13
1
2
3
4
5
6
7
8
9
10
11
12

REMARKS: Semicolon?

Because a function declaration is not an executable statement, it doesn't need to end with a semicolon

Function expressions are like variable declarations and need to end with a semicolon

Both flavors give you exactly the same result, BUT: Function declarations load before any code is executed, so it is possible to call the function before the declaration itself

 






console.log(sum1(5, 8)); // => 13

// function declaration
function sum1(number1, number2) {
  return number1 + number2;
}
1
2
3
4
5
6

Function expressions load when the interpreter reaches the specific line of code, so it's NOT possible to call the function before the expression itself

 






console.log(sum2(5, 8)); // => error: Uncaught ReferenceError: Cannot access 'sum2' before initialization

// function expression
const sum2 = function(number1, number2) {
  return number1 + number2;
};
1
2
3
4
5
6

# Arrow functions

Arrow functions are one of the most popular features of ES6. They make your code more readable and (much) shorter but they behave differently compared to the regular ES5 functions

Converting a regular ES5 function (expression) to an ES6 arrow function is easy:

  1. remove the function keyword
  2. add a fat arrow => between () and {}
// ES5 function expression
const sum = function(a, b) {
  return a + b;
};

// ES6 arrow function
const sum = (a, b) => {
  return a + b;
};
1
2
3
4
5
6
7
8
9

# Shorthands

# Single parameter

For a single parameter functions, parentheses are optional

const squareRoot = (number) => {
  return Math.sqrt(number);
};

// shorthand
const squareRoot = number => {
  return Math.sqrt(number);
};
1
2
3
4
5
6
7
8

# Single statement

For a single statement functions, the curly braces, and the return keyword are optional

const squareRoot = (number) => {
  return Math.sqrt(number);
};

// shorthand
const squareRoot = (number) => Math.sqrt(number);
1
2
3
4
5
6

# Timing functions

method description
setTimeout(cb, <delay>) (opens new window) execute the callback function (cb) once after a fixed <delay> in ms
setInterval(cb, <delay>) (opens new window) execute the callback function (cb) repeatedly with a fixed <delay> in ms
clearInterval(<intervalId>) (opens new window) cancels an action that was established with setInterval()

REMARK: clearInterval()

To use clearInterval(), you have to bind setInterval() to a variable first:

let timer = setInterval(function () {
    // execute this code every 3 seconds
}, 3000);

document.getElementById('cancelTimer').addEventListener('click', function(e) {
    clearInterval(timer); // cancel the timer
});
1
2
3
4
5
6
7

# Callback functions

A callback function (e.g. cb) is a function passed into another function as an argument

A good example for these are timing functions.

When you "externalize" the callback function (versions 2 and 3 below), you have to pass the function WITHOUT ()!

REMARK: countSeconds() vs countSeconds

countSeconds() means: execute the function

countSeconds doesn't execute the function but is just a reference to the code of the function countSeconds()

Last Updated: 4/17/2024, 10:43:21 AM