Define a Function

In this chapter we'll learn how to define a function of our own.

Function definition syntax

function name(parameter1, parameter2..) {
    code to be executed
}

A JavaScript function is defined with the function keyword, followed by a name, then parenthesis ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

The parenthesis may include parameter names separated by commas: (parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: { }

JS function follows the JS compound statement style, this is similar to for loop and if statements

Simple functions with no input parameters

Example:

function sayHi() {
    console.log("Hi!");
}

The first line begins with the keyword function to start the new function called sayHi. The empty parenthesis means this function doesn't have any input parameters. The line ends with a curly bracket {.

The function body contains only one line and it's indented by 4 spaces.

The closing curly bracket } is on a new line.

results matching ""

    No results matching ""