Javascript Function Definition

Introduction

The basic function syntax is as follows:

function functionName(arg0, arg1, ..., argN) {
    statements
}

Here's an example:

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

This function can be called by using the function name, followed by the function arguments.

The code to call the sayHi() function looks like this:

sayHi("HTML", "how are you today?"); 

The output of this function call is, "Hello HTML, how are you today?"

Functions in Javascript need not specify whether they return a value.

Any function can return a value at any time by using the return statement followed by the value to return.

function sum(num1, num2) {
    return num1 + num2;
}

The sum() function adds two values together and returns the result.

This function can be called using the following:

const result = sum(5, 10); 

A function stops executing and exits immediately when it encounters the return statement.

Therefore, any code that comes after a return statement will never be executed.

For example:

function sum(num1, num2) {
    return num1 + num2;
    console.log("Hello world"); // never executed 
}

In this example, the console.log will never be displayed because it appears after the return statement.

We can have more than one return statement in a function, like this:

function diff(num1, num2) {
    if (num1 < num2) {
        return num2 - num1;
    } else {
        return num1 - num2;
    }
}

Here, the diff() function determines the difference between two numbers.

The return statement can also be used without specifying a return value.

In the following example, where the console.log won't be displayed:

function sayHi(name, message) {
    return;
    console.log("Hello " + name + ", " + message); // never called 
}

Strict mode places several restrictions on functions:

  • No function can be named eval or arguments.
  • No parameter can be named eval or arguments.
  • No two named parameters can have the same name.



PreviousNext

Related