Skip to content

Instantly share code, notes, and snippets.

@acidtone
Last active February 7, 2022 09:28
Show Gist options
  • Save acidtone/e3ed5adfcb4f3c02f1b78f78c9c2bf8b to your computer and use it in GitHub Desktop.
Save acidtone/e3ed5adfcb4f3c02f1b78f78c9c2bf8b to your computer and use it in GitHub Desktop.
Functions: Defining as declaration vs expression

Declaring functions

There are two common ways to define a function in Javascript:

Function Statement

Also referred to as a function declaration, this is a classic syntax common to many languages. Function declarations load the function into memory during the Creation Phase (iow, the function definition is "hoisted").

function greet() {
  console.log('Hi!');
}

Function Expression

In Javascript, functions are considered First-class (citizens) and are treated like any other value. A function expression returns the function as a value which can then be assigned to a variable using the assignment operator =.

const greet = function() {
  console.log('Hi!');
};

ES6 Fat Arrow Syntax

In June 2015, a new version of Javascript (ES6) was released and added a new "fat arrow" syntax for declaring functions. You will often see this syntax in documentation:

const greet = () => {
  console.log('Hi!');
}

Key Takeaways

  • Code inside a function does not execute at the time of declaration. You have to invoke a function later to run the code inside it.

Related Gists

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment