Category: Functions

  • Function Hoisting

    Function Hoisting

    The function hoisting in JavaScript is a default behavior in which function declarations are moved at the top of their local scope before execution of the code. So, you can call the function in its scope before it is declared. It’s important to notice that only declaration is hoisted not the initialization. So the variables or functions should have been initialized before they are used.

    Similar to the function hoisting, the variable hoisting is also a default behavior in which the variable declarations are moved at the top of their local scope. We can use the function before it has been declared.

    Let’s consider the following JavaScript code.

    add(5,10);// 15functionadd(x, y){return x + y;}

    In the above JavaScript code, the function add is called before it’s declaration. This is possible because JavaScript interpreter hoists the function declaration to the top of the scope. So the above code is equivalent to

    functionadd(x, y){return x + y;}add(5,10);// 15

    The function hoisting only works with function declaration not with function expression. So, if the function is defined using the function expression,., it is not hoisted at the top.

    add(5,10);// ReferenceError: Cannot access 'add' before initializationconstadd=function(x, y){return x + y;}

    Let’s write some complete JavaScript examples of function hoisting.

    Example: Function Hoisting

    In the example below, we have defined the printMessage() function, printing the position from where it is called.

    Also, we call the printMessage() function before and after the function definition. It prints the output without any error as the function is hoisted at the top of its scope.

    <html><body><p id ="output"></p><script>printMessage("Top");functionprintMessage(pos){
    
         document.getElementById("output").innerHTML +="The function is called from the "+ pos +"&lt;br/&gt;";}printMessage("Bottom");&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The function is called from the Top
    The function is called from the Bottom
    

    Example

    In the example below, we have defined the function inside the 'if' block. So, the function is hoisted at the top of the 'if' block, and you can execute the function only inside the 'if' block before its initialization.

    You can't access the function outside the 'if' block.

    <html><body><p id ="output"></p><script>// test("Top"); // Out of scopeif(1){test("Top");// In the same scopefunctiontest(pos){
    
            document.getElementById("output").innerHTML +="The function is called from the "+ pos +"&lt;br/&gt;";}test("Bottom");// In the same scope}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The function is called from the Top
    The function is called from the Bottom
    

    The hoisting is very important behavior in JavaScript. But it is always advisable to declare the function or variable at the beginning of the code. Since JavaScript always interprets the code in sequence of declaration, then initialization and then usage.

    JavaScript Variable Hoisting

    The hoisting behaviors of JavaScript move the variables declaration to the top of the variable's scope by default. In JavaScript, variables declared with the 'var' keyword are hoisted at the top of its scope, but variables declared with the 'let' and 'const' keyword is not hoisted at the top.

    For example,

    var x = y;var y;

    The above code is similar to the below code, as the variables declaration is hoisted at the top.

    var y;var x = y;

    Let's understand the variable hoisting by following examples.

    Example: Variable Hoisting

    In the example below, we have initialized the variable y, printed its value in the output, and declared it at the end. The below code prints a value without any error, as variable y is hoisted at the top in the global scope.

    <html><head><title> JavaScript - Variable Hoisting </title></head><body><p id ="output"></p><script>
    
      y =10;
      document.getElementById("output").innerHTML ="The value of the y is : "+ y;var y;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of the y is : 10
    

    Example: Variable Hoisting with Function

    In the example below, we have defined the printNum() function. In the printNum() function, we have initialized the variable y, printed its value, and declared it afterward.

    The variable y is hoisted at the top of the function so you can access it before its declaration, but you can't access it outside the function.

    <html><head><title> JavaScript - Variable Hoisting withfunction</title></head><body><p id ="output"></p><script>const output = document.getElementById("output");functionprintNum(){
    
         y =20;
         output.innerHTML +="The value of the variable y is : "+ y;var y;// Function scope}printNum();// Variable Y can't be accessible here&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of the variable y is : 20
    

    However, variable initialization is not hoisted at the top of the block.

    Example: variable initialization is not hoisted

    The example below demonstrates that the variable is hoisted at the top, but the variable initialization is not. Here, we print the variable x without initialization of it. So, it prints the 'undefined' in the output.

    <html><body><p id ="output"></p><script>var x;
    
      document.getElementById("output").innerHTML ="x is -&gt; "+ x;
      x =10;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    x is -> undefined
    

    Example: Hoisting with let and const keywords

    The below example demonstrates that the variable declared with the 'let' and 'const' keywords are not hoisted at the top. So, you always need to define it before using it.

    We used the 'trycatch' block to handle the error. In the output, users can observe the error the below code gives when we access the variable declared with the 'let' keyword.

    <html><head><title> Hoisting withlet and const</title></head><body><p id ="output"></p><script>const output = document.getElementById("output");try{
    
         x =10;
         output.innerHTML +="The value of x is -&gt; "+ x;let x;}catch(error){
         output.innerHTML += error.message;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Cannot access 'x' before initialization
    

  • Function() Constructor

    The Function() Constructor

    The JavaScript Function() constructor can dynamically create a function object at the run time. The functions created using Function() constructor have global scope only.

    The Function() constructor can be used to define the function at the run time, but you should use the Function() constructor with caution as it can lead to vulnerabilities in the code.

    We can pass multiple arguments to the Function() constructor. All arguments except the last argument are the names of the parameters in the new function to be created. The last argument is the function body.

    Syntax

    Following is the syntax to use the Function() constructor to create an object of the function in JavaScript

    const obj =newFunction(arg1, arg2..., functionBody);

    The Function() constructor can be called with or without new keyword to create a new function object. All the parameters are JavaScript strings.

    Parameters

    • arg1, arg2… − These are arguments (optional) names that are used in function body. These are treated as the names of parameters in the function to be created.
    • functionBody − This argument contains the JavaScript statements comprising the function definition.

    Example

    In the example below, we have passed the 3 arguments to the Function() constructor. The first 2 arguments are arguments for the func() function, and the third is a body of the func() function.

    In the output, the func() function returns the multiplication of 5 and 7.

    <html><body><p id ="output"></p><script>const func =newFunction("p","q","return p * q");
    
      document.getElementById("output").innerHTML ="The value returned from the function is: "+func(5,7);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value returned from the function is: 35
    

    Example

    In the example below, we passed the one argument to the Function() constructor. So, it considers it as the function body. All the parameters except the last one are optional.

    In the output, you can observe that the func() function returns the sum of 10 and 20.

    <html><body><p id ="output"></p><script>const func =newFunction("return 10 + 20");
    
      document.getElementById("output").innerHTML ="The value returned from the function is: "+func();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value returned from the function is: 30
    

    Function Declaration or Function Expression as Parameter

    Creating function using Function constructor is less efficient than creating function using a function declaration or function expression and calling it within the code.

    We can write multiple statements in the functionBody parameter of the Function() constructor. All statements are separated by semicolons. We can create a function with function declaration or function expression and pass it as a statement in the fucntionBody parameter.

    Example

    In this example, we defined a function sum with function expression and passed to the Function() constructor as a part of the parameter (functionBody). Here the return statement is required.

    <html><body><p id ="output"></p><script>const add =newFunction("const sum = function (a, b) {return  a+ b};  return sum",)();    
    
      document.getElementById("output").innerHTML =add(5,10)// 15&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example

    In this example, we defined a function anonymous function with function declaration and passed to the Function() constructor as a part of the parameter (functionBody). Here the return statement at the end is not required.

    <html><body><p id ="output"></p><script>const sayHello =newFunction("return function (name) { return Hello, ${name} }",)();    
    
      document.getElementById("output").innerHTML =sayHello("world");// Hello, world&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Please note that in both the examples above, the new Function is self-invoked.

  • Default Parameters

    The default parameters in JavaScript are a feature that allows you to specify a default value for a function parameter. The concept of the default parameters was introduced in the ES6. We can initialize the parameters with the default values. So, if the function is called with missing argument or argument with an undefined value, it uses the default value of the parameter in the function.

    The default value of a function parameter is “undefined” in JavaScript. When a function is called with missing arguments the parameters are set to ‘undefined’. The undefined parameter values are acceptable but can generate unusual outcomes.

    Before the ES6 version of JavaScript, we needed to check whether the parameter value was “undefined” inside the function body. If yes, they need to initialize the parameter with the proper value.

    Let’s understand it via the example below.

    functionsum(p, q){return p + q;}sum(10,20);// 30sum(10);// NaNsum();// NaN

    In this example, we observe the following −

    • sum(10, 20) returns the sum of the two arguments, i.e., 30. Here both arguments are passed.
    • sum(10) returns NaN. Here only one argument is passed. The second parameter q is set to undefined. Mathematical operation on undefined returns NaN.
    • sum() also returns NaN. Here both arguments are missing. So they are set to undefined.

    When we call the function with missing argument values, it returns NaN which is unusual.

    To overcome this problem, we can use default parameter values to be used if function is called with missing argument values.

    Default Parameters Syntax

    The syntax to use the function default parameters in JavaScript is as follows

    functionfunctName(param1 = defaultValue1, param2 = DefaultValue2, ..){// Use parameters here}

    In the above syntax, the default value of the param1 is set to defaultValue1, and the default value of the param2 is set to defaultValue2.

    Let’s look at the example below −

    Example (Default parameters)

    In the below code, parameter p and q contains the 30 and 40 default values, respectively.

    In the output, unlike the first example, you can see that it returns the sum of the default parameter values when any argument is missing.

    <html><body><p id ="output"></p><script>let output = document.getElementById("output");functionsum(p = 30, q = 40){return p + q;}
    
      output.innerHTML +="sum(10, 20)  -&gt;  "+sum(10,20)+"&lt;br&gt;";// 10 + 20 = 30
      output.innerHTML +="sum(10)  -&gt;  "+sum(10)+"&lt;br&gt;";// 10 + 40 = 50
      output.innerHTML +="sum()  -&gt;  "+sum()+"&lt;br&gt;";// 30 + 40 = 70&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    sum(10, 20) -> 30
    sum(10) -> 50
    sum() -> 70
    

    Passing an expression as a default parameter value

    We can pass an expression as a default parameter value to a JavaScript function. The expression can also contain the values of the previous parameters.

    Example

    We pass the expression as a default parameter value in the code below. The expression contains the value of the previous parameters.

    In the output of the second function call, you can observe that the value of the r is 100, which is equal to (p = 5) * (q = 10) * 2. We haven't passed any argument in the third function call, so all parameters take the default value.

    <html><body><p id ="output"></p><script>let output = document.getElementById("output");functionsum(p = 2, q = p * 2, r = p * q * 2){return p + q + r;}
    
      output.innerHTML +="sum(5, 10, 15)  -&gt;  "+sum(5,10,15)+"&lt;br&gt;";// 5 + 10 + 15 = 30
      output.innerHTML +="sum(5, 10)  -&gt;  "+sum(5,10)+"&lt;br&gt;";// 5 + 10 + (5 * 10 * 2) = 115
      output.innerHTML +="sum()  -&gt;  "+sum()+"&lt;br&gt;";// 2 + 4 + 16 = 22&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    sum(5, 10, 15) -> 30
    sum(5, 10) -> 115
    sum() -> 22
    

    You can't use the uninitialized parameter in the expression. Otherwise, the code will raise a reference error.

    Passing Undefined Argument

    When you pass the undefined argument to the function call, the JavaScript function definition uses the default parameter values to avoid unnecessary errors.

    <html><body><p id="output"></p><script>let output = document.getElementById("output");functionsum(p = 24, q = 26){return p + q;}
    
    
      output.innerHTML +="sum(5, undefined)  -&gt;  "+sum(5,undefined)+"&lt;br&gt;";// 5 + 26 = 31 
      output.innerHTML +="sum(undefined)  -&gt;  "+sum(undefined)+"&lt;br&gt;";// 24 + 26 = 50&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    sum(5, undefined) -> 31
    sum(undefined) -> 50
    

    Function expression as a default parameter

    The JavaScript function expression can also be paased as a fucntion default parameter.

    In the example below, the getNum() function returns 5. We used the function expression as a default value of parameter q.

    The output shows that when the second argument is missing, the parameter uses the value returned from the getNum() function.

    <html><body><p id ="output"></p><script>let output = document.getElementById("output");functiongetNum(){return5;}functionmul(p = 5, q = getNum()){return p * q;}
    
    
      output.innerHTML +="mul(10)  -&gt; "+mul(10)+"&lt;br/&gt;";
      output.innerHTML +="mul() -&gt; "+mul()+"&lt;br/&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    mul(10) -> 50
    mul() -> 25
    

    Function Optional Parameters

    The function default parameters are also called the optional parameters, as the function will give output without any error even if we don't pass the arguments for the optional parameter.

    You should pass all required parameters at the start and optional parameters at the function end.

    functionsum(p, q=10){return p+q;}

    In the above JavaScript code snippet, we put the optional parameter q at the end of the parameter list.

    Example

    The JavaScript code below shows that the first parameter is required, and the second parameter is optional.

    <html><body><p id ="output"></p><script>let output = document.getElementById("output");functionfunc(p, q=10){return p + q;}
    
      output.innerHTML +="func(10, 20) -&gt; "+func(10,20);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    func(10, 20) -> 30
    

    If we put the optional parameter at beginning, we may encounter error while calling the function with undefined value.

    functionsum(p=10, q){return p+q;}sum(,10)// Errorsum(10)// NaN

    So, if you pass only a single argument, it replaces the default value of the first parameter, and the second parameter remains undefined.

  • Function Parameters

    Function Parameters and Arguments

    The function parameters in JavaScript are variables listed inside the parentheses in the function definition. A function can have multiple parameters separated by commas. The function arguments are the values that are passed to function when it is called. We define function listing the parameters and call the function passing the arguments.

    The number of arguments that you pass to the function must match the number of parameters in the function definition. If not, you may get unexpected result.

    Syntax

    The syntax to use function parameters in JavaScript is as follows −

    functionfunctionName(parameter1, parameter2, parameter3){//statements}

    In the above syntax, the function parameters are ‘parameter1’, ‘parameter2’, and ‘parameter3’.

    Parameter Rules

    • JavaScript functions don’t check the number of arguments passed while invoking the function.
    • Don’t need to specify the data type of function parameters.
    • JavaScript compiler doesn’t perform the type-checking on the passed function arguments.

    The JavaScript function arguments are the variables or values passed to the function while invoking it.

    functionName(10, b,'Hello');

    In the above syntax, the first argument is of number data type, and the third is of string data type. The second argument is variable, which is defined earlier in the code.

    Example: Function Parameters and Arguments

    In the below code, the mult() function takes 4 parameters. You can observe that the type of parameters is not defined. We multiply the parameter values in the function body and return the resultant value.

    While calling the function, we passed 4 number values as a function argument. Users can observe the output of the function for the different function arguments.

    <html><body><p id ="output"></p><script>functionmult(a, b, c){let res = a * b * c;return res;}let ans =mult(2,3,4);
    
      document.getElementById("output").innerHTML ="The multiplication of 2, 3, and 4 is "+ ans;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The multiplication of 2, 3, and 4 is 24
    

    Argument Object

    In JavaScript, each function can have an 'arguments' object. It contains all passed arguments while invoking the function in the array format. We can traverse through the array and get each argument even if the function's parameters are not specified.

    Example

    In the example below, the function definition doesn't contain any parameters, but we have passed the 4 arguments while calling the function. So, we traverse through the arguments[] array using the loop inside the function body to access all arguments one by one.

    In the function body, we merge all arguments and return the 'final' string.

    <html><body><p id ="output"></p><script>functionmerge(){let final ="";for(let p =0; p < arguments.length; p++){
    
            final += arguments[p]+" ";}return final;}let ans =merge("Hi","I","am","John!");
      document.getElementById("output").innerHTML ="The merged string is: "+ ans;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The merged string is: Hi I am John!
    

    Passing Arguments by Value

    In the function, when you pass the argument by value to a function call, it sends the argument value to the parameter of the function definition. So, when you update the function parameters, the function argument doesn't get changed.

    Example

    In the below code, we have defined the 'val1' and 'val2' variables outside the function and passed them as a function argument.

    In the function body, we change the parameter value. In the output, you can see that even after updating the parameter value, the actual value of the 'val1' and 'val2' is not changed.

    <html><head><title> JavaScript - Arguments are passed by value </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");functionupdate(val1, val2){
    
         val1 =20;
         val2 =30;}var val1 ="Hello";var val2 ="World";
      output.innerHTML +="Before calling the function! &lt;br&gt;";
      output.innerHTML +="val1 = "+ val1 +", val2 = "+ val2 +"&lt;br&gt;";update(val1, val2);
      output.innerHTML +="After calling the function! &lt;br&gt;";
      output.innerHTML +="val1 = "+ val1 +", val2 = "+ val2 +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Before calling the function!
    val1 = Hello, val2 = World
    After calling the function!
    val1 = Hello, val2 = World
    

    Passing Arguments by Reference

    When you pass the object as an argument, the function sends the address of the object as a parameter to the function definition. So, it is called the arguments are passed by reference.

    In the function body, if you change the property of an object, it will also reflect the outside of the function.

    Example

    In the below code, we pass the 'obj' object as a function argument. In the function body, we change the value of the 'domain' property of the object.

    In the output, you can observe that the value of the 'domain' property is changed even outside the function after invoking the function as objects are passed by reference.

    <html><head><title> JavaScript - Arguments are passed by reference </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");functionupdate(obj){
    
         obj.domain ="www.tutorialspoint.com";}var obj ={
         domain:"www.google.com",}
      output.innerHTML +="Before calling the function! &lt;br&gt;";
      output.innerHTML +="domain = "+ obj.domain +"&lt;br&gt;";update(obj);
      output.innerHTML +="After calling the function! &lt;br&gt;";
      output.innerHTML +="domain = "+ obj.domain +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Before calling the function!
    domain = www.google.com
    After calling the function!
    domain = www.tutorialspoint.com
    

  • Function Expressions

    The function expression allows us to define a JavaScript function in an expression. JavaScript functions are defined using a function declaration or a function expression. The main difference between them is the function name. The function name can be omitted in function expressions. This helps to create anonymous functions in JavaScript. We can store the function expression in the variable and use that variable to invoke the function expression.

    Syntax

    The syntax of function expression in JavaScript is as follows

    function(parameter-list){
    
    statements
    };

    We can use a variable to store a JavaScript function expression

    constvarName=function(parameter-list){
    
    statements
    };

    Here the function expression is stored in the variable, varName. Once the function is assigned to a variable, the variable is used to invoke the function. Lets look at the example below

    constsum=function(x, y){return x + y;};let z =sum(2,3);

    In the above code the function expression is assigned to the variable sum. The variable sum is used as function to invoke the function.

    Please note there is no name after the function keyword. The function expression allows to define anonymous function.

    Named Function Expression

    We can define a named function as a function expression

    constsum=functionaddNumbers(x, y){return x + y;};let z =sum(2,3);

    But we need to invoke the function using the variable only. We cant use the function name to invoke the function.

    Immediately Invoked Function Expression

    A function expression can be used as the IIFE (immediately invoked function expression) which is invoked as soon as defined.

    (functiongreet(){alert("Hello World");})();

    Examples

    Example: Function Expression

    In the example below, we stored the function expression in the sum variable. The function expression adds two numbers and prints in the output.

    At last, we used the sum variable to invoke the function expression stored in that.

    <html><body><p id ="output"></p><script>constsum=function(){let a =10;let b =20;
    
         document.getElementById("output").innerHTML ="The sum of "+ a +" and "+ b +" is "+(a + b);}sum();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The sum of 10 and 20 is 30
    

    Example: The return statement in function expression

    The below code demonstrates the using the return statement in the function expression. You can use the return statement inside the function expression as you use it in the function definition.

    In the below code, the function returns the multiplication value of two numbers.

    <html><body><p id ="output"></p><script>constmul=function(a, b){return a * b;}let result =mul(4,5);
    
      document.getElementById("output").innerHTML ="The returned value from the function is "+ result;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The returned value from the function is 20
    

    Example: Using the function expression as a value

    The below example demonstrates using the function expression as a value. Here, we stored the function expression in the num variable and multiplied its returned value by 3.

    You may return the random number from the function expression and use the function expression as a value.

    <html><body><p id ="output"></p><script>constnum=function(){return2;}let result =num()*3;
    
      document.getElementById("output").innerHTML ="The multiplication value is "+ result;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The multiplication value is 6
    

    Example: Nested function expression

    The example below demonstrates using the nested function expression. We defined the function expression and stored it in the num variable. In the function expression body, we defined another function expression and stored it in the decimal variable.

    We call the decimal() function expression in the parent function expression and return its value. When we call the num() function expression, it returns the value returned by the decimal() function expression.

    <html><body><p id ="output"></p><script>constnum=function(){constdecimal=function(){return5;}returndecimal();}
    
      document.getElementById("output").innerHTML ="The returned value from the function is "+num();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The returned value from the function is 5
  • Functions

    function in JavaScript is a group of reusable code that can be called anywhere in your program. It eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions.

    Like any other advanced programming language, JavaScript also supports all the features necessary to write modular code using functions. You must have seen functions like alert() and write() in the earlier chapters. We were using these functions again and again, but they had been written in core JavaScript only once.

    JavaScript allows us to write our own functions as well. This section explains how to write your own functions in JavaScript.

    Function Definition

    Before we use a function, we need to define it. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.

    All statements you need to execute on the function call must be written inside the curly braces.

    Syntax

    The basic syntax to define the function in JavaScript is as follows −

    functionfunctionName(parameter-list){
    
    statements
    }

    This type of function definition is called function declaration or function statement. We can also define a function using function expression. We will discuss function expression in details in the next chapter.

    The following example defines a function called sayHello that takes no parameter −

    functionsayHello(){alert("Hello there");}

    Function Expression

    The Function expression in JavaScript allows you to define a function as an expression. The function expression is similar to the anonymous function declaration. The function expression can be assigned to a varaible.

    The syntax of function expression in JavaScript is as follows

    constvarName=function(parameter-list){
    
    statements
    };

    In the example below, we have defined a JavaScript function using function expression and assigned it to a vriable name myFunc.

    constmyFunc=function(x, y){return x + y;};

    Calling a Function

    To invoke a function somewhere later in the script, you would simply need to write the name of that function with the parantheses () as shown in the following code.

    Example

    The below code shows the button in the output. When you click the button, it will execute the sayHello() function. The sayHello() function prints the “Hello there!” message in the output.

    <html><head><script type="text/javascript">functionsayHello(){alert("Hello there!");}</script></head><body><p>Click the following button to call the function</p><form><input type="button" onclick="sayHello()" value="Say Hello"></form><p> Use different text in the write method and then try...</p></body></html>

    Function Parameters

    Till now, we have seen functions without parameters. But there is a facility to pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters. A function can take multiple parameters separated by comma.

    Example

    Try the following example. We have modified our sayHello function here. Now it takes two parameters.

    <html><head><script type ="text/javascript">functionsayHello(name, age){
    
            document.write(name +" is "+ age +" years old.");}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;Click the following button to call the function&lt;/p&gt;&lt;form&gt;&lt;input type ="button" onclick ="sayHello('Zara', 7)" value ="Say Hello"&gt;&lt;/form&gt;&lt;p&gt;Use different parameters inside the function and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    The return Statement

    A JavaScript function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function.

    For example, you can pass two numbers in a function, and then you can expect the function to return their multiplication in your calling program.

    Example

    The code below defines a function that concatenates two parameters before returning the resultant in the calling program. Also, you may take a look that how it returns the value using the return statement.

    <html><head><script type="text/javascript">functionconcatenate(first, last){var full;
    
         full = first + last;return full;}functionsecondFunction(){var result;
         result =concatenate('Zara ','Ali');alert(result);}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;Click the following button to call the function&lt;/p&gt;&lt;form&gt;&lt;input type="button" onclick="secondFunction()" value="Call Function"&gt;&lt;/form&gt;&lt;p&gt;Use different parameters inside the function and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Functions as Variable Values

    In JavaScript, functions can be used same as other variables. Thats why JavaScript is said to have a first-calss functions. The functions can be passed as arguments to the other functions.

    Example

    In the example below, we have declared a function using function expression and use the function to concatenate with other string.

    <html><body><div id ="output"></div><script>constmyFunc=function(){return"Hello ";};
    
      document.getElementById("output").innerHTML =myFunc()+"Users.";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    We have covered two important concepts in separate chapters.

    • JavaScript Nested Functions
    • JavaScript Function Literals