JavaScript – Function Invocation

JavaScript – Function Invocation ”; Previous Next Function Invocation The function invocation in JavaScript is the process of executing a function. A JavaScript function can be invoked using the function name followed by a pair of parentheses. When you write a function code in JavaScript, it defines the function with expressions and statements. Now, to evaluate these expressions, it is necessary to invoke the function. The function invocation is the synonym of the function call or function execution. A JavaScript function can be defined using function declaration or function expression. The code inside the curly braces in the function definition are not executed when function is defined. To execute the code, we need to invoke the function. The call a function and invoke a function are two interchangeable terms are commonly used. But we can invoke a function without calling it. For example, self-invoking functions are invoked without calling them. Syntax The syntax of function invocation in JavaScript is as follows – functionName() OR functionName(arg1, arg2, … argN); Here ”functionName” is the function to be invoked. We can pass as many arguments as the number of parameters listed in function definition. Example In the example below, we have defined the merge() function taking two parameters. After that, we used the function name to invoke the function by passing the arguments. <html> <body> <p id = “output”> </p> <script> function merge(str1, str2) { return str1 + str2; } document.getElementById(“output”).innerHTML = merge(“Hello”, ” World!”); </script> </body> </html> Output Hello World! Invocation of Function Constructor When you invoke a function with the ”new” keyword, it works as a function constructor. The function constructor is used to create an object from the function definition. Syntax Following is the syntax to invoke the function as a constructor. const varName = new funcName(arguments); In the above syntax, we invoked the function with a ”new” keyword and passed the arguments. Example In the example below, we use the function as an object template. Here, the ”this” keyword represents the function object, and we use it to initialize the variables. After that, we invoke the function car with the ”new” keyword to create an object using the function template. <html> <body> <p id = “output”> The ODCar object is: </p> <script> function Car(name, model, year) { this.name = name; this.model = model; this.year = year; } const ODCar = new Car(“OD”, “Q6”, 2020); document.getElementById(“output”).innerHTML += JSON.stringify(ODCar); </script> </body> </html> Output The ODCar object is: {“name”:”OD”,”model”:”Q6″,”year”:2020} Object Method Invocation We haven”t covered JavaScript objects yet in this tutorial but we will cover it in upcoming chapters. Here, let”s learn the object method invocation in short. The JavaScript object can also contain the function, and it is called the method. Syntax Following is the syntax below to invoke the JavaScript object method. obj.func(); In the above syntax, the ”obj” is an object containing the method, and ”func” is a method name to execute. Example In the example below, we have defined the ”obj” object containing the ”name” property and the ”getAge()” method. Outside the object, we access the method by the object reference and invoke the method. In the output, the method prints 10. <html> <body> <p id = “output”>The age of John is: </p> <script> const obj = { name: “John”, getAge: () => { return 10; } } document.getElementById(“output”).innerHTML += obj.getAge(); </script> </body> </html> Output The age of John is: 10 Self-Invoking Functions The self-invoking functions in JavaScript are executed just after they are defined. There is no need to call these types of function to invoke them. The self-invoking functions are always defined using anonymous function expression. These types of functions are also called immediately invoked function expressions (IIFEs). To invoke these function, we wrap the function expression within a grouping operator (parentheses) and then add a pair of parentheses. Example Try the following example. In this example, we define a function to show a “Hello world” message in alert box. <html> <head> <script> (function () {alert(“Hello World”)})(); </script> </head> <body> </body> </html> Other methods to invoke the function JavaScript contains two special methods to invoke the function differently. Here, we have explained each method in the table below. Method Function invocation Arguments Call() Immediate invocation Separate arguments Apply() Immediate invocation Array of arguments The difference between the call() and apply() method is how it takes the function arguments. We will learn each of the above methods with examples in the next chapters one by one. Print Page Previous Next Advertisements ”;

JavaScript – Comma Operator

