Home / Lessons / Functions

Functions

JavaScript-logo

Functions are blocks of code that can be named and reused.

Here’s how to declare a function:

EXAMPLE

function addTwoNumbers(x, y) {
       return x + y;
}

There’s a lot going on in the example above, so let’s look at each part individually.

Using functions

Once a function is defined, you can use it by referencing its name with parentheses () right after.

Note that a function doesn’t have to have parameters.

EXAMPLE

function greetThePlanet() {
       return "Hello world!";
}

greetThePlanet();

OUTPUT

"Hello world!"

If a function does have parameters, you’ll need to provide values inside the parentheses when using the function.

EXAMPLE

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

square(16);

OUTPUT

256

Reference: https://www.javascript.com/learn/functions


Previous: Variables
Next: Conditionals