Javascript - Function

29 October 2020, 1:16 pm by antelove19

Javascript - Function
Javascript - Function

Definition

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).


Javascript - Function

Syntax

function name() 
{
    // code to be executed
}

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

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

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


Example

create the function

function say() 
{
    console.log("Hello Wordl");
}

call the function

say(); // Hello World

Javascript - Function with return value

Syntax

function name() 
{
    // code to be executed
}

Example
function say() 
{
    return "Hello Wordl";
}

call function

console.log( say() ); // Hello World

Javascript - Function pass parameter(s) by value

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

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

Syntax

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

Example

create the function

function say( parameter1, parameter2, parameter3 ) 
{
    console.log( `Hello ${parameter1}`);
    console.log( `Hello ${parameter2}`);
    console.log( `Hello ${parameter3}`);
}

call the function

say( "Jhon", "Doe", "stranger" ); // Hello Jhon, Hello Doe, Hello Stranger

Javascript - Function pass parameter(s) by value with return value

When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.

Functions often compute a return value. The return value is "returned" back to the "caller":

Syntax

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

Example

create the function

function say( parameter1, parameter2, parameter3 ) 
{
    return `Hello ${parameter1}, Hello ${parameter2}, Hello ${parameter3}`;
}

call the function

console.log( say( "Jhon", "Doe", "stranger" ) ); // Hello Jhon, Hello Doe, Hello Stranger



Keywords:


Video not yet
0 comment