Category: Operators

  • Operator Precedence

    In JavaScript, operator precedence ensures the priority of the operators to be executed when a single expression contains multiple operators. So, whatever expressions have higher priority, the compiler executes it first over other operators and then executes the operators with the lower precedence.

    Whenever you write any JavaScript expression with only 1 or 2 operators, you can easily understand the output of the expression. But when the expression contains multiple operators, you should know the concept of operator precedence to evaluate the expression correctly.

    The best example of operator precedence is that in traditional mathematics, the multiplication operator has higher precedence over the addition or subtraction operator. So, if any mathematical expression contains the multiplication and addition of both operators, you need to perform the multiplication first.

    Associativity

    The term associativity refers to the direction compiler should follow while evaluating the expression. In many situations, operators have the same precedence. In such cases, ambiguity occurs that which operation the compiler should perform first. So, the compiler takes the help of associativity. It can be from left to right or right to left.

    For example, we need to execute the below expression.

    let res =50/5*2;
    • Considering the above expression as (50/5) * 2 gives 20 as an output.
    • Evaluating the expression like 50/ (5*2) gives the 5 as a resultant value.

    To resolve the above ambiguity, the compiler uses the associativity rule. The associativity for the division and multiplication operator is from left to right. So, it evaluates the expression as (50 / 5) * 2.

    The assignment operator has right-to-left associativity. Consider the below assignment expression.

    P= q =90;

    In the above expression, 90 is assigned to the q, and the value of the q variable is assigned to the p.

    In short, the JavaScript compiler evaluates the expression based on the operator precedence, and when multiple operators have the same precedence, it uses the associativity rule.

    Operator Precedence Table

    The below table contains the operator, its description, associativity direction, and a short example.

    Operator PrecedenceOperatorDescriptionAssociativityExample
    1()GroupingL -> R(expression)
    2.Member of objectL -> RObject_name.property
    2()Function callL -> RDemo()
    2newTo create objectsR -> LNew test()
    2[]Member of objectL -> RObject[“property”]
    3Postfix decrementp–;
    3++Postfix incrementp++
    4Prefix decrementR -> L–p;
    4++Prefix incrementR -> L++p;
    4typeofTo get the variable typeR -> Ltypeof a;
    4!Logical notR -> L!a;
    4~Bitwise notR -> L~p
    4Unary minusR -> L-p
    4+Unary plusR -> L+p
    4deleteTo delete object propertyR -> LDelete arr[0]
    4voidEvaluates voidR -> LVoid(1)
    5**Exponentiation operatorR -> Lp ** q
    6*MultiplicationL -> Rp * q
    6/DivisionL -> Rp / q
    6%moduloL -> Rp % q
    7+Addition or plus operatorL -> Rp + q
    7Subtraction operatorL -> Rp – q
    8<<Left shiftL -> Rp << 2
    8>>Signed right shiftL -> Rp >> 2
    8>>>Unsigned right shiftL -> Rp >>> 2
    9inProperty in objectL -> Rx in y
    9instanceofInstance of objectL -> Rp instanceof Object
    9<Less thanL -> Rp < q
    9<=Less than or equal toL -> Rp <= q
    9>Greater thanL -> Rp > q
    9>=Greater than or equal toL -> Rp >= q
    10==EqualityL -> Rp == q
    10!=InequalityL -> Rp != q
    10===Strict equalityL -> Rp === q
    10!==Strict inequalityL -> Rp !== q
    11&Bitwise ANDL -> Rp & q
    12^Bitwise XORL -> Rp ^ q
    13|Bitwise ORL -> Rp | q
    14&&Logical ANDL -> Rp && q
    15||Logical ORL -> Rp || q
    16??Nullish CoalescingR -> Lp ?? q
    17=AssignmentR -> Lp = q
    17:Colon assignmentR -> Lp : q
    17+=Addition assignmentR -> Lp += q
    17-=Subtraction assignmentR -> Lp -= q
    17*=Multiplication assignmentR -> Lp *= q
    17/=Division assignmentR -> Lp /= q
    17%=Modulo assignmentR -> Lp %= q
    17**=Exponentiation assignmentR -> Lp **= q
    17<<=Left shift assignementR -> Lp <<= q
    17>>=Right shift assignmentR -> Lp >>= q
    17>>>=Unsigned right shift assignmentR -> Lp >>>= q
    17&=Bitwise AND assignmentR -> Lp &= q
    17^=Bitwise XOR assignmentR -> Lp ^= q
    17|=Bitwise OR assignmentR -> Lp |= q
    17&&=Logical AND assignmentR -> Lp &&= q
    17||=Logical OR assignementR -> Lp ||= q
    17=>Arrow operator(a, b )=> { // function code}
    17Spread operator[ arr]
    18yieldPause / ResumeR -> Lyield p;
    19,Comma operatorL -> R(10, 20, 30)

    Examples

    Let’s understand the operator precedence via simple examples.

    Example

    In the example below, the first expression contains the division, modulo, and multiplication operators with the same precedence. So, the compiler will use the associativity rule, which is left to right for multiplication, division, and modulo operator.

    So, it divides the 30 by 15, takes modulo of (30/15) with 3, and multiples the ((30/15)%3) with 2.

    In the second expression, the exponentiation operator has right-to-left associativity. So, it evaluates the expression same as (2 *8 (3 ** 2)).

    <html><body><div id ="output"></div><script>const first =30/15%3*2;const second =2**3**2;
    
         document.getElementById("output").innerHTML ="The value of first expression is : "+ first +"&lt;br&gt;"+"The value of second expression is : "+ second;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    It will produce the following result −

    The value of first expression is : 4
    The value of second expression is : 512
    

    Example

    This code demonstrates that you can use the grouping operator () to change the operator precedence. In the below code, we have taken the same expressions which we have taken in the above code, but we change the operator precedence.

    In the first expression, first, we take modulo and multiply the resultant value with 2. So, we get 0 and divide 30 by 0, returning infinity.

    In the second expression, the first expression evaluates the (2 ** 3) and (8 ** 2), which is equal to 64.

    <html><body><div id ="output"></div><script>const first =30/((15%3)*2);const second =(2**3)**2;
    
         document.getElementById("output").innerHTML ="The value of first expression is : "+ first +"&lt;br&gt;"+"The value of second expression is : "+ second;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The value of first expression is : Infinity
    The value of second expression is : 64
    

    The grouping operator can change operator precedence for any operator as it has the highest operator precedence.

  • Exponentiation Operator

    Exponentiation Operator

    The exponentiation operator in JavaScript is represented as **. The exponentiation operator takes two operands and returns the power of the first operand raised to the second.

    The exponentiation operator can also accept the variables of the BigInt data type as operands. Also, it follows the property of associativity, which means a**b**c and a**(b**c) expressions give the same result.

    The exponentiation operator evaluates the expression from right to left.

    Syntax

    We should follow the syntax below to use the exponentiation operator.

    let pow = x ** y;

    Return value

    It returns the result of raising the first operand (x) to the power of the second operand (y).

    Examples

    Let’s understand the exponentiation operator in details with the help of some examples.

    Example

    The example below defines the p and q variables containing the 2 and 3 values. After that, we used the exponentiation operator to get the PQ. In the output, you can observe the value of the ‘pow’ variable, which is 23, equal to 8.

    <html><body><div id ="output"></div><script>let p =2;let q =3;let pow = p ** q;
    
      document.getElementById("output").innerHTML ="The value of p ** q: "+ pow;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    The value of p ** q: 8
    

    Example: Associativity of Exponentiation Operator

    This example demonstrates that the exponentiation operator follows the associativity property and evaluates the expression from right to left.

    Both expressions print the 6561 in the output, equal to the 38, where 8 equals the 23.

    <html><body><div id="output"></div><script>let p =3;let q =2;let r =3;let pow1 = p ** q ** r;let pow2 = p **(q ** r);
    
    
      document.getElementById("output").innerHTML ="pow1 = "+ pow1 +"&lt;br&gt;"+"pow2 = "+ pow2;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    pow1 = 6561
    pow2 = 6561
    

    Example: Exponentiation operator with BigInt variables

    The below example demonstrates that the exponentiation operator can also be used with the bigint numbers. It returns the bigint value in the output.

    <html><body><div id ="output"></div><script>let p =10000000000000000000000000000n;let q =2n;let pow = p ** q;
    
      document.getElementById("output").innerHTML ="pow = "+ pow;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    pow = 100000000000000000000000000000000000000000000000000000000
    

    Example: Exponentiation operator with non-numeric values

    When you use the non-numeric value as an operand of the exponentiation operator, it converts the value to numeric and returns the result. If the operand can't be converted to the numeric value, it returns NaN in the output.

    Here, it converts the '[]' to 0 and gives the correct result. The numeric value for the string '2a' is NaN, so it prints the NaN in the output. If the array contains a single numeric element, it parses the element. Otherwise, it evaluates NaN if the array contains multiple elements.

    <html><body><div id ="output"></div><script>const output = document.getElementById("output");let pow =2**[];// Number([]) = 0
    
      output .innerHTML ="10 ** [] = "+ pow +"&lt;br&gt;";
      pow =[]**2;// Number([]) = 0
      output.innerHTML +="[] ** 2 = "+ pow +"&lt;br&gt;";
      pow =2**[2];// Number([2]) = 2    
      output.innerHTML +="10 ** [2] = "+ pow +"&lt;br&gt;";
      pow ="2"**2;// Number("2") = 2
      output.innerHTML +="2 ** 2 = "+ pow +"&lt;br&gt;";
      pow ="2a"**2;// Number("2a") = NaN
      output.innerHTML +="2a ** 2 = "+ pow +"&lt;br&gt;";
      pow =[2,3]**2;// Number([2, 3]) = NaN
      output.innerHTML +="[2, 3] ** 2 = "+ pow +"&lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    10 ** [] = 1
    [] ** 2 = 0
    10 ** [2] = 4
    2 ** 2 = 4
    2a ** 2 = NaN
    [2, 3] ** 2 = NaN
    

    The exponentiation operator is an alternative to the pow() method of the Math() object.

  • Spread Operator

    What is a Spread Operator?

    The JavaScript spread operator () allows us to spread out elements of an iterable such as an array. The spread operator is represented with three dots (). This is operator is introduced in ES6. The main use cases of the spread operator are to copy array elements, concatenate arrays or objects with rest parameters, etc.

    Let’s take an example to expand the elements of an array

    let x =["Tutorials","Point"];
    console.log(x);// [ 'Tutorials', 'Point' ]
    console.log(...x);// Tutorials Point

    Spread Operator to Concatenate Arrays

    The JavaScript spread operator can be used to concatenate the arrays.

    Example

    In the below example, we have defined two different arrays. After that, we used the spread operator to concatenate these arrays.

    <html><body><div id ="output"></div><script>const nums1 =[10,20,30];const nums2 =[40,50,60];const res =[...nums1,...nums2];
    
      document.getElementById("output").innerHTML = res;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    10,20,30,40,50,60
    

    You can also change the concatenation order of the array.

    Spread Operator to Clone an Array

    In JavaScript, when we assign one array (object) to another array, it assigns the reference rather than cloning the array. So, whenever you update the original array, it also updates the cloned array. The assignement operator creates a deep copy of the array.

    Example: Without Using Spread Operator

    In this example, we defined an array named nums1. We defiend another array named nums2 and assigned the array nums1 to array nums2. Here, you can see that when you change nums1, it also updates the nums2.

    <html><body><div id ="result1"></div><div id ="result2"></div><script>const nums1 =[10,20,30];const nums2 = nums1;
    
      document.getElementById("result1").innerHTML = nums2;
      nums1.push(40);
      document.getElementById("result2").innerHTML = nums2;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    10,20,30
    10,20,30,40
    

    Example: Using Spread Operator to Clone Arrays

    Using the spread operator to clone the array creates an actual copy of the array, and the cloned array doesn't change when you make changes to the original array. Here, you can see that nums3 doesn't get updated even if you change the nums1.

    <html><body><div id ="result1"></div><div id ="result2"></div><script>const nums1 =[10,20,30];const nums3 =[...nums1];
    
      document.getElementById("result1").innerHTML = nums3;
      nums1.push(50);
      document.getElementById("result2").innerHTML = nums1 +"&lt;br&gt;";
      document.getElementById("result2").innerHTML += nums3;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    10,20,30
    10,20,30,50
    10,20,30
    

    Spread Operator to Concatenate Objects

    You can use the spread operator to copy object properties into another object. Here, consider the 'car' object as a parent object containing similar properties to all cars. After that, created the 'BMW' object, representing the particular car, and concatenated all properties of the 'car' object with the 'BMW' object's property.

    <html><body><div id ="result1"></div><div id ="result2"></div><script>const car ={
    
         gears:6,
         color:"Black"}
      document.getElementById("result1").innerHTML =JSON.stringify(car);constBMW={
         model:"X5",
         year:2019,...car,}
      document.getElementById("result2").innerHTML =JSON.stringify(BMW);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    {"gears":6,"color":"Black"}
    {"model":"X5","year":2019,"gears":6,"color":"Black"}
    

    Function Rest Parameters

    When you need to pass an unknown number of arguments to the function, you can use the spread operator with the function parameters, called the rest parameter.

    Here, you can see that we have passed multiple numbers as a function argument and collected all arguments in the nums[] array using the spread operator except the first argument.

    <html><body><div id ="result"></div><script>functionsum(a, ...nums){let sum = a;for(let i =0; i < nums.length; i++){
    
            sum += nums[i];}
         document.getElementById("result").innerHTML = sum;}sum(3,6,9,8,6,5,3,3,2,1);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    It will produce the following result −

    46
    

    You can also use the spread operator to expand the string into the array of characters, clone the string, or concatenate the string. Also, set, map, etc., are iterable objects in JavaScript. So, you can use the spread operator with them.

  • Yield Operator

    JavaScript Yield Operator

    The yield operator in JavaScript is used to pause and resume the generator function asynchronously. In JavaScript, generator functions are the special functions that you can pause or resume while executing. The generator functions are defined with the ‘function*’ syntax. The yield keyword can only be used within the generator function that contains it.

    The yield operator pauses the execution of generator function and returns its operand (expression) to the generator’s caller.

    Syntax

    The syntax of the yield operator in JavaScript is as follows −

    yield expression;

    Paramter

    • expression − The value to yield from the generator function via the iterator protocol. ‘undefined’ is yielded, if expression is omitted.

    Return value

    It returns the optional value passed to the generator’s next() method to resume its execution.

    Yield Operator in Genrator Function

    To understand the yield operator, let’s understand fist the working of the generator function.

    When a generator function is called, it returns a generator object. When the next() method this generator object is called it resumes the execution of the generator function. When a yield expression is encountered, it pauses the execution and returns the expression after yield keyword to the object’s caller (the next() method).

    The next() method of the generator object returns an iterator object with two properties value and done. The value is the actual value of the expression and the done is a boolean value. The done property is true if the execution of the generator function is completely executed, else it if false.

    Below is a complete example code of generator function with yield keyword (operator).

    function*test(){// function codeyield expression;}const genObj =test();
    genObj.next();

    In the above syntax, ‘function*’ is used to create a generator function named test, and the yield keyword is used to return ‘expression’ from the function.

    The generator function test is called and assigned the returned generator object to the variable genObj. The next() method resumes the execution of the function and returns iterator object when encounters yield expression.

    Let’s execute the below JavaScript code snippet

    function*test(){
    
    console.log("I'm before yield expression");yield20;}const genObj =test();
    console.log(genObj.next());

    Notice when we call next() method, it display the message in the console first and then display the iterator object.

    I'm before yield expression
    { value:20, done:false}

    Example: Returning a value

    In the example below, we have defined the test() generator function. We used the yield operator 3 times in the function to return a number, an array, and a string, respectively.

    After that, we used the next() method four times to resume the execution of the function. Whenever the control flow finds the yield operator, it will stop execution and return the value.

    In the output, you can observe that it returns the object containing the operand of the yield operator and boolean value.

    function*test(){yield20;yield[1,2,3];yield"Hello World";}let res =test();
    console.log(res.next());
    console.log(res.next());
    console.log(res.next());
    console.log(res.next());

    Output

    { value: 20, done: false }
    { value: [ 1, 2, 3 ], done: false }
    { value: 'Hello World', done: false }
    { value: undefined, done: true }
    

    Example: Returning undefined

    When we omit the expression following the yield keyword, it will return undefined.

    function*test(){yield;}let res =test();
    console.log(res.next());
    console.log(res.next());

    Output

    { value: undefined, done: false }
    { value: undefined, done: true }
    

    Example: Passing a value to the next() method

    We can also pass a value to the next() method. In the below example, we have passed 30 to the second next() method. It evaluates yield to 30. The variable result is assigned the value of yield which is evaluated as 30.

    function*test(){let result =yield20;
    
    console.log("default value paased to next() method "+ result);}let res =test();
    console.log(res.next()); console.log(res.next(30));

    Output

    { value: 20, done: false }
    default value paased to next() method 30
    { value: undefined, done: true }
    

    Example

    In the below code, we used the loop, and in each operation, we stop the execution of the function using the yield operator. Afterward, we use the next() method to start the execution of the generator function.

    // Generator functionfunction*test(){for(let p =0; p <6; p +=2){yield p;}}let res =test();
    console.log(res.next());
    console.log(res.next());
    console.log(res.next());
    console.log(res.next());

    Output

    { value: 0, done: false }
    { value: 2, done: false }
    { value: 4, done: false }
    { value: undefined, done: true }
    

    In real-time development, programmers use the ‘yield’ operator for asynchronous operations, lazy evaluations, task scheduling, iterating through large datasets, creating custom iterators, etc.

  • 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..