Tidbit 0: Function Declaration vs. Function Expression in JavaScript

Jan 5, 2019 06:29 · 196 words · 1 minute read function declaration function expression javascript tidbit

Tidbit is a series of (hopefully) short and sweet explanations of certain ideas and topics across computer science. Since large tutorials takes time to write, I will fill the time with tidbits which can act as pocket guides to help remind you of certain concepts.

Two Ways of Writing a Function

In Javascript there are two ways to write a function:

Function Declaration

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

and

Function Expression

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

Hoisting: The Differentiator

The difference between the two function types is the idea of hoisting. Hoisting is just a fancy way of saying that something is available or known before any code is run.

What this means behind the scenes is that function declarations and variable declartions are added to memory during compilation.

What Works

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

add(2, 2); // returns 4

and

add(2, 2); // returns 4

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

What Does Not Work

add(2, 2) // returns Uncaught TypeError: add is not a function

let add = function(num1, num) {
    return num1 + num2;
}
Tweet Share