JavaScript Functions

Sept 15, 2022

Functions

Functions

Functions are a series of grouped statements that can be called by an assigned identifer. They have the capability of accepting input in the form of parameters and can return a value as output.

Functions are great in places where we expect to need to repeat the same task multiple times and avoid duplicated code.

Function Declaration

function sayHello(name) {
  console.log("Hello, " + name);
}

Function Usage

sayHello('Don'); // outputs "Hello, Don"

Return Values

Functions can also return values:

function area(width, height) {
    return width * height;
}
let rectArea = area(5, 6); // rectArea is 30

Arrow Functions

Arrow functions are a compact alternative to normal functions.

function square(num) {
    return num * num;
}

could become

let square = (num) => num * num;