JavaScript function

A function is a set of statements that take inputs, do some specific computation, and produces output. Basically, a function is a set of statements that performs some tasks or does some computation and then return the result to the user.

The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call that function.

There are mainly two advantages of JavaScript functions.

Code reusability: We can call a function several times so it save coding. Less coding: It makes our program compact. We don’t need to write many lines of code each time to perform a common task.

JavaScript Function Syntax The syntax of declaring function is given below.

function functionName([arg1, arg2, ...argN]){  
 //code to be executed  
}

Before, using a user-defined function in JavaScript we have to create one. We can use the above syntax to create a function in JavaScript. A function definition is sometimes also termed as function declaration or function statement.

Below are the rules for creating a function in JavaScript:

  • Every function should begin with the keyword function followed by, A user defined function name which should be unique, A list of parameters enclosed within parenthesis and separated by commas, A list of statement composing the body of the function enclosed within curly braces {}.
function calcAddition(number1, number2)
{
    return number1 + number2;
}

Calling Functions: After defining a function, the next step is to call them to make use of the function. We can call a function by using the function name separated by the value of parameters enclosed between parenthesis and a semicolon at the end. Below syntax shows how to call functions in JavaScript:

functionName( Value1, Value2, ..);