- Functions
- Last updated on
Writing a Function
Functions are blocks of code that can be used to run a task. Let’s look at how we can use them to make our code easier to write and maintain.
There have historically been two ways to write a function.
// Function declaration
function add (num1, num2) {
return num1 + num2;
}
// Function expression
let add = function (num1, num2) {
return num1 + num2;
};
The first example, function add () {}, is called a function declaration. The second example, let add = function () {}, is called a function expression.
They more-or-less do the same thing, but there’s one subtle yet important difference between them.
Note: There’s now a third way—ES6 arrow functions—that we’ll talk about in a later chapter.
Try it! Create a function that logs 🧙♂️ Abracadabra into the console, then run it.