Blog

  • Grouping Operator

    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 + 30let 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(){return5;})();

    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(){return5;})();let ans2 =(5+10)/(function(){return5;})();
       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// truelet 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
    

  • Comma Operator

    JavaScript Comma Operator

    The comma operator (,) in JavaScript evaluates the multiple expression from left to right. You can use the resultant value of the left expression as an input of the right expression. After evaluating all expressions, it returns the resultant value of the rightmost expression.

    However, the comma operator is also used in the ‘for’ loop, array, object, etc. In this chapter, you will learn all the use cases of the comma operator.

    Syntax

    You should follow the below syntax to use the comma expression to evaluate multiple expressions.

    var answer =(exp1, exp2, exp3, ex4,...);

    Return value

    It returns the resultant value of the last expression only.

    Examples

    Let’s understand the JavaScript comma operator in details with the help of some exmaples

    Example: The Comma Operator with Strings

    In the example below, we have added the 4 comma seprated strings in the braces. Here, each string works as an expression. The code will evaluate the string and return the last string. In the output, you can see that it prints the ‘CSS’ as it is the rightmost string.

    <html><body><p id ="output"></p><script>let output = document.getElementById("output");let ans =("JavaScript","Python","HTML","CSS");
    
        output.innerHTML ="The value of the ans variable is: "+ ans;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: The Comma Operator with Expressions

    In the example below, we have defined the variable 'a' and initialized it with 5. In the 'ans' variable, we store the resultant value the comma operator returns. The first expression updates the value of a to 8, the second expression increments the value of a by 1, and the third expression adds 2 to the updated value of the variable 'a'.

    The value of the 'ans' is 11, which is returned by the rightmost expression of the comma operator.

    <html><body><p id ="output"></p><script>let output = document.getElementById("output");let a =5;let ans =(a =8, a++, a +=2);
    
        output.innerHTML ="The value of the ans variable is: "+ ans;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: The comma operator with functions

    In the example below, we have defined the first() and second() functions. Also, it prints the message and returns the value from the function according to the function name.

    We use the comma operator to execute the multiple functions. In the output, you can see that it invokes both functions but prints the returned value from the second() function only.

    <html><body><p id="output"></p><script>let output = document.getElementById("output");functionfirst(){
    
            output.innerHTML +="The first function is called! &lt;br/&gt;";return1;}functionsecond(){
            output.innerHTML +="The second function is called! &lt;br/&gt;";return2;}let ans =(first(),second());
        output.innerHTML +="The value of the ans variable is: "+ ans;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Other Use Cases of The Comma Operator

    For defining the multiple variables in a single row.

    let m =1, n =2, x =3;

    To initialize the array with multiple elements.

    const arr =[10,20,30,40,50,60];

    For defining the object with multiple properties.

    const obj ={
       name:"tutorialspoint",
       age:10,... other properties
    }

    You can use the comma operator for loop to initialize or update multiple variables in each iteration.

    for(let p =0, q =1; p < n; p++, q++){// Code for the loop}

    To pass multiple parameters of arguments into the functions.

    functionfunc(param1, param2, ...){// function code}ORfunc(10,20,30,...);

    To import or export

    import{ func2, variable }from'./module2.js';ORexport{func1, variable, num};

    To destructure arrays of objects.

    let[a, b, c]=[34,72,23];

    To print multiple variables in the console.

    console.log(a, b, c)// a, b, and c are variables.

  •  Delete Operator

    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;ORdelete 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 =10varfun=function(){return20;};
       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;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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 =10varfun=function(){return20;};
       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;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    true
    ReferenceError: x is not defined

  • Safe Assignment Operator

    JavaScript Safe Assignment Operator (?=) is a suggested new feature for JavaScript that makes it easier to handle errors in code. This operator helps developers deal with errors more simply, without having to use complicated try/catch blocks.

    It is denoted by (?=) symbol. It is currently under development and not yet part of the official ECMAScript specification.

    Syntax

    The syntax for using the Safe Assignment Operator is as follows.

    variable ?= value;

    Examples

    Here are the simple and examples of using safe assignment operator that will help to better understand it:

    Using Safe Assignment Operator

    This example demonstrates how to use the operator to assign a value only if the variable is currently null or undefined.

    // Initial variable set to nulllet username =null;// Using the Safe Assignment Operator// to assign a default value
    username ?="Guest";// Alerting the resultalert(username);// This will alert "Guest"

    Output

    The variable username is set as null. The line username ?= “Guest”; checks if it’s null or undefined and sets it to “Guest”. Finally, alert(username); shows that username is now “Guest”.

    Guest

    Assign a Calculated Value

    This example demonstrates how to use the operator to assign a calculated value only if the variable is currently null or undefined.

    // Function to perform a simple calculationfunctioncalculate(value){return value *2;// Simple calculation: double the input}// Initial variable set to nulllet result =null;// Using the Safe Assignment Operator to assign the calculated value
    result ?=calculate(5);// Assigns 10 if result is null// Alerting the resultalert(result);// This will alert "10"

    Output

    The calculate function takes a number and returns its double. The variable result is set as null. The line result ?= calculate(5); checks if result is “null”, and since it is, it calls calculate(5), which returns 10 and assigns it to result. Finally, alert(result); shows that result is now 10.

    10

    This operator is supported by modern browsers (Chrome 91+, Firefox 89+, Edge 91+, Safari 15+) and Node.js (14.17.0+)

  • Nullish Coalescing Operator

    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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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 Errorlet 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 +"&lt;br&gt;"+"The value of y is : "+ y;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    The above program will produce the following result −

    The value of x is : 5
    The value of y is : 7

  • typeof Operator

    The typeof Operator

    The typeof operator in JavaScript is a unary operator used to get the data type of a particular variable. It is placed before its single operand, which can be of any type. Its returns a string value indicating the data type of its operand. JavaScript contains primitive and non-primitive data types.

    There are seven primitive or basic in JavaScript data types number, string, boolean, undefined, null, symbol, and bigint. There is also a composite data type called object. The object data type contains three sub data type Object, Array and Date.

    Syntax

    Following is the syntax of the typeof operator −

    typeof(operand);

    We can write the operand without parenthesis as follows −

    typeof operand;

    Parameter

    • operand − It can be a value, variable or expression representing the object or primitive. In JavaScript, primitives are data that are not object and have no methods or properties.

    Return Value

    • It returns the string value representing the data type of the operand.

    Datatypes Returned by typeof Operator

    Here is a list of the return values for the typeof Operator.

    TypeString Returned by typeof
    Number“number”
    String“string”
    Boolean“boolean”
    Object“object”
    Function“function”
    Undefined“undefined”
    Null“object”
    Symbol“symbol”
    Bigint“bigint”

    There are seven primitive datatypes in JavaScript number, string, boolean, bigint, undefined, null, and symbol. The typeof operator is useful to identify these primitive or basic datatypes.

    The typeof operator returns same datatype of the all primitive values except the null. It returns “object” for the null values.

    For object, date and array it returns “object” as datatype.

    For functions and classes, it returns “function” as datatype.

    Let’s use the typeof operator to identify these datatypes one by one.

    typeof10;// returns 'number'typeof'Hello World';// returns 'string'typeoftrue;// returns 'boolean'typeof{name:"Tutorialspoint"};// returns 'object'typeoffunctionfoo(){};// returns 'function'typeofundefined;// returns 'undefined'typeofnull;// returns 'object'typeofSymbol();// returns 'symbol'typeof10n;// returns 'bigint'

    JavaScript typeof Operator to Check Number Type

    In JavaScript, number type represents numeric values. JavaScript uses a floating-point representation for all numbers. The JavaScript typeof operator returns ‘number’ for all types of numbers such as integers, floating points, zero, Infinity, NaN etc.

    typeof10;//returns "number";typeof-10;//returns "number";typeof0;//returns "number";typeof10.20;//returns "number";typeof Math.LN10;//returns "number";typeofInfinity;//returns "number";typeofNaN;//returns "number";typeofNumber('1');//returns "number";typeofNumber('hello');//returns "number";

    Example

    The example below demonstrates how to use the typeof operator to check number data types.

    <html><body><p> Using typeof operator to check number data type </p><div id="output"></div><script>
    
         let num = 42;
         document.getElementById("output").innerHTML = typeof num;
      &lt;/script&gt;&lt;p&gt;Set the variable to different value and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Using typeof operator to check number data type
    number
    Set the variable to different value and then try...
    

    JavaScript typeof Operator to Check String Type

    Strings represent sequences of characters. The typeof operator helps identify string variables. The JavaScript typeof operator returns "string" for all type of strings, such as empty string, string of characters, string words, multiline string etc.

    typeof"10";//returns "string";typeof"";//returns "string";typeof"Hello World";//returns "string";typeofString(10);//returns "string";typeoftypeof2;//returns "string";

    Example

    In the example below we use typeof operator to check string datatype.

    <html><body><div id="output"></div><script>
    
         let str = "Hello World";
         document.getElementById("output").innerHTML = typeof str;
      &lt;/script&gt;&lt;p&gt;Set the variable to different value and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    string
    Set the variable to different value and then try...
    

    JavaScript typeof Operator to Check Boolean Type

    The boolean values represent true or false. The tyepof operand returns boolean for boolean variables.

    typeoftrue;//returns "boolean";typeoffalse;//returns "boolean";typeofBoolean(10);//returns "boolean";

    Example

    In the example below, we use typeof operator to check boolean datatype.

    <html><body><div id="output"></div><script>
    
         let bool = true;
         document.getElementById("output").innerHTML = typeof bool;
      &lt;/script&gt;&lt;p&gt;Set the variable to different value and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    boolean
    Set the variable to different value and then try...
    

    JavaScript typeof Operator to Check Symbol Type

    Symbols were introduced in ES6 and provide a way to create unique identifiers. Using typeof operator with symbols returns "symbol".

    typeofSymbol();//returns "symbol";typeofSymbol("unique values");//returns "symbol";

    Example

    In the example below, we use typeof operator to check Symbol datatype.

    <html><body><div id="output"></div><script>
    
         let sym = Symbol("Hello");
         document.getElementById("output").innerHTML = typeof sym;
      &lt;/script&gt;&lt;p&gt;Set the variable to different value and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    symbol
    Set the variable to different value and then try...
    

    JavaScript typeof Operator to Check Undefined and Null

    The "undefined" type represents a lack of a value. The "null" type represents the absence of any object value. When using typeof operator with an undefined variable, it returns 'undefined'. Surprisingly, using typeof operator with null also returns "object", which is a known quirk in JavaScript.

    typeofundefined;//returns "undefined";typeofnull;//returns "object";

    Please note typeof operator will return "undefined" for both undeclared variable and declared but unassigned variables.

    Example

    In the example below, we use typeof operator to check undefined datatype.

    <html><body><div id="output"></div><script>
    
         let x;
         document.getElementById("output").innerHTML = typeof x;
      &lt;/script&gt;&lt;p&gt;Set the variable to different value and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    undefined
    Set the variable to different value and then try...
    

    JavaScript typeof Operator to Check Object Type

    The JavaScript typeof operator returns "object" for all types of object such as JavaScript objects, arrays, dates, regex, etc.

    const obj ={age:23};typeof obj;//returns "object";const arr =[1,2,3,4];typeof arr;//returns "object";typeofnewDate();//returns "object";typeofnewString("Hello World");//returns "object";

    Example

    In the example below, we use typeof operator to check object datatype.

    <html><body><div id="output"></div><script>
    
         const person = {name: "John", age: 34};
         document.getElementById("output").innerHTML = typeof person;
      &lt;/script&gt;&lt;p&gt;Set the variable to different value and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    object
    Set the variable to different value and then try...
    

    JavaScript typeof Operator to Check Function Type

    Functions are first class citizens in JavaScript. The JavaScript typeof operator returns "function" for all types of functions. Interestingly it returns "function" for classes also.

    constmyFunc=function(){return"Hello world"};typeof myFunc;//returns "function";const func =newFunction();typeof func;//returns "function";classmyClass{constructor(){}}typeof myClass;// returns "function";

    Example

    In the example below, we use typeof operator to check function datatype.

    <html><body><div id="output"></div><script>
    
         const myFunc = function(){return "Hello world"};
         document.getElementById("output").innerHTML = typeof myFunc;
      &lt;/script&gt;&lt;p&gt;Set the variable to different value and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    function
    Set the variable to different value and then try...
    

    JavaScript typeof Operator to Check BigInt Type

    The typeof operator returns "bigint" for BigInt numbers. BigInt values are the numeric values that are too big to be represented by the number primitive.

    typeof100n;// returns "bigint"

    JavaScript typeof Operator in Real-Time Development

    For example, the developer gets the data from API. If there is only a single string, API returns the string response, and for multiple strings, API returns the array of strings. In this scenario, developers require to check whether the type of the response is string or array, and if it is an array, they need to traverse each string of the array.

    Example

    In the example below, we check the type of the response variable and print its value accordingly.

    <html><body><script>
    
         const response = ["Hello", "World!", "How", "are", "you?"];
         if (typeof response == "string") {
            document.write("The response is - ", response);
         } else {
            document.write("The response values are : ");
            // Traversing the array
            for (let val of response) {
               document.write(val, " ");
            }
         }
      &lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The response values are : Hello World! How are you?
    

    JavaScript Arrays and typeof Operator

    Arrays, despite being a type of object in JavaScript, have a distinct behavior with the typeof operator.

    let numbers =[1,2,3];
    typeof numbers;// Output: 'object'

    Arrays return "object" when using typeof operator, so for precise array detection, it's often better to use Array.isArray().

    Example

    <html><body><div id="output"></div><script>
    
         let numbers = [1, 2, 3];
         document.getElementById("output").innerHTML = Array.isArray(numbers);
      &lt;/script&gt;&lt;p&gt;Set the variable to different value and then try...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    true
    Set the variable to different value and then try..

  • Conditional Operators

    JavaScript Conditional Operators

    The conditional operator in JavaScript first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation. The conditional operator is also known as the ternary operator.

    The JavaScript conditional (ternary) operator is only operator that takes three operands a condition followed by a question mark (?), then the first expression to be executed if the condition is truthy followed by a colon (:), and finally the second expression to be executed if the condition is falsy.

    There are six falsy values in JavaScript. These are − 0 (zero), false, empty string (” or “”), null, undefined, and NaN. All other values are treated as truthy in JavaScript.

    Syntax

    Following is the syntax of conditional (ternary) operator in JavaScript −

    var variable = condition ? exp1 : exp2;

    Parameters

    Here, we have explained the parameters in the above statement.

    • condition − It is a conditional statement.
    • exp1 − If the conditional statement evaluates truthy, control flow executes the exp1 expression.
    • exp2 − If the conditional statement evaluates falsy, control flow executes the exp2 expression.

    If the value of the condition is any falsy value, the result of the expression will be the value of exp2; otherwise, it will be the value of exp1.

    Example

    In the example below, we compare the value of the num1 and num2 variables in the conditional statement. Here, the conditional statement evaluates true, so the result variable contains the value of the first expression.

    <html><body><div id="output"></div><script>var num1 =90;var num2 =67;var res = num1 > num2 ?"num1 is greater than num2":"num2 is greater than num1";
       document.getElementById("output").innerHTML = res;</script></body></html>

    It will produce the following result −

    num1 is greater than num2
    

    Example

    In the example below, we assign the value to the object property according to the conditional statements result.

    Now, imagine what if you need to write the if-else statement to assign value to each property conditionally. The code will become complex, but with the ternary operator, you can easily do it with a single line of code.

    <html><body><div id="output"></div><script>const year =2004;const obj ={
    	  name:"John",
    	  age: year <2005?"adult":"minor",
    	  city:"New York"};
    
       document.getElementById("output").innerHTML = 
       obj.name +" is "+ obj.age +" and lives in "+ obj.city;</script></body></html>

    It will produce the following result −

    John is adult and lives in New York
    

    Example

    This example demonstrates that you can also use the expression instead of values. According to the conditional statement, control flow evaluates the first or second expression and assigns the resultant value to the ‘result’ variable.

    <html><body><div id="output"></div><script>let operator ='-';let res = operator =='+'?10+20:10-20;
       document.getElementById("output").innerHTML ="The result is: "+ res;</script></body></html>

    It will produce the following result −

    The result is: -10
    

    In short, you can use the ternary or conditional operator to shorten the code, which uses the if-else statement.

    Handling null values

    We can use the JavaScript conational operator to handle null value to set a default value if the user passes a null value.

    Example

    Try the following example −

    <html><body><div id="output"></div><script>constgreet=(user)=>{const name = user? user.name :"stranger";returnHello, ${name};};
       document.getElementById("output").innerHTML =greet({ name:"John"})+"<br>"+greet(null);</script></body></html>

    It will produce the following result −

    Hello, John
    Hello, stranger

  • Assignment Operators

    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 literallet y = x;// right operand is a variablelet 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 OperatorExampleEquivalent To
    = (Assignment)a = ba = b
    += (Addition Assignment)a += ba = a + b
    -= (Subtraction Assignment)a -= ba = a b
    *= (Multiplication Assignment)a *= ba = a * b
    /= (Division Assignment)a /= ba = a / b
    %= (Remainder Assignment)a %= ba = a % b
    **= (Exponentiation Assignment)a **= ba = 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 +"&lt;br&gt;"+"Value of y : "+ y;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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 +"&lt;br&gt;"+"Value of y : "+ y;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Example: String Concatenation Assignment

    <html><body><div id="output"></div><script>let x ="Hello";
    
    x +=" World";
    document.getElementById("output").innerHTML ="Value of x : "+ x;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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 OperatorExampleEquivalent To
    &= (Bitwise AND Assignment)a &= ba = a & b
    |= (Bitwise OR Assignment)a |= ba = a | b
    ^= (Bitwise XOR Assignment)a ^= ba = 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 operand (variable).

    let x &= b;

    In the above statement, it performs bitwise AND on x and b and assigns the result to the variable x.

    <html><body><div id="output"></div><script>let x =7; 
    
    x &amp;=5;
    document.getElementById("output").innerHTML ="Value of x : "+ x;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Bitwise OR Assignment Operator

    The JavaScript bitwise OR assignment (|=) operator performs bitwise OR operation on the operands and assigns the result to the left operand (variable).

    let x |= b;

    In the above statement, it performs bitwise OR on x and b and assigns the result to the variable x.

    <html><body><div id="output"></div><script>let x =7; 
    
    x |=5;
    document.getElementById("output").innerHTML ="Value of x : "+ x;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Bitwise XOR Assignment Operator

    The JavaScript bitwise XOR assignment (^=) operator performs bitwise XOR operation on the operands and assigns the result to the left operand (variable).

    let x ^= b;

    In the above statement, it performs bitwise XOR on x and b and assigns the result to the variable x.

    <html><body><div id="output"></div><script>let x =7; 
    
    x ^=5;
    document.getElementById("output").innerHTML ="Value of x : "+ x;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript Shift Assignment Operators

    A shift assignment operator performs bitwise shift operation on the operands and assign the result to a variable (left operand). These are a combinations two operators, the first bitwise shift operator and second the simple assignment operator.

    Following is the list of the shift assignment operators with example −

    Assignment OperatorExampleEquivalent To
    <<= (Left Shift Assignment)a <<= ba = a << b
    >>= (Right Shift Assignment)a >>= ba = a >> b
    >>>= (Unsigned Right Shift Assignment)a >>>= ba = a >>> b

    Left Shift Assignment Operator

    The JavaScript left shift assignment (<<=) operator performs left shift operation on the operands and assigns the result to the left operand (variable).

    let x <<= b;

    In the above statement, it performs left shift on x and b and assigns the result to the variable x.

    <html><body><div id="output"></div><script>let x =7; 
    
    x &lt;&lt;=2; 
    document.getElementById("output").innerHTML ="Value of x : "+ x;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Right Shift Assignment Operator

    The JavaScript right shift assignment (>>=) operator performs right shift operation on the operands and assigns the result to the left operand (variable).

    let x >>= b;

    In the above statement, it performs right shift on x and b and assigns the result to the variable x.

    <html><body><div id="output"></div><script>let x =7; 
    	x >>=1; 
    
    document.getElementById("output").innerHTML ="Value of x : "+ x;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Unsigned Right Shift Assignment Operator

    The JavaScript unsigned right shift assignment (>>>=) operator performs unsigned right shift operation on the operands and assigns the result to the left operand (variable).

    let x >>>= b;

    In the above statement, it performs unsigned right shift on x and b and assigns the result to the variable x.

    <html><body><div id="output"></div><script>let x =7; 
    
    x &gt;&gt;&gt;=2;
    document.getElementById("output").innerHTML ="Value of x : "+ x;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript Logical Assignment operators

    In JavaScript, a logical assignment operator performs a logical operation on the operands and assign the result to a variable (left operand). Each logical assignment operator is a combinations two operators, the first logical operator and second the simple assignment operator.

    Following is the list of the logical assignment operators with example −

    Assignment OperatorExampleEquivalent To
    &&= (Logical AND Assignment)a &&= ba = a && b
    ||= (Logical OR Assignment)a ||= ba = a || b
    ??= (Nullish Coalescing Assignment)a ??= ba = a ?? b

    Example

    <html><body><div id="output"></div><script>var a =5;var b =10;var result =(a &&= b);
    
    document.getElementById("output").innerHTML ="Value of (a &amp;&amp;= b) =&gt; "+ result +"&lt;br/&gt;";
    result =(a ||= b);
    document.getElementById("output").innerHTML +="Value of (a ||= b) =&gt; "+ result;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

  • Bitwise Operators

    JavaScript Bitwise Operators

    The bitwise operators in JavaScript perform operations on the integer values at the binary level. They are used to manipulate each bit of the integer values. Bitwise operators are similar to logical operators but they work on individual bits.

    JavaScript bitwise operators works on 32-bits operands. In JavaScript, numbers are stored as 64-bit floating point number. JavaScript converts the numbers to 32-bit signed integer before performing the operation. After bitwise operation, it converts the result to 64-bits number.

    There are seven bitwise operators in JavaScript. Following is the list of bitwise operators with description.

    OperatorNameDescription
    &Bitwise ANDReturns 1 if both bits are 1, otherwise 0.
    |Bitwise ORReturns 1 if either bit is 1, otherwise 0.
    ^Bitwise XORReturns 1 if both bits are different, otherwise 0.
    !Bitwise NOTReturns 1 if bit is 0, otherwise 0.
    <<Left ShiftShifts the bits left by pushing zeros in from right and discarding leftmost bits.
    >>Right ShiftShifts the bits right by pushing copies of leftmost bit in from left and discarding rightmost bits.
    >>>Right Shift with ZeroShifts the bits right by pushing zeros in from left and discarding rightmost bits.

    JavaScript Bitwise AND (&) Operator

    The bitwise AND (&) operator performs AND operation on each pair of bits of its integer operands. After the operation, it returns a new integer value with the updated bits.

    When bitwise AND operator is applied on a pair of bits, it returns 1 if both bits are 1, otherwise returns 0.

    Following is the truth table for bitwise AND operation −

    ABA & B
    000
    010
    100
    111

    Let’s understand bitwise AND operation taking an example of 4-bit operands.

    ABA & B
    111100010001
    111100100010
    111101000100
    111110001000

    Example

    Let’s perform bitwise AND (&) operation on 5 and 7. These numbers are represented as 32-bits integer.

    Decimal NumberBinary Equivalent (32-bits)
    500000000000000000000000000000101
    700000000000000000000000000000111
    5 & 700000000000000000000000000000101 (= 5)

    The resultant value of the OR operation of each bit of the 101 and 111 binary numbers is the same as below.

    • 1 & 1 = 1
    • 1 & 0 = 0
    • 1 & 1 = 1

    So, the resultant binary number is 111, which is equal to 7 in the decimal representation.

    <html><body><div id="output"></div><script>const a =5;const b =7;
      document.getElementById("output").innerHTML ="a & b = "+(a & b);</script></body></html>

    It will produce the following result −

    a & b = 5
    

    JavaScript Bitwise OR (|) Operator

    The bitwise OR (|) operator performs OR operation on each pair of bits of its integer operands. After the operation, it returns an integer value with the updated bits.

    When bitwise OR operator is applied on a pair of bits, it returns 1 if either of bits is 1, otherwise returns 0.

    Following is the truth table for bitwise OR operation.

    ABA | B
    000
    011
    101
    111

    Let’s understand bitwise OR operation taking an example of 4-bit operands.

    ABA | B
    111100011111
    111100101111
    111101001111
    111110001111

    Example

    Let’s perform bitwise OR (|) operation on 5 and 7. These numbers are represented as 32-bits integer.

    Decimal NumberBinary Equivalent (32-bits)
    500000000000000000000000000000101
    700000000000000000000000000000111
    5 | 700000000000000000000000000000111 (= 7)

    The resultant value of the OR operation of each bit of the 101 and 111 binary numbers is the same as below.

    • 1 | 1 = 1
    • 1 | 0 = 1
    • 1 | 1 = 1

    So, the resultant binary number is 111, which is equal to 7 in the decimal representation.

    <html><body><div id="output"></div><script>const a =5;const b =7;
      document.getElementById("output").innerHTML ="a | b = "+(a | b);</script></body></html>

    It will produce the following result −

    a | b = 7
    

    JavaScript Bitwise XOR (^) Operator

    The bitwise XOR (^) operator performs exclusive OR operation on each pair of bits of its integer operands. After the operation, it returns an integer value with the updated bits.

    When bitwise XOR operator is applied on a pair of bits, it returns 1 if both bits are different, otherwise returns 0.

    Following is the truth table for Bitwise XOR operation −

    ABA ^ B
    000
    011
    101
    110

    Example

    Let’s perform bitwise XOR (^) operation on 5 and 7.

    Decimal NumberBinary Equivalent (32-bits)
    500000000000000000000000000000101
    700000000000000000000000000000111
    5 ^ 700000000000000000000000000000010 (= 2)

    After performing the bitwise XOR operation of 101 and 111, the resultant binary number is given below.

    • 1 ^ 1 = 0
    • 1 ^ 0 = 1
    • 1 ^ 1 = 0

    So, the resultant binary number is 010, which is equal to 2.

    <html><body><div id="output"></div><script>const a =5;const b =7;
      document.getElementById("output").innerHTML ="a ^ b = "+(a ^ b);</script></body></html>

    It will produce the following output −

    a ^ b = 2
    

    JavaScript Bitwise NOT (~) Operator

    The bitwise NOT (~) operator performs the NOT operation on each bit of the binary number. It is a unary operator that inverts each bit of the binary number and returns the 2s complement to the binary number.

    Following is the truth table for the Bitwise XOR operation.

    Input (A)Output (~A)
    01
    10

    Example

    Let’s perform bitwise NOT (~) operation.

    Decimal NumberBinary Equivalent (32-bits)
    500000000000000000000000000000101
    700000000000000000000000000000111
    ~511111111111111111111111111111010 (= -6)
    ~711111111111111111111111111111000 (= -8)

    Try to execute the below code −

    <html><body><div id="output"></div><script>const a =5;const b =7;
      document.getElementById("output").innerHTML ="~a = "+(~a)+"<br>"+"~b = "+(~b)</script></body></html>

    It will produce the following output −

    ~a = -6
    ~b = -8
    

    Bitwise Left Shift (<<) Operator

    The JavaScript bitwise left shift (<<) operator 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 from the right and left most bits are discarded.

    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.

    Example

    When you left shift 5 (101) by 1, a value becomes 10 (1010). When you perform the left shift operation by 2 places, the resultant value is 20 (10100).

    Decimal NumberBinary Equivalent (32-bits)
    500000000000000000000000000000101
    500000000000000000000000000001010 (= 10)
    500000000000000000000000000010100 (= 20)

    The following JavaScript program demonstrates the bitwise left shift operation −

    <html><body><div id="output"></div><script>const a =5;
      document.getElementById("output").innerHTML ="a << 1 = "+(a <<1)+"<br>"+"a << 2 = "+(a <<2);</script></body></html>

    It will produce the following output −

    a << 1 = 10
    a << 2 = 20
    

    Bitwise Right Shift (>>) Operator

    The bitwise right shift (>>) operator moves all the bits in its first operand to the right by the number of places specified in the second operand. It inserts copies of leftmost bit in from left and discard rightmost bits. In this way it preserves the sign of the number.

    In short, it removes the N last bits from the number. Here, N is a second operand. Right-shifting the binary number is equivalent to dividing the decimal number by 2.

    Example

    In the below example, when we perform the right shift operation on 101 for the first time, the value of a becomes equal to 010. After performing the right-shift operation for the second time, the resultant value is 001, equal to 1 in the decimal representation.

    Decimal NumberBinary Equivalent (32-bits)
    500000000000000000000000000000101
    5 >> 100000000000000000000000000000010 (= 2)
    ~511111111111111111111111111111010 (= -6)
    ~5 >>111111111111111111111111111111101 (= -3)

    Try to execute the following program −

    <html><body><div id="output"></div><script>const a =5;
      document.getElementById("output").innerHTML ="a >> 1 = "+(a >>1)+"<br>"+"~a >> 1 = "+(~a >>1);</script></body></html>

    It will produce the following output −

    a >> 1 = 2
    ~a >> 1 = -3
    

    Bitwise Right Shift with Zero (>>>) Operator

    The Right Shift with Zero (>>>) operator is very similar to the right shift operator. It always fills the left bits with zero without worrying about the sign of the bit.

    Example

    Here, the binary representation of 10 is 1010. When we perform the right shift with zero operation, it moves all bits 2 times in the right direction and inserts two 0 at the start. So, the resultant value will be 0010, equal to 1.

    Decimal NumberBinary Equivalent (32-bits)
    500000000000000000000000000000101
    5 >>> 100000000000000000000000000000010 (= 2)

    The following JavaScript program demonstrate the use of >>> operator.

    <html><body><div id="output"></div><script>const a =5;
      document.getElementById("output").innerHTML ="a >>> 1 = "+(a >>>1);</script></body></html>

    It will produce the following result −

    a >>> 1 = 2
    

    You may try to use the different inputs with each operator and observe the output for more practices.

  • Logical Operators

    JavaScript Logical Operators

    The logical operators in JavaScript are generally used with Boolean operands and return a boolean value. There are mainly three types on logical operators in JavaScript – && (AND), || (OR), and ! (NOT). These operators are used to control the flow the program.

    Although the logical operators are typically used with Boolean values, they can be used with any type. For each non-boolean value, the operator converts to a boolean. The falsy values are converted to false and truthy values to true.

    There are six falsy values in JavaScript: false, null, undefined, 0 (zero), “” (empty string), NaN. The value other than falsy values are treated as truthy values. So non zero numbers, non-empty strings, etc., are truthy values.

    The && and || operators return the value of one of the operands based on condition. So if the operands are non-boolean, they return a non-boolean value. The ! operator always returns a Boolean value.

    The operands may be literals, variables or expressions. These are first evaluated to boolean equivalent before performing the logical operation.

    In the below table, we have given the logical operators with its description and example. Lets assume: x = true, y = false.

    OperatorDescriptionExample
    &&Logical AND(x && y) is false.
    ||Logical OR(x || y) is true.
    !Logical NOT!(x) is false.

    JavaScript Logical AND (&&) Operator

    The logical AND (&&) operator evaluates the operands from left to right. If the first operand can be converted to false, it will return the value of first operand, otherwise it will return the value of the second operand.

    x && y
    

    In the above expression if x is a falsy value then it will return the value of x otherwise it will return the value of y.

    The above rule is followed for all types of operands, whether they are Boolean values, numbers or strings, etc.

    Let’s first discuss with Boolean operands. In general, for a set of Boolean operands, it will return true if both operands are true else it returns false.

    true&&true;// returns truetrue&&false;// returns falsefalse&&true;// returns falsefalse&&false;// returns false

    For number operands, the && operator will return the first operand if it is flasy values (0, -0, and 0n), otherwise second operand.

    0&&10;// returns 010&&20;// returns 20 20&&0;// returns 0

    For string values, empty string is converted to false and non-empty string to true. Look at the below example.

    let str1 ='';let str2 ='Hello';let str3 ='World';  
    console.log(str1 && str2);// returns '' empty string
    console.log(str2 && str3);// returns World

    Let’s look how && operator works for null and undefined −

    null&&true// return nullundefined&&true// returns undefined

    For all above examples, you have noticed that if the first operand can be converted to false then it returns the value of first operand otherwise the value of second operand.

    Example

    Now let’s look at an example of a logical expression.

    <html><body><div id="output"></div><script>const x =3;const y =-2;
      document.getElementById("output").innerHTML = x >0&& y >2;</script></body></html>

    Here x > 0 is evaluated to true and y > 2 is evaluated to false. And the final expression becomes true && false which is evaluated as false.

    Multiple && Operators

    If we have multiple && operators in an expression, the && operator evaluates the expression from left to right and it converts each operand to a boolean value. If the result is false, then it returns the value of that operand and terminates the execution. If all the operands are truthy then it returns the value of the last operand.

    10&&null&&false;// returns nulltrue&&10&&20;// returns 20

    JavaScript Logical OR (||) Operator

    The logical OR (||) operator also evaluates the operands from left to right. If the first operand can be converted to true, it will return the value of first operand, otherwise it will return the value of the second operand.

    x || y
    

    In the above expression if x is a truthy value then it will return the value of x otherwise it will return the value of y.

    As || is a logical operator but it can be applied to any type of operand not only boolean.

    Let’s first discuss with Boolean operands. In general, for a set of Boolean operands, it will return flase if both operands are false else it returns true.

    true||true;// returns truetrue||false;// returns truefalse||true;// returns truefalse||false;// returns false

    For number operands, the || operator will return the first operand if it is truthy values (other than 0, -0, and 0n), otherwise second operand.

    0||10;// returns 1010||20;// returns 1020||0;// returns 20

    For string values, empty string is converted to false and non-empty string to true. Look at the below example.

    Example

    <html><body><div id="output"></div><script>let str1 ='';let str2 ='Hello';let str3 ='World';  
      document.getElementById("output").innerHTML = 
      str1 || str2 +"<br>"+
      str2 || str3;</script></body></html>

    Let’s look how && operator works for null and undefined −

    null||true;// returns trueundefined||true;// returns true

    For all above examples, you have noticed that if the first operand can be converted to true then it returns the value of first operand otherwise the value of second operand.

    Example

    Now let’s look at an example with expression −

    <html><body><div id="output"></div><script>const x =3;const y =-2;
      document.getElementById("output").innerHTML = x >0|| y >2;</script></body></html>

    Multiple || Operators

    We may have multiple || operators in an expression. The || operator evaluates the expression from left to right and it converts each operand to a boolean value. If the result is true, then it returns the value of that operand and terminates the execution. If all the operands are falsy then it returns the value of the last operand.

    null||10||false// returns 10false||null||undefined// returns undefined

    JavaScript Logical NOT (!) Operator

    The logical NOT (!) Operator is a unary operator. It returns false if the operand can be converted to true, otherwise it returns true.

    !x
    

    If x is truthy, the NOT (!) operator returns false. If the x is falsy then it returns true.

    Same as Logical AND, and OR operators, this logical NOT operator can also be used with non-boolean operands. But it will always return a Boolean value.

    Example

    <html><body><div id="output"></div><script>
      document.getElementById("output").innerHTML =!true+"<br>"+!false+"<br>"+!0+"<br>"+!20+"<br>"+!('Hello World')</script></body></html>

    Logical Operators Precedence

    An expression may have more than one logical operators in JavaScript. In such situation, the operators are evaluated on the basis of their precedence. The NOT (!) operator has the highest precedence. Then AND (&&) operator has the higher precedence than OR (||) operator.

    • Logical NOT (!)
    • Logical AND (&&)
    • Logical OR (||)

    Example

    Let’s check the following example −

    <html><body><div id="output"></div><script>
      document.getElementById("output").innerHTML =(false||true&&!false)// returns true</script></body></html>

    The logical NOT (!) operator has the highest precedence so !false is evaluated to true. Hence the expression now looks like “false || true && true”. The && has higher precedence than || so next “true && true” will be evaluated. Now the expression looks like “false || true”. Finally “false || true” will be evaluated to true.

    Short Circuit Evaluation

    Logical expressions are evaluated from left to right. These are tested for short-circuit evaluation. Following is the rule of short circuit evaluation −

    • false && any_value returns false
    • true || any_value retuns true

    The any_value part is not evaluated so it doesn’t have any effect on final result.