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 – Objects

JavaScript – Objects Overview ”; Previous Next JavaScript Objects The JavaScript object is a non-primitive data type that is used to store data as key-value pairs. The key-value pairs are often referred as properties. A key in a key-value pair, also called a “property name”, is a string and value can be anything. If a property”s value is a function, the property is known as a method. Objects are created using curly braces and each property is separated by a comma. Each property is written as property name followed by colon (:) followed by property value. The key: value pairs are not stored in the specific order in the object. So an object is an unordered collection of properties written as key: value pairs. JavaScript is an Object Oriented Programming (OOP) language. A programming language can be called object-oriented if it provides four basic capabilities to developers. Encapsulation − the capability to store related information, whether data or methods, together in an object. Abstraction − the capability to hide object”s implementation details from users. Inheritance − the capability of a class to rely upon another class (or number of classes) for some of its properties and methods. Polymorphism − the capability to write one function or method that works in a variety of different ways. Let”s understand in details about the JavaScript objects. Object Properties Object properties can be any of the primitive data types, objects or functions. Object properties are usually variables that are used internally in the object”s methods, but can also be globally visible variables that are used throughout the page. The syntax for adding a property to an object is − objectName.objectProperty = propertyValue; For example − The following code gets the document title using the “title” property of the document object. var str = document.title; Object Methods Methods are the functions that let the object do something or let something be done to it. There is a small difference between a function and a method – at a function is a standalone unit of statements and a method is attached to an object and can be referenced by the this keyword. Methods are useful for everything from displaying the contents of the object to the screen to performing complex mathematical operations on a group of local properties and parameters. For example − Following is a simple example to show how to use the write() method of document object to write any content on the document. document.write(“This is test”); Creating New Objects All user-defined objects and built-in objects are descendants of an object called Object. We can use object literals to create a new user-defined object. Alternatively, we can create a constructor function and then invoke this function using new keyword to instantiate an object. There are different ways to create an object in JavaScript. Here, we will learn all ways given below. Using the Object Literal Using the Object Constructor Using the Object.create() Method Using JavaScript ES6 Classes The JavaScript Object Literal In JavaScript, ‘{}’ is represented by the object literal. You can add pair of key-value pairs between curly braces to define an object. You can follow the syntax below to use the object literal to define objects. const obj = { key: val, } You can add key-value pairs between curly braces. Each key-value pair is comma separated, and you need to add a colon (:) between the key and value. Example In the example below, we have defined a wall object containing the 4 properties. Each property contains the different values of different data types. In the output, you can observe the object properties and its value. <html> <body> <p id = “output”> </p> <script> const myBook = { title: “Perl”, author: “Mohtashim”, pages: 355, } document.getElementById(“output”).innerHTML = “Book name is : ” + myBook.title + “<br>” +”Book author is : ” + myBook.author + “<br>” +”Total pages : ” + myBook.pages; </script> </body> </html> Output Book name is : Perl Book author is : Mohtashim Total pages : 355 The JavaScript new Operator The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method. In the following example, the constructor methods are Object(), Array(), and Date(). These constructors are built-in JavaScript functions. var employee = new Object(); var books = new Array(“C++”, “Perl”, “Java”); var day = new Date(“August 15, 1947”); The JavaScript Object() Constructor A constructor is a function that creates and initializes an object. JavaScript provides a special constructor function called Object() to build the object. The return value of the Object() constructor is assigned to a variable. The variable contains a reference to the new object. The properties assigned to the object are not variables and are not defined with the var keyword. Example Try the following example; it demonstrates how to create an Object. <html> <body> <p id = “output”> </p> <script> var book = new Object(); // Create the object book.subject = “Perl”; // Assign properties to the object book.author = “Mohtashim”; document.getElementById(“output”).innerHTML = “Book name is : ” + book.subject + “<br>” + “Book author is : ” + book.author; </script> </body> </html> Output Book name is : Perl Book author is : Mohtashim The JavaScript Constructor Function In JavaScript, you can define a custom function and use it as a constructor function to define a new object. Here, the custom function works as a template. The benefit of the custom user-defined constructor function over the Object() constructor is that you can add arguments to the custom function according to your requirements. Below is simple syntax to use the custom user-defined constructor function to create an object. // Object template function ConstructorFunc(para) { this.para = para; } const obj = new ConstructorFunc(arg); The ConstructorFunc() function works as an object template. It uses the ”this” keyword to access the context of the function and define the key in the function context. Also, the key is initialized with the

JavaScript – For Loop

JavaScript – For Loop ”; Previous Next The JavaScript for loop is used to execute a block of code repeteatedly, until a specified condition evaluates to false. It can be used for iteration if the number of iteration is fixed and known. The JavaScript loops are used to execute the particular block of code repeatedly. The ”for” loop is the most compact form of looping. It includes the following three important parts − Initialization − The loop initialization expression is where we initialize our counter to a starting value. The initialization statement is executed before the loop begins. Condition − The condition expression which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed. Otherwise, the control will come out of the loop. Iteration − The iteration expression is where you can increase or decrease your counter. You can put all the three parts in a single line separated by semicolons. Flow Chart The flow chart of a for loop in JavaScript would be as follows − Syntax The syntax of for loop is JavaScript is as follows − for (initialization; condition; iteration) { Statement(s) to be executed if condition is true } Above all 3 statements are optional. Examples Try the following examples to learn how a for loop works in JavaScript. Example: Executing a code block repeatedly In the example below, we used the for loop to print the output”s updated value of the ”count” variable. In each iteration of the loop, we increment the value of ”count” by 1 and print in the output. <html> <head> <title> JavaScript – for loop </title> </head> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); output.innerHTML = “Starting Loop <br>”; let count; for (let count = 0; count < 10; count++) { output.innerHTML += “Current Count : ” + count + “<br/>”; } output.innerHTML += “Loop stopped!”; </script> </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! Example: Initialization is optional The below code demonstrates that the first statement is optional in the for loop. You can also initialize the variable outside the loop and use it with the loop. Whenever you need to use the looping variable, even after the execution of the loop is completed, you can initialize a variable in the parent scope of the loop, as we have done in the below code. We also print the value of p outside the loop. <html> <head> <title> Initialization is optional in for loop </title> </head> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); var p = 0; for (; p < 5; p++) { output.innerHTML += “P -> ” + p + “<br/>”; } output.innerHTML += “Outside the loop! <br>”; output.innerHTML += “P -> ” + p + “<br/>”; </script> </body> </html> Output P -> 0 P -> 1 P -> 2 P -> 3 P -> 4 Outside the loop! P -> 5 Example: Conditional statement is optional The below code demonstrates that the conditional statement in the for loop is optional. However, if you don”t write any condition, it will make infinite iterations. So, you can use the ”break” keyword with the for loop to stop the execution of the loop, as we have done in the below code. <html> <head> <title> Conditional statement is optional in for loop </title> </head> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); let arr = [10, 3, 76, 23, 890, 123, 54] var p = 0; for (; ; p++) { if (p >= arr.length) { break; } output.innerHTML += “arr[” + p + “] -> ” + arr[p] + “<br/>”; } </script> </body> </html> Output arr[0] -> 10 arr[1] -> 3 arr[2] -> 76 arr[3] -> 23 arr[4] -> 890 arr[5] -> 123 arr[6] -> 54 Example: Iteration statement is optional In the for loop, the third statement is also optional and is used to increment the iterative variable. The alternative solution is that we can update the iterative variable inside the loop body. <html> <head> <title> Iteration statement is optional </title> </head> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); let str = “Tutorialspoint”; var p = 0; for (; 😉 { if (p >= str.length) { break; } output.innerHTML += “str[” + p + “] -> ” + str[p] + “<br/>”; p++; } </script> </body> </html> Output str[0] -> T str[1] -> u str[2] -> t str[3] -> o str[4] -> r str[5] -> i str[6] -> a str[7] -> l str[8] -> s str[9] -> p str[10] -> o str[11] -> i str[12] -> n str[13] -> t Print Page Previous Next Advertisements ”;

JavaScript – Break Statement

JavaScript – Break Statement ”; Previous Next The break statement in JavaScript terminates the loop or switch case statement. When you use the break statement with the loop, the control flow jumps out of the loop and continues to execute the other code. The break statement can also be used to jump a labeled statement when used within that labeled statement. It is a useful tool for controlling the flow of execution in your JavaScript code. Syntax The syntax of break statement in JavaScript is as follows − break; OR break [label]; The label is optional with a break statement. Note – In the next chapter, we will learn to use the break statement with the label inside the loop. Flow Chart The flow chart of a break statement would look as follows − Example (break statement with for loop) In the example below, we used the for loop to make iterations. We added the conditional expression in the loop using the ”if” statement. When the value of ”x” is 5, it will ”break” the loop using the break statement. The below code prints only 1 to 4 values in the output. <html> <head> <title> JavaScript – Break statement </title> </head> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); output.innerHTML += “Entering the loop. <br /> “; for (let x = 1; x < 10; x++) { if (x == 5) { break; // breaks out of loop completely } output.innerHTML += x + “<br />”; } output.innerHTML += “Exiting the loop!<br /> “; </script> </body> </html> Output Entering the loop. 1 2 3 4 Exiting the loop! Example (break statement with the while loop) The code below demonstrates the while loop with the ”break” statement. In the while loop, whenever the value of x is either 3 or 7, it will terminate the loop using the ”break” statement. In the code, we update the value after checking the condition. So, it will print 3 first and then terminate the loop in the next iteration. <html> <head> <title> JavaScript – Break 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 < 10) { if (x == 3 || x == 7) { break; // breaks out of loop completely } x = x + 1; output.innerHTML += x + “<br />”; } output.innerHTML += “Exiting the loop!<br /> “; </script> </body> </html> Output Entering the loop. 2 3 Exiting the loop! Break statement with nested loops You can use the ”break” statement to jump out of any loop when you have nested loops. For example, if you use the ”break” statement with the parent loop, the code will also terminate all iterations of the nested loop. Using the ”break” statement with the nested loop will terminate only the nested loop. Example In the example below, x is a looping variable for the parent loop, and y is a looping variable for a child loop. In the nested loop, whenever y becomes 3, it will break the loop; in the outer loop, whenever x becomes 3, it will break the loop. You won”t see x > 3 or y > 2 in the output. <html> <head> <title> JavaScript – Break statement </title> </head> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); output.innerHTML += “Entering the loop. <br /> “; for (let x = 1; x < 10; x++) { for (let y = 1; y < 10; y++) { if (y == 3) { break; // breaks inner loop } output.innerHTML += x + ” ” + y + “<br />”; } if (x == 3) { break; // break outer loop } } output.innerHTML += “Exiting the loop!<br /> “; </script> </body> </html> Output Entering the loop. 1 1 1 2 2 1 2 2 3 1 3 2 Exiting the loop! Break statement with switch case statement The switch case statement executes one of the code blocks from multiple based on the conditional expression. The ”break” statement terminates the switch case statement after matching one or more cases with the conditional expression”s value. Example In the below code, we used the ”break” statement with each case. Here, the value of variable p works as a conditional expression for the switch case statement. It matches with ”case 10”. So, the code will execute that particular code block and terminate the switch case statement using the ”break” statement. <html> <head> <title> JavaScript – Break statement </title> </head> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); var p = 10; switch (p) { case 10: output.innerHTML = “p is 10”; break; case 20: output.innerHTML = “p is 20”; break; case 30: output.innerHTML = “p is 30”; break; default: output.innerHTML = “p is not 10, 20 or 30″; } </script> </body> </html> Output p is 10 Print Page Previous Next Advertisements ”;

JavaScript – Function() Constructor

JavaScript – Function() Constructor ”; Previous Next 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 = new Function(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 = new Function(“p”, “q”, “return p * q”); document.getElementById(“output”).innerHTML = “The value returned from the function is: ” + func(5, 7); </script> </body> </html> 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 = new Function(“return 10 + 20”); document.getElementById(“output”).innerHTML = “The value returned from the function is: ” + func(); </script> </body> </html> 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 = new Function( “const sum = function (a, b) {return a+ b}; return sum”, )(); document.getElementById(“output”).innerHTML = add(5,10) // 15 </script> </body> </html> 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 = new Function( “return function (name) { return `Hello, ${name}` }”, )(); document.getElementById(“output”).innerHTML = sayHello(“world”); // Hello, world </script> </body> </html> Please note that in both the examples above, the new Function is self-invoked. Print Page Previous Next Advertisements ”;

JavaScript – Grouping Operator

JavaScript – Grouping Operator ”; Previous Next JavaScript Grouping Operator The grouping operator in JavaScript controls the precedence of the evaluation in expressions. It is denoted by parenthesis (), and you can put the expression inside that to change the expression evaluation order. It helps to evaluate an expression with lower precedence before an expression with higher precedence. Syntax You can follow the syntax below to use the grouping operator – ( exp ) In the above syntax, the ”exp” is an expression to change the precedence of evaluation. let res1 = 4 + 5 * 6; // 4 + 30 let res2 = (4 + 5) * 6; // 9 + 6 The multiplication (*) operator in JavaScript has higher precedence than the addition (+) operator. So, when the above code evaluates the first expression, it will multiply 5 and 6 and add the resultant value to 4. In the second expression, we grouped the (4 + 5) expression using the grouping operator to provide it with higher precedence than the normal operator. So, it adds 4 and 5 first and multiplies the resultant value with 6. Example <html> <body> <div id=”output”></div> <script> let res1 = 4 + 5 * 6; let res2 = (4 + 5) * 6; document.getElementById(“output”).innerHTML = “Result 1: ” + res1 + “<br>” + “Result 2: ” + res2; </script> </body> </html> It will produce the following result − Result 1: 34 Result 2: 54 Immediately Invoked Function Expressions (IIFEs) To define an immediately invoked function in JavaScript, we use the grouping operator. The anonymous function definition is put inside the grouping operator. These functions are also called self-executing functions. (function () { return 5; })(); In the above example, the function definition “function () { return 5;}” in put inside the grouping operator. Example In the example below, we have defined the self-executing function statement using the grouping operator. The first expression divides 10 by 5 (returned value from the function) and adds the resultant value, which is 2 to 5. The second expression adds 5 and 10 first and divides the resultant value with the value returned from the function. <html> <body> <div id=”output”></div> <script> let ans1 = 5 + 10 / (function () { return 5; })(); let ans2 = (5 + 10) / (function () { return 5; })(); document.getElementById(“output”).innerHTML = “Result 1: ” + ans1 + “<br>” + “Result 2: ” + ans2; </script> </body> </html> It will produce the following result − Result 1: 7 Result 2: 3 In simple terms, the grouping operator is used to group the sub-expressions to change its evaluation precedence over the normal precedence. Grouping Operator with Logical Operators The grouping operator in JavaScript can also be used to group expressions with logical operators. For example, in the following expression, the && operator has a higher precedence than the ||operator. So, the expression will be evaluated as follows: false && false || true; // true However, if we add parentheses around the ||operator, the expression will be evaluated as follows: false && (false || true); //false This is because the grouping operator overrides the normal operator precedence, so that the ||operator is evaluated first. Example This example demonstrates that how a grouping operator changes the precedence of OR operator to be evaluated before AND operator. The expression uses the logical operators. <html> <body> <div id=”output”></div> <script> let res1 = false && false || true // true let res2 = false && (false || true) //false document.getElementById(“output”).innerHTML = “Result without grouping operator: ” + res1 + “<br>” + “Result with grouping operator: ” + res2; </script> </body> </html> It will produce the following result − Result without grouping operator: true Result with grouping operator: false Print Page Previous Next Advertisements ”;

JavaScript – If…Else

JavaScript – if…else Statement ”; Previous Next The JavaScript if…else statement executes a block of code when the specified condition is true. When the condition is false the else block will be executed. The if-else statements can be used to control the flow of execution of a program based on different conditions. While writing a program, there may be a situation when you need to adopt one out of a given set of paths. In such cases, you need to use conditional statements that allow your program to make correct decisions and perform the right actions. JavaScript supports conditional statements used to perform different actions based on different conditions. Here we will explain the if…else statement. Flow Chart of if-else The following flow chart shows how the if-else statement works. JavaScript supports the following forms of if…else statement − if statement if…else statement if…else if… statement. JavaScript if statement The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally. Syntax The syntax for a basic if statement is as follows − if (expression) { Statement(s) to be executed if expression is true } Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are executed. If the expression is false, then no statement would be not executed. Most of the times, you will use comparison operators while making decisions. Example Try the following example to understand how the if statement works. <html> <body> <div id =”output”> </div> <script type = “text/javascript”> let result; let age = 20; if( age > 18 ) { result = “Qualifies for driving”; } document.getElementById(“output”).innerHTML = result; </script> <p> Set the variable to a different value and then try… </p> </body> </html> Output Qualifies for driving Set the variable to different value and then try… JavaScript if…else statement The ”if…else” statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way. Syntax if (expression) { Statement(s) to be executed if expression is true } else { Statement(s) to be executed if expression is false } Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else block are executed. Example Try the following code to learn how to implement an if-else statement in JavaScript. <html> <body> <div id =”output”> </div> <script type = “text/javascript”> let result; let age = 15; if( age > 18 ) { result = “Qualifies for driving”; } else { result = “Does not qualify for driving”; } document.getElementById(“output”).innerHTML = result; </script> <p> Set the variable to a different value and then try… </p> </body> </html> Output Does not qualify for driving Set the variable to different value and then try… JavaScript if…else if… statement The if…else if… statement (also called as if…else ladder)is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions. Syntax The syntax of an if-else-if statement is as follows − if (expression 1) { Statement(s) to be executed if expression 1 is true } else if (expression 2) { Statement(s) to be executed if expression 2 is true } else if (expression 3) { Statement(s) to be executed if expression 3 is true } else { Statement(s) to be executed if no expression is true } There is nothing special about this code. It is just a series of if statements, where each if is a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions is true, then the else block is executed. Example Try the following code to learn how to implement an if-else-if statement in JavaScript. <html> <body> <div id =”demo”></div> <script type=”text/javascript”> const output = document.getElementById(“demo”) let book = “maths”; if (book == “history”) { output.innerHTML=”<b>History Book</b>”; } else if (book == “maths”) { output.innerHTML=”<b>Maths Book</b>”; } else if (book == “economics”) { output.innerHTML=”<b>Economics Book</b>”; } else { output.innerHTML=”<b>Unknown Book</b>”; } </script> <p> Set the variable to a different value and then try… </p> </body> <html> Output Maths Book Set the variable to different value and then try… Print Page Previous Next Advertisements ”;

JavaScript – Spread Operator

JavaScript – Spread Operator ”; Previous Next What is a Spread Operator? The JavaScript spread operator (…) allows us to spread out elements of an iterable such as an array. The spread operator is represented with three dots (…). This is operator is introduced in ES6. The main use cases of the spread operator are to copy array elements, concatenate arrays or objects with rest parameters, etc. Let”s take an example to expand the elements of an array – let x = [“Tutorials”, “Point”]; console.log(x); // [ ”Tutorials”, ”Point” ] console.log(…x); // Tutorials Point Spread Operator to Concatenate Arrays The JavaScript spread operator can be used to concatenate the arrays. Example In the below example, we have defined two different arrays. After that, we used the spread operator to concatenate these arrays. <html> <body> <div id = “output”></div> <script> const nums1 = [10, 20, 30]; const nums2 = [40, 50, 60]; const res = […nums1, …nums2]; document.getElementById(“output”).innerHTML = res; </script> </body> </html> It will produce the following result − 10,20,30,40,50,60 You can also change the concatenation order of the array. Spread Operator to Clone an Array In JavaScript, when we assign one array (object) to another array, it assigns the reference rather than cloning the array. So, whenever you update the original array, it also updates the cloned array. The assignement operator creates a deep copy of the array. Example: Without Using Spread Operator In this example, we defined an array named nums1. We defiend another array named nums2 and assigned the array nums1 to array nums2. Here, you can see that when you change nums1, it also updates the nums2. <html> <body> <div id = “result1”></div> <div id = “result2”></div> <script> const nums1 = [10, 20, 30]; const nums2 = nums1; document.getElementById(“result1”).innerHTML = nums2; nums1.push(40); document.getElementById(“result2″).innerHTML = nums2; </script> </body> </html> It will produce the following result − 10,20,30 10,20,30,40 Example: Using Spread Operator to Clone Arrays Using the spread operator to clone the array creates an actual copy of the array, and the cloned array doesn”t change when you make changes to the original array. Here, you can see that nums3 doesn”t get updated even if you change the nums1. <html> <body> <div id = “result1”></div> <div id = “result2”></div> <script> const nums1 = [10, 20, 30]; const nums3 = […nums1]; document.getElementById(“result1”).innerHTML = nums3; nums1.push(50); document.getElementById(“result2”).innerHTML = nums1 + “<br>”; document.getElementById(“result2″).innerHTML += nums3; </script> </body> </html> It will produce the following result − 10,20,30 10,20,30,50 10,20,30 Spread Operator to Concatenate Objects You can use the spread operator to copy object properties into another object. Here, consider the ”car” object as a parent object containing similar properties to all cars. After that, created the ”BMW” object, representing the particular car, and concatenated all properties of the ”car” object with the ”BMW” object”s property. <html> <body> <div id = “result1”></div> <div id = “result2”></div> <script> const car = { gears: 6, color: “Black” } document.getElementById(“result1”).innerHTML = JSON.stringify(car); const BMW = { model: “X5”, year: 2019, …car, } document.getElementById(“result2”).innerHTML = JSON.stringify(BMW); </script> </body> </html> It will produce the following result − {“gears”:6,”color”:”Black”} {“model”:”X5″,”year”:2019,”gears”:6,”color”:”Black”} Function Rest Parameters When you need to pass an unknown number of arguments to the function, you can use the spread operator with the function parameters, called the rest parameter. Here, you can see that we have passed multiple numbers as a function argument and collected all arguments in the nums[] array using the spread operator except the first argument. <html> <body> <div id = “result”></div> <script> function sum(a, …nums) { let sum = a; for (let i = 0; i < nums.length; i++) { sum += nums[i]; } document.getElementById(“result”).innerHTML = sum; } sum(3, 6, 9, 8, 6, 5, 3, 3, 2, 1); </script> </body> </html> It will produce the following result − 46 You can also use the spread operator to expand the string into the array of characters, clone the string, or concatenate the string. Also, set, map, etc., are iterable objects in JavaScript. So, you can use the spread operator with them. Print Page Previous Next Advertisements ”;

JavaScript – Functions

JavaScript – Functions ”; Previous Next A 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 − function functionName(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 − function sayHello() { 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– const varName = 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. const myFunc = 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”> function sayHello() { 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”> function sayHello(name, age) { document.write (name + ” is ” + age + ” years old.”); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type = “button” onclick = “sayHello(”Zara”, 7)” value = “Say Hello”> </form> <p>Use different parameters inside the function and then try…</p> </body> </html> 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”> function concatenate(first, last) { var full; full = first + last; return full; } function secondFunction() { var result; result = concatenate(”Zara ”, ”Ali”); alert(result); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type=”button” onclick=”secondFunction()” value=”Call Function”> </form> <p>Use different parameters inside the function and then try…</p> </body> </html> Functions as Variable Values In JavaScript, functions can be used same as other variables. That’s 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> const myFunc = function (){ return “Hello “;}; document.getElementById(“output”).innerHTML = myFunc() + “Users.”; </script> </body> </html> We have covered two important concepts in separate chapters. JavaScript Nested Functions JavaScript Function Literals Print Page Previous Next Advertisements ”;