JavaScript – Comma Operator ”; Previous Next JavaScript Comma Operator The comma operator (,) in JavaScript evaluates the multiple expression from left to right. You can use the resultant value of the left expression as an input of the right expression. After evaluating all expressions, it returns the resultant value of the rightmost expression. However, the comma operator is also used in the ”for” loop, array, object, etc. In this chapter, you will learn all the use cases of the comma operator. Syntax You should follow the below syntax to use the comma expression to evaluate multiple expressions. var answer = (exp1, exp2, exp3, ex4, …); Return value It returns the resultant value of the last expression only. Examples Let”s understand the JavaScript comma operator in details with the help of some exmaples Example: The Comma Operator with Strings In the example below, we have added the 4 comma seprated strings in the braces. Here, each string works as an expression. The code will evaluate the string and return the last string. In the output, you can see that it prints the ”CSS” as it is the rightmost string. <html> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); let ans = (“JavaScript”, “Python”, “HTML”, “CSS”); output.innerHTML = “The value of the ans variable is: ” + ans; </script> </body> </html> Example: The Comma Operator with Expressions In the example below, we have defined the variable ”a” and initialized it with 5. In the ”ans” variable, we store the resultant value the comma operator returns. The first expression updates the value of a to 8, the second expression increments the value of a by 1, and the third expression adds 2 to the updated value of the variable ”a”. The value of the ”ans” is 11, which is returned by the rightmost expression of the comma operator. <html> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); let a = 5; let ans = (a = 8, a++, a += 2); output.innerHTML = “The value of the ans variable is: ” + ans; </script> </body> </html> Example: The comma operator with functions In the example below, we have defined the first() and second() functions. Also, it prints the message and returns the value from the function according to the function name. We use the comma operator to execute the multiple functions. In the output, you can see that it invokes both functions but prints the returned value from the second() function only. <html> <body> <p id=”output”> </p> <script> let output = document.getElementById(“output”); function first() { output.innerHTML += “The first function is called! <br/>”; return 1; } function second() { output.innerHTML += “The second function is called! <br/>”; return 2; } let ans = (first(), second()); output.innerHTML += “The value of the ans variable is: ” + ans; </script> </body> </html> Other Use Cases of The Comma Operator For defining the multiple variables in a single row. let m = 1, n = 2, x = 3; To initialize the array with multiple elements. const arr = [10, 20, 30, 40, 50, 60]; For defining the object with multiple properties. const obj = { name: “tutorialspoint”, age: 10, … other properties } You can use the comma operator for loop to initialize or update multiple variables in each iteration. for(let p = 0, q = 1; p < n; p++, q++) { // Code for the loop } To pass multiple parameters of arguments into the functions. function func(param1, param2, … ) { // function code } OR func(10, 20, 30, …); To import or export import { func2, variable } from ”./module2.js”; OR export {func1, variable, num}; To destructure arrays of objects. let [a, b, c] = [34, 72, 23]; To print multiple variables in the console. console.log(a, b, c) // a, b, and c are variables. Print Page Previous Next Advertisements ”;

JavaScript – Function Expressions

JavaScript – Function Expressions ”; Previous Next 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 – const varName = 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. Let’s look at the example below – const sum = 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 – const sum = function addNumbers(x, y) { return x + y; }; let z = sum(2, 3); But we need to invoke the function using the variable only. We can’t 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. (function greet() { 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> const sum = function () { let a = 10; let b = 20; document.getElementById(“output”).innerHTML = “The sum of ” + a + ” and ” + b + ” is ” + (a + b); } sum(); </script> </body> </html> 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> const mul = function (a, b) { return a * b; } let result = mul(4, 5); document.getElementById(“output”).innerHTML = “The returned value from the function is ” + result; </script> </body> </html> 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> const num = function () { return 2; } let result = num() * 3; document.getElementById(“output”).innerHTML = “The multiplication value is ” + result; </script> </body> </html> 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> const num = function () { const decimal = function () { return 5; } return decimal(); } document.getElementById(“output”).innerHTML = “The returned value from the function is ” + num(); </script> </body> </html> Output The returned value from the function is 5 Print Page Previous Next Advertisements ”;

JavaScript – Function call()

JavaScript – Function call() Method ”; Previous Next Function call() Method The Function call() method allows us to invoke a function given a specific value for this and arguments provided individually. When a normal function is called, the value of this inside the function is the object that the function was accessed on. We can manipulate the this value and can assign an arbitrary object to this by using the call() method. In other word, we can call existing function as a method of an object without attaching the function to the object as a method. In JavaScript, every function is a Function object. The Function object provides properties and methods for functions. These properties and methods are defined on Function.prototype and shared by all Function instances. Some of the important methods provided by the Function object are call(), apply() and bind() methods. Let us understand the syntax of the Function call() method. Syntax The syntax of Function call() method in JavaScript is as follows − funcName.call(thisArg, arg1, arg2, … argN); In the above syntax, the ”funcName” is the name of the function to be called. Parameters thisArg − It represents the context for the function. It is an object whose properties or methods we need to access using the ”this” keyword inside the function. arg1, arg2, … argN − It is N arguments to pass to the function. They are optional arguments. By default, the context of the function is a global (window) object. So, the ”this” keyword refers to the ”window” object. Return value The call() method returns the value returned from the function. Examples Let”s understand JavaScript Function call() method with the help of some examples. Function call() method without specifying arguments In the example below, we have defined the test() function. We have invoked the function using the function name and call() method. In both cases, the function prints the same output. So, when you don”t pass any arguments, the call() method gives the same output as a normal function call. <html> <head> <title> JavaScript – Function call() method </title> </head> <body> <p id = “output1”> </p> <p id = “output2”> </p> <script> function test() { return “The function is invoked!”; } document.getElementById(“output1”).innerHTML = test(); document.getElementById(“output2″).innerHTML = test.call(); </script> </body> </html> Output The function is invoked! The function is invoked! Function call() method with ”this” argument only As we discussed above, ”this” argument is used to specify the context of the function. Here, we have defined the person1 and person2 objects containing the name and age properties. We passed the object as an argument of the call() method. In the printMessage() function, we access the object”s properties, which is passed as a function argument using the ”this” keyword. In the output, you can observe that it prints the object properties” value according to the object passed as an argument of the call() method. <html> <head> <title> JavaScript – Function call() method </title> </head> <body> <p id = “output1”> </p> <p id = “output2”> </p> <script> function printMessage() { return “The age of the ” + this.name + ” is ” + this.age; } const person1 = { name: “John Doe”, age: 22, } const person2 = { name: “Jane Doe”, age: 40, } document.getElementById(“output1”).innerHTML = printMessage.call(person1); document.getElementById(“output2”).innerHTML = printMessage.call(person2); </script> </body> </html> Output The age of the John Doe is 22 The age of the Jane Doe is 40 Function call() method with multiple arguments The example below demonstrates passing multiple arguments to the call() method. The printSum() function returns the sum of function parameters and object properties in the below code. <html> <head> <title> JavaScript – Function call() method </title> </head> <body> <p id = “output”> </p> <script> function printSum(p1, p2) { return (this.num1 + this.num2 + p1 + p2); } const nums = { num1: 5, num2: 10, } const ans = printSum.call(nums, 40, 32); document.getElementById(“output”).innerHTML = “Total sum is ” + ans; </script> </body> </html> Output Total sum is 87 When you pass the ”this” keyword as the first argument of the call() method instead of an object, it specifies the function itself as a function context. Using a method of different object Using Function call() method, an object can use a method that is defined in other object. In the below example, we create three objects – student, student1 and student2. We define a method getAge() of the object student. This getAge() method is used by the other two objects (student1 and student2) to access the age. The objects student1 and student2 are passed as arguments to the call() method. <html> <head> <title> JavaScript – Function call() method </title> </head> <body> <p id = “output1”> </p> <p id = “output2”> </p> <script> const student = { getAge: function(){ return this.age; } } const student1 = { name: “John”, age: 22 } const student2 = { name: “Doe”, age: 18 } document.getElementById(“output1”).innerHTML =student.getAge.call(student1); document.getElementById(“output2″).innerHTML =student.getAge.call(student2); </script> </body> </html> The Function call() and apply() methods are the same but with minor difference as call() method accepts a list of arguments but the apply() method accepts an array of arguments. Let”s understand the Function apply() method in detail in the next chapter this tutorial. Print Page Previous Next Advertisements ”;

JavaScript – While Loop

JavaScript – While Loops ”; Previous Next A while statement in JavaScript creates a loop that executes a block of code repeatedly, as long as the specified condition is true. The condition is evaluated before the execution of the block of code. While writing a program, you may encounter a situation where you need to perform an action over and over again. In such situations, you would need to write loop statements to reduce the number of lines. JavaScript supports all the necessary loops to ease the pressure of programming. In this chapter, we will discuss the while loop. There are 2 kinds of while loops in JavaScript, as given below. Entry-controlled loops − The loop checks whether the looping condition is valid first and enters into the body of the loop to execute the loop statements. Exit-controlled loops − The loop enters into the body and executes the loop statements without checking the condition. After completing the iteration, it checks the condition. JavaScript while Loop The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The while loop is an entry-controlled loop. The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates. Flow Chart The flow chart of while loop looks as follows − Syntax The syntax of while loop in JavaScript is as follows − while (expression) { Statement(s) to be executed if expression is true } Example In the example below, we defined the ”count” variable and initialized it with 0. After that, we make iterations using the while loop until the value of the count is less than 10. <html> <body> <div id = ”output”></div> <script type=”text/javascript”> let output = document.getElementById(“output”); var count = 0; output.innerHTML=”Starting Loop <br>”; while (count < 10) { output.innerHTML+=”Current Count : ” + count + “<br>”; count++; } output.innerHTML+=”Loop stopped!”; </script> <p> Set the variable to a different value and then try… </p> </body> </html> Output Starting Loop Current Count : 0 Current Count : 1 Current Count : 2 Current Count : 3 Current Count : 4 Current Count : 5 Current Count : 6 Current Count : 7 Current Count : 8 Current Count : 9 Loop stopped! Set the variable to different value and then try… JavaScript do…while Loop The do…while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false. Flow Chart The flow chart of a do-while loop would be as follows − Syntax The syntax for do-while loop in JavaScript is as follows − do { Statement(s) to be executed; } while (expression); Don”t miss the semicolon used at the end of the do…while loop. Example In the example below, we used the do…while loop and printed the results in the output until the value of the count variable is less than 5. In the output, we can observe that it always executes for once, even if the condition is false. <html> <body> <div id=”output”></div> <script type=”text/javascript”> let output = document.getElementById(“output”); var count = 0; output.innerHTML += “Starting Loop” + “<br />”; do { output.innerHTML += “Current Count : ” + count + “<br />”; count++; } while (count < 5); output.innerHTML += “Loop stopped!”; </script> <p>Set the variable to a different value and then try…</p> </body> </html> Output Starting Loop Current Count : 0 Current Count : 1 Current Count : 2 Current Count : 3 Current Count : 4 Loop Stopped! Set the variable to different value and then try… JavaScript while vs. for Loops The JavaScript while loop is similar to the for loop with the first and third expressions omitted. A for loop is generally used when the number of iteration is fixed and known but we use the while loop whne the number of iterations is not known. Example Let”s take an example of printing the first five natural numbers using for loop − <html> <body> <p> First five natural numbers:</p> <div id = “demo”> </div> <script> const output = document.getElementById(“demo”); for(let i = 1; i <= 5; i++){ output.innerHTML += i + “<br>”; } </script> </body> </html> It will produce the following output − First five natural numbers: 1 2 3 4 5 Example We can now modify the above for loop as follows − <html> <body> <p> First five natural numbers:</p> <div id = “demo”> </div> <script> const output = document.getElementById(“demo”); let i = 1; for(; i <= 5; ){ output.innerHTML += i + “<br>”; i++ } </script> </body> </html> Output First five natural numbers: 1 2 3 4 5 Example In the above example, we have omitted first and third expression in for loop statement. This is similar to the while loop statement. Look at the below example − <html> <body> <p> First five natural numbers:</p> <div id = “demo”> </div> <script> const output = document.getElementById(“demo”); let i = 1; while(i <= 5){ output.innerHTML += i + “<br>”; i++ } </script> </body> </html> Output First five natural numbers: 1 2 3 4 5 You notice that the for loop without first expression (initialization) and third expression (iteration), is similar to the while loop. Print Page Previous Next Advertisements ”;

JavaScript – Hello World

JavaScript – Hello World Program ”; Previous Next Write “Hello World” Program in JavaScript “Hello, World!” is often the first program, programmers write when learning a new programming language. JavaScript “Hello World” is a simple program, generally used to demonstrate the basic syntax of the language. This program will make use of different JavaScript methods to print “Hello World”. Using document.write() In JavaScript, the simplest way to print “Hello World” is to use document.write() method. The document.write() method writes the content (a string of text) directly to the HTML document or web page. Let’s look at the following − <script> document.write(“Hello World) </script> We should write the document.write() within the <script> and </script> tags. We can place the <script> inside the <head> or <body> section. Example Let”s try to write a JavaScript program that prints the “Hello World!” to the document or web page. In the below program, we placed the JavaScript code within the <head> section. You can try to put the JavaScript part inside the <body> section and execute the program. <html> <head> <script> document.write(“Hello World”); </script> </head> <body> </body> <html> Using alert() method We can use the window alert() method to print “Hello Word” in a dialogue box. The alert() is a window method that instruct the browser to display an alert box with the message. We can write alert without passing any message to it. <script> alert(“Hello World”) </script> We can write alert() method as window.alert(). As window object is a global scope object, we can skip the “window” keyword. Example Let”s try an example showing “Hello World” in the alert box. Try to execute the program by putting the <script> part within the <body> section. <html> <head> <script> alert(“Hello World”); </script> </head> <body> </body> <html> Using console.log() The console.log() is a very convenient method to print the message to web Console. It is very useful to debug the JavaScript codes in the browsers. Let”s look at the simple application of the console.log() to print the “Hello World” to the web console. <script> Console.log(“Hello World”) </script> We can use the console.log to print strings or JavaScript objects. Here in above code snippet, we have passed “Hello World” as a string argument to the console.log() method. Example Let”s try to write a complete JavaScript program with HTML. <html> <head> <script> console.log(“Hello World”); </script> </head> <body> <p> Please open the console before clicking “Edit & Run” button </p> </body> <html> It will produce the following message in the web console − Hello World Using innerHTML The innerHTML property of an HTML element defines the HTML content of the element. We can use this property to display the Hello World message. By changing the innerHTML property of the element, we can display the message in HTML document or webpage. To use innerHTML property of an element, we need to access that element first. We can use document.getElementById() method to access the element. Let”s look at a complete example. Example In the example below, we define a div element with id, “output”. We access this element using the document.getElementById(“output”). Then we change the innerHTML property and display our message, “Hello World”. <html> <head> <title>Using innerHTML property</title> </head> <body> <div id = “output”> </div> <script> document.getElementById(“output”).innerHTML = “Hello World”; </script> </body> <html> Print Page Previous Next Advertisements ”;

JavaScript – Continue Statement

JavaScript – Continue Statement ”; Previous Next The continue statement in JavaScript is used to skip the current iteration of a loop and continue with the next iteration. It is often used in conjunction with an if statement to check for a condition and skip the iteration if the condition is met. The JavaScript continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop. Syntax The syntax of continue statement in JavaScript is as follows − continue; OR continue label; We can use the continue statement inside the loops like for loop, while loop, do…while loop, etc. We will learn to use the ‘continue’ statement with the ‘label’ statement in the upcoming chapter. Continue statement with for loop The example below uses the continue statement with the for loop. In the loop, when the value of the x is 3, it will execute the continue statement to skip the current iteration and move to the next iteration. In the output, you can see that the loop doesn’t print 3. Example <html> <head> <title> JavaScript – Continue statement </title> </head> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); output.innerHTML += “Entering the loop. <br /> “; for (let x = 1; x < 5; x++) { if (x == 3) { continue; // skip rest of the loop body } output.innerHTML += x + “<br />”; } output.innerHTML += “Exiting the loop!<br /> “; </script> </body> </html> Output Entering the loop. 1 2 4 Exiting the loop! Continue statement with while loop We used the while loop with the continue statement in the example below. In each iteration of the while loop, we increment the x”s value by 1. If the value of the x is equal to 2 or 3, it skips the current iteration and moves to the next iteration. In the output, you can see that the code doesn’t print 2 or 3. Example <html> <head> <title> JavaScript – Continue statement </title> </head> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); var x = 1; output.innerHTML += “Entering the loop. <br /> “; while (x < 5) { x = x + 1; if (x == 2 || x == 3) { continue; // skip rest of the loop body } output.innerHTML += x + “<br />”; } output.innerHTML += “Exiting the loop!<br /> “; </script> </body> </html> Output Entering the loop. 4 5 Exiting the loop! Continue statement with the nested loop You can use the continue statement with nested loops and skip the iteration of the parent loop or child loop. Example The parent loop traverses the 1 to 5 elements in the code below. In the parent loop, we used the continue statement to skip the iteration when the value of x is 2 or 3. Also, we have defined the nested loop. In the nested loop, we skip the loop iteration when the value of y is 3. In the output, you can observe the value of x and y. You won’t see 2 or 3 values for x and 3 for y. <html> <head> <title> JavaScript – Continue statement </title> </head> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); output.innerHTML += “Entering the loop. <br /> “; for (let x = 1; x < 5; x++) { if (x == 2 || x == 3) { continue; // skip rest of the loop body } for (let y = 1; y < 5; y++) { if (y == 3) { continue; } output.innerHTML += x + ” – ” + y + “<br />”; } } output.innerHTML += “Exiting the loop!<br /> “; </script> </body> </html> Output Entering the loop. 1 – 1 1 – 2 1 – 4 4 – 1 4 – 2 4 – 4 Exiting the loop! Print Page Previous Next Advertisements ”;

JavaScript – Function Parameters

JavaScript – Function Parameters ”; Previous Next 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 − function functionName (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> function mult(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; </script> </body> </html> 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> function merge() { 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; </script> </body> </html> 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”); function update(val1, val2) { val1 = 20; val2 = 30; } var val1 = “Hello”; var val2 = “World”; output.innerHTML += “Before calling the function! <br>”; output.innerHTML += “val1 = ” + val1 + “, val2 = ” + val2 + “<br>”; update(val1, val2); output.innerHTML += “After calling the function! <br>”; output.innerHTML += “val1 = ” + val1 + “, val2 = ” + val2 + “<br>”; </script> </body> </html> 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”); function update(obj) { obj.domain = “www.tutorialspoint.com”; } var obj = { domain: “www.google.com”, } output.innerHTML += “Before calling the function! <br>”; output.innerHTML += “domain = ” + obj.domain + “<br>”; update(obj); output.innerHTML += “After calling the function! <br>”; output.innerHTML += “domain = ” + obj.domain + “<br>”; </script> </body> </html> Output Before calling the function! domain = www.google.com After calling the function! domain = www.tutorialspoint.com Print Page Previous Next Advertisements ”;

JavaScript – Nested Destructuring

JavaScript – Nested Destructuring ”; Previous Next Nested Destructuring The Nested Destructuring in JavaScript allows us to extract data from nested objects and arrays. An object (or array) can contain another object (or array) inside itself, known as a nested object (or array). Unpacking the nested objects or arrays is called nested destructuring. We can extract all or some data from the objects or arrays using destructuring. We can assign the extracted data from nested array or object to the variables. This is referred as nested destructuring assignment. When using nested destructuring to get some values from a nested array or object, you have to follow the structure of the array or object. Nested Object Destructuring This section will demonstrate nested object destructuring in JavaScript. Syntax The syntax of nested object destruction in JavaScript is as follows − const {prop1, prop2: {nestedprop1, nestedprop2}} = obj; In the above syntax, prop1 is a property of the object, and the prop2 property contains the nested object, having nestedprop1 and nestedprop2 properties. Example In the example below, the car object contains the brand, model, and info properties. The info property contains the nested object containing the price and color properties. We have destructured the nested object and printed the values of the variables in the output. <html> <body> <p id = “output”> </p> <script> const car = { brand: “Hyundai”, model: “Verna”, info: { price: 1200000, // Nested properties color: “white”, } } const { brand, model, info: { price, color } } = car; // Destructuring document.getElementById(“output”).innerHTML = `Brand: ${brand} <br> Model: ${model} <br> Price: ${price} <br> Color: ${color}`; </script> </body> </html> Output Brand: Hyundai Model: Verna Price: 1200000 Color: white Example: Nested object destructuring and renaming variables The below code demonstrates that you can rename the variables while unpacking the nested object properties. We have renamed the brand, model, price, and color variables to company, name, cost, and carColor. <html> <body> <p id = “output”> </p> <script> const car = { brand: “Hyundai”, model: “Verna”, info: { price: 1200000, // Nested properties color: “white”, } } // Destructuring const {brand: company, model: name, info: {price: cost, color: carColor }} = car; document.getElementById(“output”).innerHTML = `Company: ${company}, Name: ${name}, Cost: ${cost}, Color: ${carColor}`; </script> </body> </html> Output Company: Hyundai, Name: Verna, Cost: 1200000, Color: white Example: Nested object destructuring and default values You can use the assignment operator to assign the default values to the variables. Whenever particular property of the object is undefined, it initializes the variable with the default value. Here, we have renamed each variable and assigned default values. The ”science” property is not defined in the grades (nested object) object. So, the code prints its default value in the output. <html> <body> <p id = “output”> </p> <script> const student = { firstName: “Sam”, lastName: “Raina”, grades: { English: 75, } }; const { firstName: name = “Jay”, lastName: surname = “Shah”, grades: { English: eng = 0, Science: sci = 0 } } = student; document.getElementById(“output”).innerHTML = `Name: ${name} <br> Surname: ${surname} <br> English: ${eng} <br> Science: ${sci}`; </script> </body> </html> Output Name: Sam Surname: Raina English: 75 Science: 0 Example: Nested object destructuring and rest operator The rest operator allows you to collect the remaining properties into a single object. In the below code, the grades object contains 4 different properties. We have stored the value of the Maths property in the Maths variables and other properties in the ”allGrades” variable using the rest operator. The ”allGrades” is an object containing 3 properties. <html> <body> <p id = “output”> </p> <script> const student = { firstName: “Kunal”, lastName: “Karma”, grades: { English: 75, Maths: 87, SocialScience: 90, Science: 80, } }; const { firstName, lastName, grades: { Maths, …allGrades } } = student; document.getElementById(“output”).innerHTML = `firstName: ${firstName} <br> lastName: ${lastName} <br> Maths: ${Maths} <br> allGrades: ${JSON.stringify(allGrades)} <br> `; </script> </body> </html> Output firstName: Kunal lastName: Karma Maths: 87 allGrades: {“English”:75,”SocialScience”:90,”Science”:80} Nested Array Destructuring This section will demonstrate nested array destructuring in JavaScript. Syntax The syntax to unpack nested array elements (nested array destructuring) in JavaScript is as follows − const [a, [b, c], d] = arr; In the above syntax, we store the nested array elements in the b and c variables. Example In the below code, the arr array contains the nested array. We unpack the nested array elements into the variables b and c. In the output, you can observe the values of the b and c variables. <html> <body> <p id = “output”> </p> <script> const arr = [10, [15, 20], 30]; const [a, [b, c], d] = arr; document.getElementById(“output”).innerHTML = “a = ” + a + “, b = ” + b + “, c = ” + c + “, d = ” + d; </script> </body> </html> Output a = 10, b = 15, c = 20, d = 30 Example: Skipping elements of the nested array Assignment destructuring allows you to skip the elements of the nested array. Here, the arr array contains two nested arrays. We skip the first element of each nested array while destructuring the nested array. <html> <body> <p id = “output”> </p> <script> const arr = [2, [3, 4], [9, 10]]; const [a, [, b], [, c]] = arr; document.getElementById(“output”).innerHTML = “a = ” + a + “, b = ” + b + “, c = ” + c; </script> </body> </html> Output a = 2, b = 4, c = 10 Example: Nested array destructuring and default values You can assign default values to the variables like objects while destructuring the nested arrays. Here, the first nested array of arr [3, 4] contains two elements. While destructuring, we skipped the first two elements and used the variable p to get the third element, but the nested array contains only two elements. So, the value of the variable p is a 29 default value. <html> <body> <p id = “output”> </p> <script> const arr = [2, [3, 4], [9, 10]];

JavaScript – Variables

JavaScript – Variables ”; Previous Next JavaScript Variables JavaScript variables are used to store data that can be changed later on. These variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container. Before you use a variable in a JavaScript program, you must declare it. In JavaScript, you can declare the variables in 4 ways − Without using any keywords. Using the ”var” keyword. Using the ”let” keyword. Using the ”const” keyword. The let and const keywords were introduced to JavaScript in 2015 (ES6). Prior to ES6, only var keyword was used to declare the variable in JavaScript. In this section, we will discuss ”var” keyword. We will cover the ”let” and ”const” keywords in subsequent chapters. Variable Declaration in JavaScript You can follow the syntax below to declare the variables without using any keywords. <script> Money = 10; Name = “tutorialspoint”; </script> Furthermore, you can use the var keyword to declare the variables as shown below. <script> var money; var name; </script> You can also declare multiple variables with the same var keyword as follows − <script> var money, name; </script> Variable Initialization using the Assignment Operator Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable. For instance, you might create a variable named money and assign the value 2000.50 to it later. For another variable, you can assign a value at the time of initialization as follows. <script> var name = “Ali”; var money; money = 2000.50; </script> Note − Use the var keyword only for declaration or initialization, once for the life of any variable name in a document. You should not re-declare same variable twice. JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don”t have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically. JavaScript Data Types In JavaScript, the variable can hold the value of the dynamic data type. For example, you can store the value of number, string, boolean, object, etc. data type values in JavaScript variables. <script> var num = 765; // Number var str = “Welcome”; // String var bool = false; // Boolean </script> You will learn data types in detail in JavaScript Data Types chapter. JavaScript Variable Names (Identifiers) In JavaScript, a unique character sequence is used to name the variables called identifiers. Here are some rules for the naming of the identifiers in JavaScript − Valid characters − In JavaScript, a variable name can contain digits, alphabetical characters, and special characters like underscore (_) and dollar sign ($). JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one.. Case sensitivity − Variable names are case sensitive. It means Name and name are different identifiers. Unicode support − The identifiers can also contain the Unicode. So, developers may define variables in any language. Reserve keywords − You should not use any of the JavaScript reserved keywords as a variable name. For example, break or boolean variable names are not valid. Here, we have given a full list of the JavaScript revered keywords. JavaScript Dollar Sign ($) and Under Score (_) You can use the $ and _ to define the variables in JavaScript, as the JavaScript engine considers it a valid character. Example (Demonstrating the identifiers) In this example, we have defined the variables using the var keyword. The first variable name starts with the underscore, and the second variable name starts with the dollar sign. Programmers can uncomment the third variable declaration to check the error generated by JavaScript when we start any identifier with the digit. <html> <head> <title> Variables in JavaScript </title> </head> <body> <script> var _abc = “Hi!”; var $abc = “Hello!”; // var 9abc = “Bye!”; // This is invalid document.write(“_abc ” + _abc + “<br>”); document.write(“$abc = ” + $abc + “<br>”); </script> </body> </html> It produces the following result − _abc Hi! $abc = Hello! Undefined Variable Value in JavaScript When you don”t initialize the variable after declaring, it contains the undefined value. However, you can also assign the undefined value to the variable. Let”s look at the example below. Example <html> <body> <script> var num; document.write(“The value of num is: ” + num + “<br/>”); </script> </body> </html> This produces the following result − The value of num is: undefined JavaScript Variable Scope The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes. Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function. Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Take a look into the following example. Example In the example below, we have defined the variable named myVar outside the function and initialized it with the ”global” value. Also, we have defined the variable with the same identifier inside the checkscope() function and initialized it with the ”local” value. We print the myVar variable”s value inside the function. So, the local variable takes preference over the global variable and prints the ”local” in the output. <html> <head> <title> JavaScript Variable