JavaScript functions are defined with the function keyword. We may use a function declaration or a function expression.
Function Declaration:
We declare functions with the following Syntax.
function functionName(parameters) {
// code which we have be execut.
}
Declared functions are not executed immediately. Instead, they are saved for later use and executed later when invoked (called upon). Let us see below given an example to understand it better:
Example:
function myFunction(a, b) {
return a + b;
}
var z = myFunction(7, 5);
Here 12 will be stored in z as it is calling function to add 7 and 5.
Function Expressions:
A JavaScript function can also be defined using an expression. A function expression can be stored in a variable. After a function expression has been stored in a variable, the variable can be used as a function. Let us see below given an example to understand it better:
Example:
var x = function (a, b) {return a + b};
var z = x(7, 5);
Here 12 will be stored in z as it is calling function stored in x to add 7 and 5.
Please note the function above is actually an anonymous function (a function without a name). Functions stored in variables do not need function names. They are always invoked using the variable name.
Functions by new Keyword:
Functions can also be defined with a built-in JavaScript function constructor called Function(). Let us see below given an example to understand it better:
Example:
var x = new Function("a", "b", "return a + b");
var z = x(7, 5);
This is similar to using var x = function (a, b) {return a + b}; So here again 12 will be stored in z.
Function Parameters and Arguments:
Function parameters are the names listed in the function definition. Function arguments are the real values passed to (and received by) the function. JavaScript function definitions do not specify data types for parameters. Also, JavaScript functions do not perform type checking on the passed arguments, and the number of arguments received.
Example:
function functionName(parameter1, parameter2, parameter3) {
// code which we will be executed
}
If a function is called with missing arguments (less than declared), the missing values are set to undefined.
Try the following example in the editor below.
You are given three numbers. You have to implement one function which will return the product of those numbers. Please note that you don’t have to print values, implement the function which takes three parameters and return the product as mentioned in the editor below.