Functions in JavaScript

Functions are central in JavaScript. We’ll learn about functions with a few different examples.

// Here's a function that takes two numbers and returns
// their sum as a number.
function plus(a, b) {
    // JavaScript has implicit returns, but we'll use an explicit return
    // to maintain similarity with the original example.
    return a + b;
}

// In JavaScript, we don't need to specify types for parameters.
// Here's a function that takes three parameters and returns their sum.
function plusPlus(a, b, c) {
    return a + b + c;
}

// In JavaScript, we don't have a main function.
// Instead, we can just write our code at the top level.
// For demonstration purposes, we'll wrap it in an immediately invoked function expression (IIFE).
(function() {
    // Call a function just as you'd expect, with name(args).
    let res = plus(1, 2);
    console.log("1+2 =", res);

    res = plusPlus(1, 2, 3);
    console.log("1+2+3 =", res);
})();

To run this JavaScript code, you can save it in a file (e.g., functions.js) and run it using Node.js:

$ node functions.js
1+2 = 3
1+2+3 = 6

There are several other features to JavaScript functions. One is the ability to return multiple values using arrays or objects, which we’ll look at next.