You are currently viewing What is Javascript Function Expression with Examples

What is Javascript Function Expression with Examples

 Javascript function expression

In this article, we will what is javascript function expression with examples

Function Expression

A function defined with function expression begins with the var keyword.

Syntax: /*function definition*/
var functionName = function( [parameter 1, parameter 2, ..... parameter N]) // function header
{
statement(s);
[retrun returning Value] //by default a funciton returns undefined value
};
  1. You can observe the function header syntax, first, we use the “var” keyword and then we give a function name.
  2. Then put is equal to (=) sign for assign the value to function and Write “function()” keyword.
  3. If you pass a parameter to a function, you must pass the arguments while calling the function. If parameters are empty you can pass arguments.
  4. Then open the curly braces inside it, and we can write the statement and return the value.
  5. Finally, we put the semicolon after closing the function curly braces.

Note: function get executed only when we call them

Syntax: /* function call */
functionName([parameter 1, parameter 2, ..... parameter N]);

Example code

A function without parameters, without returning value

var wishHi = function()
{
document.write("Hello World !", "<br/>");
}
wishHi();

/*
Output:
Hello World !
*/

A function with parameters and returning value

var add = function(num1, num2)
{
return num1+num2;
}
document.write(add(4,8));

/*
Output:
12
*/

Here,We create a function called “add()” with 2 parameters. Add those two values ​​into the function and return. Then we print the add() function and give two arguments value as ​​(4,8). So the two values ​​are added and the output display is 12.

 

Leave a Reply