How to create a function in Javascript

Description

Functions allow the encapsulation of statements.

Functions in Javascript are declared using the function keyword, followed by arguments and the function body.

The basic syntax is as follows:


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

Example

Here's an example. This function is called using its name, followed by the function arguments enclosed in parentheses and separated by commas in case of multiple arguments.


function sayHi(name, message) {
    console.log("Hello " + name + ", " + message);
}
sayHi("Javascript", "is it working?");

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions