JavaScript – Delete Operator ”; Previous Next JavaScript Delete Operator The JavaScript delete operator deletes/ removes a property from an object. It removes the property as well as value of the property from the object. It works only with the objects not with the variables or functions. In JavaScript, an array is an object, so you can use the ”delete” operator to delete an element from the particular index. However, there are methods like pop(), slice(), or shift() available to delete the element from the array. Syntax Follow the below syntax to delete the object property using the ”delete” operator. delete obj.property; OR delete obj[“property”]; Return value − The ”delete” operator returns true if the operand (specified property) is deleted successfully, otherwise returns false if the property is not deleted. If you try to delete a property that doesn”t exist, it will return true but will not affect the object. Follow the below syntax to delete the array element using the ”delete” operator. delete arr[index]; Deleting Object Properties The JavaScript delete operator can be used to delete a property of an object. To delete the property we write the delelte operator followed by the property of the object. delete obj.propertyName; or delete obj[“propertyNmae”]; In the above syntas, object property named propertyName is being deleted from the object called obj. Example: Deleting an Object Property The ”obj” object in the example below contains the product, price, and color properties. We used the ‘delete” operator to delete the price property from the object. <html> <body> <div id=”output”></div> <script> const obj = { product: “Mobile”, price: 20000, color: “Blue”, } delete obj.price; // deleting price document.getElementById(“output”).innerHTML = “The Mobile price is ” + obj.price + ” and color is ” + obj.color; </script> </body> </html> It will produce the following result − The Mobile price is undefined and color is Blue Notice that when we access the deleted property, it returns undefined. Example: Deleting a Nonexistent object Property Try to delete a property that doesn”t exit. It will return true but doesn”t affect the original object. <html> <body> <div id=”output”></div> <script> const obj = { product: “Mobile”, price: 20000 } document.getElementById(“output”).innerHTML = delete obj.color; </script> </body> </html> The above program will produce the following result − true Deleting Array Elements We can use the delete operator to remove or delete an element from an array. To delete an element, we use delete keyword followed by array element. We can use square brackets ([]) to access the elements from the array. Example The below code contains the array of numbers. We used the ”delete” operator to delete the element from the 1st index of the array. In the output, you can observe that element from the array gets deleted, but the position of the other elements remains as it is. The array length also remains the same. <html> <body> <div id=”output”></div> <script> const arr = [10, 20, 30, 40, 50, 60]; delete arr[1]; // deleting 2nd element from array document.getElementById(“output”).innerHTML = arr + “<br>” + arr[1]; </script> </body> </html> It will produce the following result − 10,,30,40,50,60 undefined Deleting Predefined Object The JavaScript ”delete” operator can delete the predifiend object such as Math, Date, etc. It is not advisable to delete predefined objects. Once deleted, you can”t access the properties of these objects. Example: Deleting Built-in Math Object In the example below, we try delete Math object so we get the above error. <html> <body> <div id=”output”></div> <script> var x = 10 var fun = function(){return 20;}; document.getElementById(“output”).innerHTML = “delete Math.PI :” + delete Math.PI + “<br>” + “delete Math :” + delete Math + “<br>”; try{ document.getElementById(“output”).innerHTML += Math.PI; } catch(e){ document.getElementById(“output”).innerHTML += e; } </script> </body> </html> It will produce the following output − delete Math.PI :false delete Math :true ReferenceError: Math is not defined Can”t Delete Variables and Functions The delete operator can”t delete the variables or functions. <html> <body> <div id=”output1″></div> <div id=”output2″></div> <script> var x = 10 var fun = function(){return 20;}; document.getElementById(“output1”).innerHTML = delete x; document.getElementById(“output2″).innerHTML = delete fun; </script> </body> </html> It will produce the following result − false false The variable defined without var, let or const can be deleted. Such a variable is treated as property of window object. <html> <body> <div id=”output1″></div> <div id=”output2”></div> <script> try{ x = 10 document.getElementById(“output1”).innerHTML = delete x; document.getElementById(“output2”).innerHTML = x; }catch(e){ document.getElementById(“output2″).innerHTML = e; } </script> </body> </html> It will produce the following result − true ReferenceError: x is not defined Print Page Previous Next Advertisements ”;
Category: javascript
JavaScript – Nullish Coalescing Operator ”; Previous Next Nullish Coalescing Operator The Nullish Coalescing operator in JavaScript is represented by two question marks (??). It takes two operands and returns the first operand if it is not null or undefined. Otherwise, it returns the second operand. It is a logical operator introduced in ES2020. In many cases, we can have the null or empty values stored in the variables, which can change the behavior of the code or generate errors. So, we can use the Nullish Coalescing operator to use the default values when a variable contains falsy values. Syntax We can follow the syntax below to use the Nullish Coalescing operator. op1 ?? op2 The nullish coalescing operator (??) returns the second operand (op2) if the first operand (op1) is null or undefined. Otherwise, the ”res” variable will contain ”op2”. The above syntax is similar to the below code. let res; if (op1 != null || op1 != undefined) { res = op1; } else { res = op2; } Examples Let”s undersand the nullish coalescing operator in details with the help of some examples. Example: Handling null or undefined In the example below, the value of the x is null. We used the x as the first operand and 5 as the second. You can see in the output that the value of y is 5, as x is null. You can assign undefined to the variable. <html> <body> <div id = “output”></div> <script> let x = null; let y = x ?? 5; document.getElementById(“output”).innerHTML = “The value of y is: ” + y; </script> </body> </html> It will produce the following result − The value of y is: 5 Example: Handling null or undefined in Arrays In the example below, we have defined an array containing numbers. We used the empty array ([]) as a second operand. So, if arr is null or undefined, we assign an empty array to the arr1 variable. <html> <body> <div id = “output”></div> <script> const arr = [65, 2, 56, 2, 3, 12]; const arr1 = arr ?? []; document.getElementById(“output”).innerHTML = “The value of arr1 is: ” + arr1; </script> </body> </html> It will produce the following result – The value of arr1 is: 65,2,56,2,3,12 Example: Accessing Object Properties In the example below, we created the object containing the mobile-related properties. After that, we access the properties of the object and initialize the variables with value. The object doesn”t contain the ”brand” property, so the code initializes the ”brand” variable with the ”Apple”, which you can see in the output. In this way, we can use the Nullish Coalescing operator while accessing the properties of objects having different properties. <html> <body> <div id = “output”></div> <script> const obj = { product: “Mobile”, price: 20000, color: “Blue”, } let product = obj.product ?? “Watch”; let brand = obj.brand ?? “Apple”; document.getElementById(“output”).innerHTML = “The product is ” + product + ” of the brand ” + brand; </script> </body> </html> It will produce the following result – The product is Mobile of the brand Apple Short-Circuiting Like Logical AND, and OR operators, the Nullish Coalescing operator doesn”t evaluate the right-hand operand if the left-hand operand is neither null nor undefined. Using ?? with && or || When we use the ?? operator with logical AND or OR operators, we should use the parenthesis to explicitly specify the precedence. let x = 5 || 7 ?? 9; // Syntax Error let x = (5 || 7) ?? 9; // works Example In the example below, we have used nullish coalescing operator with OR operator (||) and AND operator (&&). <html> <body> <div id = “output”></div> <script> let x = (5 || 7) ?? 9; let y = (5 && 7) ?? 9; document.getElementById(“output”).innerHTML = “The value of x is : ” + x + “<br>” + “The value of y is : ” + y; </script> </body> </html> The above program will produce the following result − The value of x is : 5 The value of y is : 7 Print Page Previous Next Advertisements ”;
Javascript – For…of
JavaScript – For…of Loop ”; Previous Next JavaScript for…of Loop The for…of loop in JavaScript is used to traverse elements of the iterable object. In each iteration, it gives an element of the iterable object. Iterable objects include arrays, strings, maps, sets, and generators. The JavaScript for…of loop is a much more efficient way to iterate over iterables than using a for…in loop. The for…of loop iterates over the property value while the for…in loop is used to iterate through the keys (property name) of an object. Syntax The syntax of ”for…of” loop in JavaScript in as follows − for (ele of iterable) { // loop body } Parameters ele − It is a current element of the iterable. of − It is a JavaScript operator. iterable − It is iterable like an object, array, string, etc. Examples Example: For…of Loop with Arrays In the example below, the array contains various strings. After that, we used the for…of loop to traverse each array element. In the output, we can see that it prints each array element. <html> <head> <title> JavaScript – for…of loop </title> </head> <body> <p id=”output”> </p> <script> const output = document.getElementById(“output”); const arr = [“JavaScript”, “Python”, “C”, “C++”, “HTML”, “CSS”]; for (let ele of arr) { output.innerHTML += ele + “<br>”; } </script> </body> </html> Output JavaScript Python C C++ HTML CSS Example: For…of Loop with Strings In JavaScript, the string is also iterable as we can traverse through each character of the string. In the below code, for…of loop is used to traverse through each character of the string. <html> <head> <title> JavaScript – for…of loop </title> </head> <body> <p id=”output”> </p> <script> const output = document.getElementById(“output”); let str = “JavaScript”; for (let char of str) { output.innerHTML += char + “, “; } </script> </body> </html> Output J, a, v, a, S, c, r, i, p, t, Example: For…of Loop with Set In JavaScript, the set contains a unique element. Here, we have passed the array containing numbers as a parameter of the Set() constructor to create a set. After that, we used the for…of loop to traverse the set. <html> <head> <title> JavaScript – for…of loop </title> </head> <body> <p id=”output”> </p> <script> const output = document.getElementById(“output”); const nums = new Set([10, 20, 30, 30, 30, 40, 50, 60]); for (let num of nums) { output.innerHTML += num + “, “; } </script> </body> </html> Output 10, 20, 30, 40, 50, 60, Example: For…of Loop with Map The map contains the key-value pair in JavaScript and is similar to the object. Here, we created a map and inserted 3 key-value pairs in the map. When we use the for…of loop to traverse the map elements in each iteration, we can get the key and value shown in the code below. <html> <body> <p id=”output”> </p> <script> const output = document.getElementById(“output”); const map = new Map(); map.set(“one”, 1); map.set(“second”, 2); map.set(“third”, 3) for (let [k, v] of map) { output.innerHTML += k + ” -> ” + v + “<br/>”; } </script> </body> </html> Output one -> 1 second -> 2 third -> 3 However, you can also use the for…in loop to traverse the iterable like an array, string, map, set, etc. Print Page Previous Next Advertisements ”;
JavaScript – Strict Mode
JavaScript – Strict Mode ”; Previous Next Strict Mode in JavaScript In JavaScript, the strict mode is introduced in the ES5 (ECMAScript 2009). The purpose behind introducing the “strict mode” is to make the JavaScript code more secure. The ”use strict” literal expression is used to add the strict mode in the JavaScript code. It removes the silent errors from the code, such as you can”t use the variable without declaration, you can”t modify the readable property of the object, etc. Enabling Strict Mode To enble strcit mode, you should write the following literal expression to the top of your code − ”use strict”; The ”use strict” directive is used enable JavaScript”s strict mode. Why Use the Strict Mode? Here, we have listed some reasons for using the strict JavaScript mode − Error Prevention − The strict mode prevents the common errors which developers make while writing the JavaScript code, such as initializing the variable without declaration or using the reserved keywords as an identifier. Safer Code − The strict mode prevents the creation of global variables accidentally. Also, it doesn”t allow to use of statements like ”with”, which can lead to vulnerability in the code. Future Compatibility − You can align your code with the future versions of JavaScript by using the script mode. For example, the current version of JavaScript doesn”t contain keywords like ”public” but is reserved for future versions. So, the strict mode won”t allow you to use it as an identifier from now. Strict Mode in the Global Scope When you add the ”use strict” at the top of the JavaScript code; it uses the strict mode for the whole code. Example In the example below, we have defined the ”y” variable and initialized it with the 50. The code prints the value of ”y” in the output. Also, we initialized the variable ”x” without declaring it. So, it gives the error in the console and doesn”t print the output. In short, the strict mode doesn”t allow you to use the variable without its declaration. <html> <head> <title> Using the strict mode gloablly </title> </head> <body> <script> “use strict”; let y = 50; // This is valid document.write(“The value of the X is: ” + y); x = 100; // This is not valid document.write(“The value of the X is: ” + x); </script> </body> </html> Strict Mode in the Local Scope You can also use the “strict mode” inside the particular function. So, it will be applied only in the function scope. Let”s understand it with the help of an example. Example In the example below, we used the ”use strict” literal only inside the test() function. So, it removes the unusual errors from the function only. The code below allows you to initialize the variable without declaring it outside the function but not inside it. <html> <head> <title> Using the strict mode gloablly </title> </head> <body> <script> x = 100; // This is valid document.write(“The value of the X is – ” + x); function test() { “use strict”; y = 50; // This is not valid document.write(“The value of the y is: ” + x); } test(); </script> </body> </html> Mistakes that you should”t make in the strict mode 1. You can”t initialize the variable with a value without declaring it. <script> ”use strict”; num = 70.90; // This is invalid </script> 2. Similarly, you can”t use the object without declaring it. <script> ”use strict”; numObj = {a: 89, b: 10.23}; // This is invalid </script> 3. You can”t delete objects using the delete keyword. <script> ”use strict”; let women = { name: “Aasha”, age: 29 }; delete women; // This is invalid </script> 4. You can”t delete the object prototype in the strict mode. <script> ”use strict”; let women = { name: “Aasha”, age: 29 }; delete women.prototype; // This is invalid </script> 5. Deleting the function using the delete operator is not allowed. <script> ”use strict”; function func() { } delete func; // This is invalid </script> 6. You can”t have a function with duplicate parameter values. <script> ”use strict”; function func(param1, param1, param2) { // Function with 2 param1 is not allowed! } </script> 7. You can”t assign octal numbers to variables. <script> ”use strict”; let octal = 010; // Throws an error </script> 8. You can”t use escape characters. <script> ”use strict”; let octal = 10; // Throws an error </script> 9. You can”t use reserved keywords like eval, arguments, public, etc., as an identifier. <script> ”use strict”; let public = 100; // Throws an error </script> 10. You can”t write to the readable property of the object. <script> ”use strict”; let person = {}; Object.defineProperty(person, ”name”, { value: “abc”, writable: false }); obj1.name = “JavaScript”; // throws an error </script> 11. You can”t assign values to the getters function. <script> ”use strict”; let person = { get name() { return “JavaScript”; } }; obj1.name = “JavaScript”; // throws an error </script> 12. In the strict mode, when you use the ”this” keyword inside the function, it refers to the reference object through which the function is invoked. If the reference object is not specified, it refers to the undefined value. <script> ”use strict”; function test() { console.log(this); // Undefined } test(); </script> 13. You can”t use the ”with” statement in the strict mode. <script> ”use strict”; with (Math) {x = sin(2)}; // This will throw an error </script> 14. You can”t use the eval() function to declare the variables for the security reason. <script> ”use strict”; eval(“a = 8″) </script> 15. You can”t use the keywords as an identifier that are reserved for the future. Below keywords are reserved for the future − implements interface package private protected Print Page Previous Next Advertisements ”;
JavaScript – Iterables
JavaScript – The Iterables Object ”; Previous Next In JavaScript, iterables are objects that can be iterated through using the for…of loop. They can also be iterated over using other methods like forEach(), map(), etc. Basically, you can traverse through each element of the iterable in JavaScript. Here are some examples of the common iterables. Array String Map Set Arguments NodeList TypedArrays Generators Iterate using the for…of loop In this section, we will iterate through the array elements, string characters, set elements, and key-value pairs of the map using the for…of loop. Example: Iterate over an array In the below code, we have defined an array and used the for…of loop to iterate through the array. The code prints each element of the array in the output. <html> <body> <div>Iterating the array: </div> <div id = “demo”></div> <script> const output = document.getElementById(“demo”); const array = [“Hello”, “Hi”, 10, 20, 30]; // Iterating array for (let ele of array) { output.innerHTML += ele + “, “; } </script> </body> </html> Output Iterating the array: Hello, Hi, 10, 20, 30, Example: Iterate over a string In the below code, we used the for…of loop to iterate through each string character. The code prints the comma seprated string characters in the output. <html> <body> <div id = “demo”>Iterating a string: </div> <script> const output = document.getElementById(“demo”); let str = “Hello”; // Iterating a string for (let char of str) { output.innerHTML += char + “, “; } </script> </body> </html> Output Iterating a string: H, e, l, l, o, Example: Iterate over a set In this example, we have created a set containing multiple elements. After that, we traverse through each element of the set and print in the output. <html> <body> <p id = “demo”>Iterating the Set: </p> <script> const output = document.getElementById(“demo”); const set = new Set([10, 20, 30, 40, 40, 50, 50]); // Iterating a Set for (let ele of set) { output.innerHTML += ele + “, “; } </script> </body> </html> Output Iterating the Set: 10, 20, 30, 40, 50, Example: Iterate over a map In the example below, we have defined the map containing 3 key-value pairs. In each iteration of the for…of loop, we get a single key-value pair from the map. <html> <body> <div id = “demo”>Iterating the Map: <br></div> <script> const output = document.getElementById(“demo”); const map = new Map([ [“1”, “one”], [“2”, “two”], [“3”, “three”], ]); // Iterating array for (let ele of map) { output.innerHTML += ele + “<br>”; } </script> </body> </html> Output Iterating the Map: 1,one 2,two 3,three Iterate using the forEach() method In this section, we have used the forEach() method to iterate through the iterable. Example In the example below, we used the forEach() method with an array to iterate the array and print each element of the array in the output. <html> <body> <div> Using the forEach() method: </div> <div id=”demo”></div> <script> const output = document.getElementById(“demo”); const array = [true, false, 50, 40, “Hi”]; // Iterating array array.forEach((ele) => { output.innerHTML += ele + “, “; }) </script> </body> </html> Output Using the forEach() method: true, false, 50, 40, Hi, Iterate using the map() method In this section, we have used the map() method to iterate through the iterable. Example In the example below, the map() method is used with the array. In the callback function of the map() method, we print the array elements. <html> <body> <p id = “demo”>Using the map() method: </p> <script> const output = document.getElementById(“demo”); const array = [true, false, 50, 40, “Hi”]; // Iterating array array.map((ele) => { output.innerHTML += ele + “, “; }) </script> </body> </html> Output Using the map() method: true, false, 50, 40, Hi, However, you can traverse the array, string, etc., using the loops like a for loop, while loop, etc. JavaScript also allows us to define custom iterators to traverse the iterable. Print Page Previous Next Advertisements ”;
JavaScript – Assignment Operators ”; Previous Next JavaScript Assignment Operators The assignment operators in JavaScript are used to assign values to the variables. These are binary operators. An assignment operator takes two operands, assigns a value to the left operand based on the value of right operand. The left operand is always a variable and the right operand may be literal, variable or expression. let x = 10; // right operand is a literal let y = x; // right operand is a variable let z = x + 10; // right operand is an expression An assignment operator first evaluates the expression and then assign the value to the variable (left operand). A simple assignment operator is equal (=) operator. In the JavaScript statement “let x = 10;”, the = operator assigns 10 to the variable x. We can combine a simple assignment operator with other type of operators such as arithmetic, logical, etc. to get compound assignment operators. Some arithmetic assignment operators are +=, -=, *=, /=, etc. The += operator performs addition operation on the operands and assign the result to the left hand operand. Arithmetic Assignment Operators In this section, we will cover simple assignment and arithmetic assignment operators. An arithmetic assignment operator performs arithmetic operation and assign the result to a variable. Following is the list of operators with example − Assignment Operator Example Equivalent To = (Assignment) a = b a = b += (Addition Assignment) a += b a = a + b -= (Subtraction Assignment) a -= b a = a – b *= (Multiplication Assignment) a *= b a = a * b /= (Division Assignment) a /= b a = a / b %= (Remainder Assignment) a %= b a = a % b **= (Exponentiation Assignment) a **= b a = a ** b Simple Assignment (=) Operator A simple assignment (=) operator assigns a value to a variable. We can assign a single value to multiple variables. This is known as assignment chaining. <html> <body> <div id=”output”></div> <script> let x = 5; let y = x + 10; document.getElementById(“output”).innerHTML = “Value of x : ” + x + “<br>” + “Value of y : ” + y; </script> </body> </html> Below is an example of assignment chaining − <html> <body> <div id=”output”></div> <script> let x = y = 5; document.getElementById(“output”).innerHTML = “Value of x : ” + x + “<br>” + “Value of y : ” + y; </script> </body> </html> Addition Assignment (+=) Operator The JavaScript addition assignment operator performs addition on the two operands and assigns the result to the left operand. Here addition may be numeric addition or string concatenation. x += b; In the above statement, it adds values of b and x and assigns the result to x. Example: Numeric Addition Assignment <html> <body> <div id=”output”></div> <script> let x = 5; x += 7; document.getElementById(“output”).innerHTML = “Value of x : ” + x; </script> </body> </html> Example: String Concatenation Assignment <html> <body> <div id=”output”></div> <script> let x =”Hello”; x += ” World”; document.getElementById(“output”).innerHTML = “Value of x : ” + x; </script> </body> </html> Subtraction Assignment (-=) Operator The subtraction assignment operator in JavaScript subtracts the value of right operand from the left operand and assigns the result to left operand (variable). let x -=b; In the above statement, it subtracts b from x and assigns the result to x. <html> <body> <div id=”output”></div> <script> let x = 15; x -= 5; document.getElementById(“output”).innerHTML = “Value of x : ” + x; </script> </body> </html> Multiplication Assignment (*=) Operator The multiplication assignment operator in JavaScript multiplies the both operands and assign the result to the left operand. let x *= b; In the above statement, it multiplies x and b and assigns the result to x. <html> <body> <div id=”output”></div> <script> let x = 10; x *= 5; document.getElementById(“output”).innerHTML = “Value of x : ” + x; </script> </body> </html> Division Assignment (/=) Operator This operator divides left operand by the right operand and assigns the result to left operand. let x /= b; In the above statement, it divides x by b and assigns the result (quotient) to x. <html> <body> <div id=”output”></div> <script> let x = 10; x /= 5; document.getElementById(“output”).innerHTML = “Value of x : ” + x; </script> </body> </html> Remainder Assignment (%=) Operator The JavaScript remainder assignment operator performs the remainder operation on the operands and assigns the result to left operand. let x %= b; In the above statement, it divides x by b and assigns the result (remainder) to x. <html> <body> <div id=”output”></div> <script> let x = 12; x %= 5; document.getElementById(“output”).innerHTML = “Value of x : ” + x; </script> </body> </html> Exponentiation Assignment (**=) Operator This operator performs exponentiation operation on the operands and assigns the result to left operand. let x **= b; In the above statement, it computes x**b and assigns the result to x. <html> <body> <div id=”output”></div> <script> let x = 5; x **= 3; document.getElementById(“output”).innerHTML = “Value of x : ” + x; </script> </body> </html> JavaScript Bitwise Assignment operators A bitwise assignment operator performs bitwise operation on the operands and assign the result to a variable. These operations perform two operations, first a bitwise operation and second the simple assignment operation. Bitwise operation is done on bit-level. A bitwise operator treats both operands as 32-bit signed integers and perform the operation on corresponding bits of the operands. The simple assignment operator assigns result is to the variable (left operand). Following is the list of operators with example − Assignment Operator Example Equivalent To &= (Bitwise AND Assignment) a &= b a = a & b |= (Bitwise OR Assignment) a |= b a = a | b ^= (Bitwise XOR Assignment) a ^= b a = a ^ b Bitwise AND Assignment Operator The JavaScript bitwise AND assignment (&=) operator performs bitwise AND operation on the operands and assigns the result to the left
JavaScript – Operators
JavaScript – Operators ”; Previous Next What is an Operator? In JavaScript, an operator is a symbol that performs an operation on one or more operands, such as variables or values, and returns a result. Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands, and ‘+’ is called the operator. JavaScript supports the following types of operators. Arithmetic Operators Comparison Operators Logical (or Relational) Operators Bitwise Operators Assignment Operators Miscellaneous Operators Lets have a look on all operators one by one. JavaScript Arithmetic Operators The JavaScript arithmetic operators are used to perform mathematical calculations such as addition, multiplication, subtraction, division, etc. on numbers. JavaScript supports the following arithmetic operators − Assume variable x holds 10 and variable y holds 20, then − Operator Description Example + (Addition) Adds two operands. x + y will give 30. – (Subtraction) Subtracts the second operand from the first. x – y will give -10. * (Multiplication) Multiplies both operands. x * y will give 200. / (Division) Divides the numerator by the denominator. y / x will give 2. % (Modulus) Outputs the remainder of an integer division. y % x will give 0 ++ (Increment) Increases an integer value by one. x++ will give 11. — (Decrement) Decreases an integer value by one. x– will give 9. Addition operator (+) works for Numeric as well as Strings. e.g. “a” + 10 will give “a10”. JavaScript Comparison Operators The JavaScript comparison operators compare two values and returns a boolean result (true or false). JavaScript supports the following comparison operators − Assume variable x holds 10 and variable y holds 20, then − Operator Description Example == (Equal) Checks if the value of two operands is equal or not. If yes, then the condition becomes true. (x == y) is not true. != (Not Equal) Checks if the value of two operands is equal or not. If the values are not equal, then the condition becomes true. (x != y) is true. === (Strict equality) It checks whether the value and data type of the variable is equal or not. If yes, then the condition becomes true. (x === y) is not true. !== (Strict inequality) It checks whether the value and data type of the variable is equal or not. If the values are not equal, then the condition becomes true. (x !== y) is true. > (Greater than) Checks if the value of the left operand is greater than the value of the right operand. If yes, then the condition becomes true. (x > y) is not true. < (Less than) Checks if the value of the left operand is less than the value of the right operand. If yes, then the condition becomes true. (x < y) is true. >= (Greater than or Equal to) Checks if the value of the left operand is greater than or equal to the value of the right operand. If yes, then the condition becomes true. (x >= y) is not true. <= (Less than or Equal to) Checks if the value of the left operand is less than or equal to the value of the right operand. If yes, then the condition becomes true. (x <= y) is true. JavaScript Logical Operators The logical operators are generally used to perform logical operations on boolean values. But logical operators can be applied to values of any types not only boolean. JavaScript supports the following logical operators − Assume that the value of x is 10 and y is 0. Operator Description Example && (Logical AND) If both the operands are non-zero, then the condition becomes true. (x && y) is false || (Logical OR) If any of the two operands are non-zero, then the condition becomes true. (x || y) is true. ! (Logical NOT) Reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false. !x is false. JavaScript Bitwise Operators The JavaScript bitwise operators are used to perform bit-level operations on integers. JavaScript supports the following seven types of bitwise operators − Assume variable x holds 2 and variable y holds 3, then − Operator Description Example & (Bitwise AND) It performs a Boolean AND operation on each bit of its integer arguments. (x & y) is 2. | (Bitwise OR) It performs a Boolean OR operation on each bit of its integer arguments. (x | y) is 3. ^ (Bitwise XOR) It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both. (x ^ y) is 1. ~ (Bitwise Not) It is a unary operator and operates by reversing all the bits in the operand. (~y) is -4. << (Left Shift) It moves all the bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4, and so on. (x << 1) is 4. >> (Right Shift) Binary Right Shift Operator. The left operand’s value is moved right by the number of bits specified by the right operand. (x >> 1) is 1. >>> (Right shift with Zero) This operator is just like the >> operator, except that the bits shifted in on the left are always zero. (x >>> 1) is 1. JavaScript Assignment Operators In JavaScript, an assignment operator is used to assign a value to a variable. JavaScript supports the following assignment operators − Operator Description Example = (Simple Assignment) Assigns values from the right side operand to the left side operand z = x + y will assign the value of x + y into z += (Add and Assignment) It adds the right operand to the
JavaScript – Loop Control
JavaScript – Loop Control ”; Previous Next JavaScript Loop Control JavaScript provides full control to handle loops and switch statements. There may be a situation when you need to come out of a loop without reaching its bottom. There may also be a situation when you want to skip a part of your code block and start the next iteration of the loop. To handle all such situations, JavaScript provides break and continue statements. These statements are used to immediately come out of any loop or to start the next iteration of any loop respectively. Also, JavaScript allows developers to use labels to name the loop. We have explained the keywords in the below table, which can be used to control the loop. Keyword Explanation break The ”break” keyword is used to come out of the loop. continue The ”continue” keyword is used to skip the current iteration of the loop. label The ”label” is not a keyword, but you can use any identifier followed by a colon (:) to give a label to the loop. After that, you can use the label to target the particular loop with the break and continue keyword. In the upcoming chapters, we will learn in detail about the break, continue and label statements. The break Statement The JavaScript break statement, which was briefly introduced with the switch statement, is used to exit a loop early, breaking out of the enclosing curly braces. Flow Chart The flow chart of a break statement would look as follows − Example The following example illustrates the use of a break statement with a while loop. Notice how the loop breaks out early once x reaches 5 and reaches − <html> <body> <div id = “output”> </div> <script> const coutput = document.getElementById(“output”); let x = 1; coutput.innerHTML = “Entering the loop<br> “; while (x < 20) { if (x == 5) { break; // breaks out of loop completely } x = x + 1; coutput.innerHTML += x + “<br>”; } coutput.innerHTML += “Exiting the loop!<br> “; </script> <p>Set the variable to different value and then try…</p> </body> </html> Output Entering the loop 2 3 4 5 Exiting the loop! Set the variable to different value and then try… The continue Statement 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. Example This example illustrates the use of a continue statement with a while loop. Notice how the continue statement is used to skip printing when the index held in variable x reaches 5 − <html> <body> <div id = “output”> </div> <script> const coutput = document.getElementById(“output”); let x = 1; coutput.innerHTML = “Entering the loop<br> “; while (x < 10) { x = x + 1; if (x == 5) { continue; // skip rest of the loop body } coutput.innerHTML += x + “<br>”; } coutput.innerHTML += “Exiting the loop!<br> “; </script> <p>Set the variable to different value and then try…</p> </body> </html> Output Entering the loop 2 3 4 6 7 8 9 10 Exiting the loop! Set the variable to different value and then try… Using Labels to Control the Flow Starting from JavaScript 1.2, a label can be used with break and continue to control the flow more precisely. A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. We will see two different examples to understand how to use labels with break and continue. Line breaks are not allowed between the ”continue” or ”break” statement and its label name. Also, there should not be any other statement in between a label name and associated loop. Try the following two examples for a better understanding of Labels. Example 1 The following example shows how to implement Label with a break statement. In the example below, we have given the ”outerloop” and ”innerloop” labels to the loop. We used the ”break” statement in the nested loop with the label. In the output, you can see that it breaks the outer loop from the inner loop. <html> <body> <div id = “output”> </div> <script> const coutput = document.getElementById(“output”); output.innerHTML = “Entering the loop!<br /> “; outerloop: // This is the label name for (let i = 0; i < 5; i++) { output.innerHTML += “Outerloop: ” + i + “<br />”; innerloop: for (let j = 0; j < 5; j++) { if (j > 3 ) break ; // Quit the innermost loop if (i == 2) break innerloop; // Do the same thing if (i == 4) break outerloop; // Quit the outer loop output.innerHTML += “Innerloop: ” + j + ” <br />”; } } output.innerHTML += “Exiting the loop!<br /> “; </script> </body> </html> Output Entering the loop! Outerloop: 0 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 1 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 2 Outerloop: 3 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 4 Exiting the loop! Example 2 In the below code, we use the continue statement with a label inside the nested loop to skip the current iteration of the outer loop. Whenever the value of q becomes 3, it skips the execution of the remaining code of the current iteration and starts a new iteration. <html> <head> <title> JavaScript – Label statement </title> </head> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); output.innerHTML += “Entering the loop!<br /> “; outerloop: // This is the label name for (let p = 0; p < 3; p++) { output.innerHTML += “Outerloop: ” + p + “<br />”; for (let q = 0; q < 5; q++) { if (q == 3) { continue outerloop;
JavaScript – Comparison Operators ”; Previous Next JavaScript Comparison Operators The comparison operators in JavaScript compare two variables or values and return a boolean value, either true or false based on comparison result. For example, we can use the comparison operators to check whether two operands are equal or not. The comparison operators are used in logical expressions. A logical expression is evaluated to either true or false. The comparison operators are binary operators as they perform operations on two operands. The operands can be numerical, string, logical, or object values. There are eight comparison operators in JavaScript to perform different types of comparison. Here, we have given a table explaining each comparison operator with the example. Operator Description Example == Equal x == y != Not Equal x != y === Strict equality (equal value and equal type) x === y !== Strict inequality (not equal value or not equal type) x !== y > Greater than x > y < Less than x < y< >= Greater than or Equal to x >= y <= Less than or Equal to x <= y How comparison is done? If both operands are of same type, the comparison operators compare the values. However, if the operands are of different types, JavaScript perform appropriate type conversion for the comparison. This is known as type coercion. The comparison is done by checking the numerical values of the operands if both the operands are numbers. The strings are compared based on lexicographical ordering, using Unicode values. The following type coercion is done when a string is compared with a number. If the string contains only numeric value, it is converted to number type. If the string contains non-numeric values as well, it will be converted to NaN. If string is empty, it is converted to zero. The strict equality (===) and strict inequality (!==) operators perform strict comparison. These operators don”t perform type conversion before performing comparison operation. Dealing with falsy values There are some falsy values in JavaScript. JavaScript deals with these falsy values differently while performing the comparison. Followings are the flasy values − 0 (zero) false ” ” or ” ” (Empty String) null undefined NaN All comparison operators (excepts === and !==) converts false and empty string to zero before performing comparison. In addition to above, the less and, greater than operators (, >=) convert null to zero and undefined to NaN. JavaScript Equality (==) Operator The “equality” operator checks if the value of two operands are equal or not. It returns true if the operands are equal, otherwise it returns false. If the operands are of different types, it performs type conversion and then compare the operands. Let’s look at some examples of comparison with no type conversion. The both operands are of same type. const a = 10; const b = 20; a == 10; //true a == b; // false “Hello” == “Hello”; // true Now let’s check some example of comparison with type conversion. Here the operands are of different types. 5 == ”5”; // true 0 == false; // true 0 == ””; // true In the first example above, ”5” is converted to 5 (string to number conversion). The false and empty string (” ”), are converted to zero (0) before comparison. Example The following code shows how to use equality operator in JavaScript − <html> <body> <div id=”output”></div> <script> const a = 10; const b = 20; let result = (a == b); document.getElementById(“output”).innerHTML = “(a == b) => ” + result; </script> <p> Set the variables to different values and then try…</p> </body> </html> JavaScript Inequality (!=) Operator The “inequality” operator checks if the values of two operands are not equal. It returns true if the operands are not equal, otherwise it returns false. Same as the equality operator, type conversion is performed if the operands are not of same type. In the example below two values of same type are compared for inequality check. If the values are not equal, the inequality operator will return true. 10 != 10; // false 10 != 20; // true “Hello” != “Hello”; // false Let’s check for inequality when the operands are of different types . 10 != ”10”; // false 0 != false; // false Here in first example, ”10” is type casted to 10. Here string is converted to number type. In second example, false (Boolean value) is converted to zero (number). Example The following code shows how to use inequality operator in JavaScript. <html> <body> <div id=”output”></div> <script> const a = 10; const b = 20; let result = (a != b); document.getElementById(“output”).innerHTML = “(a != b) => ” + result; </script> <p> Set the variables to different values and then try…</p> </body> </html> JavaScript Strict Equality (===) Operator The “strict equality” operator checks whether the values and data types of the two operands are equal or not. It returns true if both operands are equal and of same type. In other words, it checks the equality of the operands without the type conversion. If the operands are of different types, it returns false without further checking the value. 10 === 10; // true 10 === 20; // false ”Hello”===”Hello”; // true 10 === ”10”; // false 0 === false; // false Example The following code shows how to use strict equality operator in JavaScript. <html> <body> <div id=”output”></div> <script> const a = 10; const b = 20; let result = (a === b); document.getElementById(“output”).innerHTML = “(a === b) => ” + result; </script> <p> Set the variables to different values and then try…</p> </body> </html> Strict Inequality (!==) Operator The “strict inequality” operator checks whether the two operands are not equal in value or type. It returns true if the operands are of same type but not equal or are of different types. Same as strict equality operator, it also first checks the inequality of operands without type conversion. If the operands are of different
JavaScript – Comments
JavaScript – Comments ”; Previous Next JavaScript Comments JavaScript comments are used to explain the purpose of the code. The comments are not executed as a part of program and these are solely meant for human developers to understand the code better. You can use comments for various purposes, such as − Explaining the purpose of a particular piece of code. Adding documentation to your code for yourself and others who may read it. Temporarily disabling or “commenting out” a block of code for testing or debugging without deleting it. A good developer always writes a comment to explain the code. There are two common ways to write comments in JavaScript − Single-line comments Multi-line comments Single-line comments in JavaScript We can start the single-line comment with the double forward slash (//). We can write comment between // and end of the line. Syntax The syntax for the single-line comments is given below − <script> // single-line comment message </script> Example In the example below, we have explained each step of JavaScript code using single-line comments. In the output, the code prints the concatenated string. <html> <head> <title> Single line comments </title> </head> <body> <script> // Defining the string1 var string1 = “JavaScript”; // Defining the string2 var string2 = “TypeScript”; // Printing the strings document.write(string1, ” “, string2); </script> </body> </html> Example In the example below, we have commented the ”bool1 = false;” line to avoid execution of that code. In the output, we can see that value of the bool1 variable is true, as we commented out the code, which updates the bool1 variable’s value. Also, we can add the single line code after writing the code, as we added after the document.write() method. <html> <head> <title> Single line comments </title> </head> <body> <script> var bool1 = true; // bool1 = false; document.write(“The value of the bool1 is: “, bool1); // print variable value </script> </body> </html> Multi-line comments in JavaScript The multi-line comment is useful when we require to comment the multiple lines of code or explain the larger codes. We can write multi-line comments between the /* and */. Syntax The syntax for the multi-line comments is given below − <script> /* First line of comment message The second line of the comment message */ </script> Example In the example below, we have defined ”a” and ”b” variables. After that, we have written the code to swap values of ”a” and ”b” in 3 lines and comment out using the multi-line comments. The output prints the actual values of the ”a” and ”b” as the browser ignores the commented code. <html> <head> <title> Multi line comments </title> </head> <body> <script> var a = 100; var b = 200; /* a = a + b; b = a – b; a = a – b; */ document.write(“a = ” + a + “<br>” + “b = ” + b); </script> </body> </html> Always write comments in your code as it helps other collaborators to understand your code. Print Page Previous Next Advertisements ”;