JavaScript - tutorial - 02 - operators

revision:


Content

an operand is what operators are applied to. arithmetic operators assignment operators comparison operators logical operators "typeof" operator "delete" operator "in" operator "instanceof" operator "bitwise" operators operators examples


an operand is what operators are applied to.

top

Operand - operators: the numbers (in an arithmetic operation) are called operands. The operation (to be performed between the two operands) is defined by an operator. An operator is unary if it has a single operand. An operator is binary if it has two operands. Operations run from left to right.

Grouping operators: operations within brackets are executed earlier than those outside.

Order of operations: B I D M A S, i.e. brackets, indices, division, multiplication, addition, substraction.

examples


code:
                    <div class="spec">
                        <a id="id1"></a><br>
                        <a id="id2"></a><br>
                        <a id="id3"></a> 
                    </div>
                    <script>
                            document.getElementById('id1').innerHTML = "string + number: " +(2+2+"1");
                            document.getElementById('id2').innerHTML = "string + number: " + (2+"2"+1);
                            document.getElementById('id3').innerHTML = "string + number: " + ("1"+2+3);
                    </script>
                

The assignment operator (=) assigns a value to a variable.


arithmetic operators

top

the addition operator (+) adds numbers.

The + operator can also be used to add (concatenate) strings. When used on strings, the "+" operator is called the concatenation operator.

Adding two numbers, will return the sum, but adding a number and a string will return a string. The rule is simple: if either operand is a string, the other one is converted into a string as well.

String concatenation and conversion is a special feature of the binary plus "+". If the operand is not a number, the unary plus converts it into a number.

P.S. Other arithmetic operators work only with numbers and always convert their operands to numbers.

examples






















code:
                    <div class="spec">
                        <a id="id4"></a><br><br> 
                        <a id="id5"></a><br><br> 
                        <a id="id6"></a><br><br>  
                        <a id="id7"></a><br><br> 
                        <a id="id8"></a><br><br> 
                        <a id="id9"></a><br><br>  
                        <a id="id10"></a><br><br>  
                        <a id="id11"></a><br><br>  
                        <a id="id12"></a><br><br>  
                        <a id="id13"></a><br><br>  
                        <a id="id14"></a><br><br>  
                    </div>
                    <script>
                        let s = "my" + "string"; document.getElementById('id4').innerHTML = "string + string: " + s;
                        document.getElementById('id5').innerHTML = "string + number: " + ("1" + 2);
                        document.getElementById('id6').innerHTML = "string + number: " + (2 + "1");
                    
                        let x=1; document.getElementById('id7').innerHTML = "positive number: "  + x;
                        let y = -2; document.getElementById('id8').innerHTML = "negative number: " + y;
                        document.getElementById('id9').innerHTML = "true: " + true;
                        document.getElementById('id10').innerHTML = "empty variable" +'';
            
                        let apples = "2";
                        let oranges = "3";
                            document.getElementById('id11').innerHTML = "addition: " + (apples + oranges);
                                
                        let apples1 = '2';
                        let oranges1 = '5';
                            document.getElementById('id12').innerHTML = "adding of string numbers: " +  (+apples1 + +oranges1);
                            document.getElementById('id13').innerHTML =  "adding of string numbers: " + (Number(apples1) + Number(oranges1));
            
                        let apples2 = 2;
                        let oranges2 = 3;
                            document.getElementById('id14').innerHTML = "adding numbers: " +(apples2 + oranges2);
                    </script>
                

the subtraction operator (-) subtracts numbers.

examples
code:
                    <div class="spec">
                        <a id="id15"></a>      
                    </div>
                    <script> 
                        document.getElementById('id15').innerHTML = "substraction number and string: " + (2 - "1");
                    </script>
                

the multiplication operator (*) multiplies numbers.

examples
code:
                    <div class="spec">
                        <a id="id15a"></a>  
                    </div>
                    <script>
                        var x1 = 5;
                        var y1 = 2;
                        var z1 = x1 * y1;
                        document.getElementById("id15a").innerHTML = z1;
                    </script>
                

the division operator (/) divides numbers.

examples
code:
                    <div class="spec">
                        <a id="id16"></a>  
                    </div>
                    <script>
                    document.getElementById('id16').innerHTML = ("6"/"2");
                    </script>
                
code:
                    <div class="spec">
                        <a id="id16a"></a> 
                    </div>
                    <script>
                        var x2 = 5;
                        var y2 = 2;
                        var z2 = x2 / y2;
                        document.getElementById("id16a").innerHTML = z2;
                    </script>
                

the modulus/remainder operator (%) returns the division remainder.

examples






code:
                    <div class="spec">
                        <a id="id18"></a><br><br>
                        <a id="id19"></a><br><br>
                        <a id="id20"></a><br><br>
                        <a id="id21"></a>
                    </div>
                    <script>
                        document.getElementById('id18').innerHTML = (10/2);
                        let radius = 7;let pi = 3.1415;
                        let result2 = radius % 3;
                        let result3 = pi * radius**2;
                        document.getElementById('id19').innerHTML = result2;
                        document.getElementById('id20').innerHTML = result3;   
                        let result4 = 5 * (10-3)**2;
                        document.getElementById('id21').innerHTML = result4;
                    </script>
                

the increment operator (++) increments numbers.

examples
code:
                    <div class="spec">
                        <a id="id22"></a>  
                    </div>
                    <script>
                        var xx = 5;
                        xx++;
                        var zz = xx;
                        document.getElementById("id22").innerHTML = zz;
                    </script>
                

the decrement operator (--) decrements numbers.

examples

code:
                    <div class="spec">
                        <a id="id22"></a><br> 
                    </div>
                    <script>
                        let likes = 10;
                        likes = likes + 1;
                        likes++;
                        likes--;
                        likes += 10;
                        likes -=5;
                        likes *= 2;
                        likes /=2;
                        document.getElementById('id22').innerHTML = "likes: " + likes;
                    </script> 
                

the exponentiation operator (**) raises the first operand to the power of the second operand.

"x**y" produces the same result as "Math.pow(x,y)".

examples
code:
                    <div class="spec">
                        <a id="id24"></a>
                    </div>
                    <script>
                        var xxx = 5;
                        document.getElementById("id24").innerHTML = "5 to power 2: " + Math.pow(xxx,2);
                    </script> 
                

Instead of using the Math.pow() function to raise a number to a power, you can use the ** operator as a shorthand.

longhand

                    Math.pow(2,3); // 8
                    Math.pow(2,2); // 4
                    Math.pow(4,3); // 64
                    const power = Math.pow(4, 3); // 64
                

shorthand

                    2**3 // 8
                    2**2 // 4
                    4**3 // 64
                    const power = 4**3; // 64
                

assignment operators

top

the assignment operator ("=") assigns a value to a variable.

examples
code:
                    <div class="spec">
                        <a id="id25"></a>
                    </div>
                    <script>
                        var a = 10;
                        document.getElementById("id25").innerHTML = "10: " + a;
                    </script>
                

the addition assignment operator ("+=") adds a value to a variable.

The += assignment operator can also be used to add (concatenate) strings.

examples
code:
                    <div class="spec">
                        <a id="id26"></a> 
                    </div>
                    <script>
                        var b = 10;
                        b += 5;
                        document.getElementById("id26").innerHTML = "10 += 5: " + b;
                    </script>
                

the substraction assignment operator ("-=")subtracts a value from a variable.

examples
code:
                    <div class="spec">
                        <a id="id27"></a> 
                    </div>
                    <script>
                        var c = 10;
                        c -= 5;
                        document.getElementById("id27").innerHTML = "10 -= 5: " + c;
                    </script>
                

the multiplication assignment operator("*=") multiplies a variable.

examples
code:
                    <div class="spec">
                        <a id="id28"></a>
                    </div>
                    <script>
                        var d = 10;
                        d *= 5;
                        document.getElementById("id28").innerHTML = "10 *= 5: " + d;
                    </script>
                

the division assignment operator("/=") divides a variable.

examples
code:
                    <div class="spec">
                        <a id="id29"></a>
                    </div>
                    <script>
                        var e = 10;
                        e /= 5;
                        document.getElementById("id29").innerHTML = "10 /= 5: " + e;
                    </script>
                

the modulus/remainder assignment operator("%=") assigns a remainder to a variable.

examples
code:
                    <div class="spec">
                        <a id="id30"></a>
                    </div>
                    <script>
                        var f = 10;
                        f %= 5;
                        document.getElementById("id30").innerHTML = "10 %= 5: " + f;
                    </script>
                

comparison operators

top

double and triple equality

The equality operator (==) checks whether its two operands are equal, returning a Boolean result. Double equals (==) is a "comparison operator" that transforms the operands having the same type before comparison. It tests for abstract equality, meaning that before doing the equality comparison it performs the necessary type conversion.

The equality operators (== and !=) use the "abstract equality comparison algorithm" to compare two operands:

if the operands are both objects, return "true" only if both operands reference the same object;
if one operand is "null" and the other is "undefined", return "true";
if the operands are of different types, try to convert them to the same type before comparing:

when comparing a number to a string, try to convert the string to a numeric value;
if one of the operands is Boolean, convert the Boolean operand to 1 if it is true and +0 if it is false;
if one of the operands is an object and the other is a number or a string, try to convert the object to a primitive using the object's valueOf() and toString() methods.

If the operands have the same type, they are compared as follows:

string : return "true" only if both operands have the same characters in the same order;
number : return "true" only if both operands have the same value; +0 and -0 are treated as the same value;
if either operand is NaN, return false;
boolean : return "true" only if operands are both true or both false.

The strict equality operator (===) checks whether its two operands are equal, returning a Boolean result. The strict equality operator always considers operands of different types to be different. It does not attempt type conversion.

The strict equality operators (=== and !==) use the strict equality comparison algorithm to compare two operands:

if the operands are of different types, return "false".
if both operands are objects, return "true" only if they refer to the same object;
if both operands are "null" or both operands are "undefined", return true;
if either operand is NaN, return "false".

Otherwise, compare the two operand's values:

numbers must have the same numeric values; +0 and -0 are considered to be the same value;
strings must have the same characters in the same order;
booleans must be both "true" or both "false".

syntax:

equality operator: x == y

strict equality operator: x=== y
examples

equality operator

code:
                    <div class="spec">
                        <p class="spec" style="margin-left:5vw;" id="op-01"></p>
                        <p class="spec" style="margin-left:5vw;" id="op-02"></p>
                        <p class="spec" style="margin-left:5vw;" id="op-03"></p>
                        <p class="spec" style="margin-left:5vw;" id="op-04"></p>
                        <p class="spec" style="margin-left:5vw;" id="op-05"></p>
                        <p class="spec" style="margin-left:5vw;" id="op-06"></p>
                        <p class="spec" style="margin-left:5vw;" id="op-07"></p>
                    </div>
                    <script>
                        const string1 = "hello";
                        const string2 = String("hello");
                        const string3 = new String("hello");
                        const string4 = new String("hello");
        
                        console.log(string1 == string2); 
                        console.log(string1 == string3); 
                        console.log(string2 == string3); 
                        console.log(string3 == string4); 
                        console.log(string4 == string4); 
                        document.getElementById("op-01").innerHTML = "hello == String('hello'): " + (string1 == string2);
                        document.getElementById("op-02").innerHTML = "hello == new String('hello'): " + (string1 == string3);
                        document.getElementById("op-03").innerHTML = "String('hello') ==  new String('hello'): " + (string2 == string3);
                        document.getElementById("op-04").innerHTML = "new String('hello') == new String('hello'): " + (string3 == string4);
                        document.getElementById("op-05").innerHTML = "new String('hello') == new String('hello'): " + (string4 == string4);
                    </script>
                

strict equality operator

code:
                        <div class="spec">
                            <p class="spec" style="margin-left:5vw;" id="op-08"></p>
                            <p class="spec" style="margin-left:5vw;" id="op-09"></p>
                            <p class="spec" style="margin-left:5vw;" id="op-10"></p>
                            <p class="spec" style="margin-left:5vw;" id="op-11"></p>
                            <p class="spec" style="margin-left:5vw;" id="op-12"></p>
                            <p class="spec" style="margin-left:5vw;" id="op-13"></p>
                            <p class="spec" style="margin-left:5vw;" id="op-14"></p>
        
                        </div>
                        <script>
                            console.log("hello" === "hello");   // true
                            console.log("hello" === "hola");    // false
                            console.log(3 === 3);               // true
                            console.log(3 === 4);               // false
                            console.log(true === true);         // true
                            console.log(true === false);        // false
                            console.log(null === null);         // true
                            document.getElementById("op-08").innerHTML = '"hello" === "hello": ' + ("hello" === "hello");
                            document.getElementById("op-09").innerHTML = '"hello" === "hola": ' + ("hello" === "hola");
                            document.getElementById("op-10").innerHTML = '3 === 3: ' + (3 === 3);
                            document.getElementById("op-11").innerHTML = '3 === 4: ' + (3 === 4);
                            document.getElementById("op-12").innerHTML = 'true === true: ' + (true === true);
                            document.getElementById("op-13").innerHTML = 'true === false: ' + (true === false);
                            document.getElementById("op-14").innerHTML = 'null === null: ' + (null === null);
                        </script>
                    

== : equal to

examples



code:
                    <div class="spec">
                        <a id="id31"></a>
                        <a id="id32"></a>
                        <a id="id33"></a>
                        <a id="id34"></a>
                    </div>
                    <script>
                        let age = 25;
                        document.getElementById('id31').innerHTML = "age = 25: " + (age == 25);
                        document.getElementById('id32').innerHTML = "age = 30: " + (age == 30);
                        let name = 'shaun';
                        document.getElementById('id33').innerHTML = "name = shaun: " + (name = 'shaun');
                        document.getElementById('id34').innerHTML = "name = Shaun: " + (name = 'Shaun');
                    </script>
                

=== : equal value and equal type

examples

code:
                    <div class="spec">
                        <a id="id35"></a><br>
                        <a id="id36"></a>
                    </div>
                    <script>
                        let age_a = 25;
                        document.getElementById('id35').innerHTML = "age_a === 25: " + (age_a === 25);
                        document.getElementById('id36').innerHTML = "age_a === '30': " + (age_a === "30");
                    </script>
                

!= : not equal

examples

code:
                    <div class="spec">
                        <a id="id37"></a><br>
                        <a id="id38"></a>
                    </div>
                    <script>
                        let age_b = 25;
                        let aa = 5;
                        document.getElementById('id37').innerHTML = "age_b != 30: " + (age_b != 30);
                        document.getElementById('id38').innerHTML = "aa != 5: " + (aa != 5);
                    </script>
                

!== : not equal value or not equal type

examples

code:
                    <div class="spec">
                        <a id="id39"></a><br>
                        <a id="id40"></a>
                    </div>
                    <script>
                        let age_c = 25;
                        let ab = 10;
                        document.getElementById('id39').innerHTML = "age_c !== 30: " + (age_c !== 30);
                        document.getElementById('id40').innerHTML = "ab !== 30: " + (ab !== 30);
                    </script>
                

> : greater than

examples



code:
                    <div class="spec">
                        <a id="id41"></a><br>
                        <a id="id42"></a><br>
                        <a id="id43"></a><br>
                        <a id="id44"></a>
                    </div>
                    <script>
                        let age_d = 25;
                        document.getElementById('id41').innerHTML = "age_d > 30: " + (age_d > 20);
                        let name_a = 'shaun';
                        document.getElementById('id42').innerHTML = "name_a > crystal: " + (name_a > 'crystal');
                        document.getElementById('id43').innerHTML = "name_a > Shaun: " + (name_a > 'Shaun');
                        document.getElementById('id44').innerHTML = "name_a > Crystal: " + (name_a > 'Crystal');
                    </script>
                

< : less than

examples

code:
                    <div class="spec">
                        <a id="id45"></a><br>
                        <a id="id46"></a>
                    </div>
                    <script>
                        let age_e = 25;
                        let bb = 123;
                        document.getElementById('id45').innerHTML = "age_e < 30: " + (age_e < 20);
                        document.getElementById('id46').innerHTML = "bb < 200: " + (bb < 200);
                    </script>
                

>= : greater than or equal to

examples

code:
                    <div class="spec">
                        <a id="id47"></a><br>
                        <a id="id48"></a>
                    </div>
                    <script>
                        let age_f = 25;
                        let cc = 245;
                        document.getElementById('id47').innerHTML = "age_d >= 30: " + (age_d >= 20);
                        document.getElementById('id48').innerHTML = "cc >= 200: " + (cc >= 200);
                    </script>
                

<= : less than or equal to

examples

code:
                    <div class="spec">
                        <a id="id49"></a><br>
                        <a id="id50"></a>
                    </div>
                    <script>
                        let age_g = 25;
                        let dd = 345;
                        document.getElementById('id49').innerHTML = "age_g <= 30: " + (age_g <= 30);
                        document.getElementById('id50').innerHTML = "dd <= 345: " + (dd <= 345);
                    </script>
                

? : ternary operator

examples

code:
                    <div class=spec>
                        <input id="ouderdom" value="18" />
                        <button onclick="myFunction()">Try it</button>
                        <p id="id51"></p>
                    </div>
                    <script>
                        function myFunction() {
                            let ouderdom = document.getElementById("ouderdom").value;
                            let voteable = (age < 18) ? "Too young":"Old enough";
                            document.getElementById("id51").innerHTML = voteable + " to vote."; 
                        }
                    </script>
                

Ternary operator can be used to compress if-else statements. "if else statements" can be written in one line using the ternary (? :) operator. The conditional (ternary) operator is the only JavaScript operator that takes three operands:

a condition followed by a question mark (?),
then an expression to execute if the condition is truthy followed by a colon (:),
and finally the expression to execute if the condition is falsy.

longhand

            const x = 20;
            let answer;
            if (x > 10) {
                answer = "greater than 10";
            } else {
                answer =  "less than 10";
            }
        

shorthand

            const answer = x > 10 ? "greater than 10" : "less than 10";
            const answer = x > 10 ? "greater than 10" : x < 5 ? "less than 5" : "between 5 and 10";

            group = age > 18 ? "Adult" : "Child";
        

ternary operator - longhand and shorthand

longhand

                let info;
                if (value < minValue) {
                info = "Value is too small";
                } else if (value > maxValue) {
                info = "Value is too large";
                } else {
                info = "Value is in range";
                }
            

shorthand

                const info =
                value < minValue
                    ? "Value is too small"
                    : value > maxValue ? "Value is too large" : "Value is in range";
            

Toggle display of an element: you can easily toggle between hiding and displaying an element with the single line method.

Example - code

                const toggle = element => element.style.display = 
                (element.style.display === "none" ? "block" : "none")
            
                const toggle = ele => (ele.style.display = 
                (ele.style.display === 'none') ? 'block' : 'none');
            
                const toggle = ele => ele.hidden = !ele.hidden;
            

loose comparison (different types can still be equal)

examples



code:
                    <div class="spec">
                        <a id="id52"></a><br>
                        <a id="id53"></a><br>
                        <a id="id54"></a><br>
                        <a id="id55"></a>
                    </div>
                    <script>
                        document.getElementById('id52').innerHTML = "age == 25: " + (age == 25);
                        document.getElementById('id53').innerHTML = "age == '25': " + (age == '25');
                        document.getElementById('id54').innerHTML = "age != 25: " + (age != 25);
                        document.getElementById('id55').innerHTML = "age != '25': " + (age != '25');
                    </script>
                

strict comparison (different types cannot be equal)

examples



code:
                    <div class="spec">
                        <a id="id56"></a><br>
                        <a id="id57"></a><br>
                        <a id="id58"></a><br>
                        <a id="id59"></a>
                    </div>
                    <script>
                        document.getElementById('id56').innerHTML = "age === 25: " + (age === 25);
                        document.getElementById('id57').innerHTML = "age === '25': " + (age === '25');
                        document.getElementById('id58').innerHTML = "age !== 25: " + (age !== 25);
                        document.getElementById('id59').innerHTML = "age !== '25': " + (age !== '25');
                    </script>
                

logical operators

top

The precedence of NOT "!" is the highest of all logical operators, so it always executes first, before && or ||.

&& : logical and

examples








code:
                    <div class="spec">
                        <a id="id60"></a><br><br>
                        <a id="id61"></a><br><br>
                        <a id="id62"></a><br><br>
                        <a id="id63"></a><br><br>
                        <a id="id64"></a>
                    </div>
                    <script>
                        document.getElementById('id60').innerHTML = "true && true: " + (true && true);
                        document.getElementById('id61').innerHTML = "false && true: " + (false && true);
                        document.getElementById('id62').innerHTML = "true && false: " + (true && false);
                        document.getElementById('id63').innerHTML = "false && false: " + (false && false);
            
                        let hour = 12;
                        let minute = 30;
                            if(hour == 12 && minute == 30){
                                document.getElementById('id64').innerHTML = 'the time is 12:30';
                            }
                    </script>
                

"Short-circuit evaluation" works with the && logical operator. The expressions are evaluated left to right.

Short circuit evaluation with &&(AND) logical operator means if the first expression evaluates to false then the whole expression will be false and the rest of the expressions will not be evaluated.

longhand

                    if (variable1 !== null || variable1 !== undefined || variable1 !== ' ') {
                        let variable2 = variable1;
                    }
                

shorthand

                    const variable2 = variable1  || 'new';
                

You can use the && operator if you want to execute a function if a variable is true. This operator will return false as soon as it gets any falsy value and will return the last true value if all the values are truthy.

longhand

                if (isLoggedin) {   
                    redirectToHomepage();   
                }

                var age =  25;
                function driveCar() {
                    return 'Driving Car';
                }
            

shorthand

                isLoggedin && redirectToHomepage();

                var result = age > 18 && driveCar();
                console.log(result);
                // Driving Car
            

|| : logical or

examples












code:
                    <div class="spec">
                        <a id="id65"></a><br>
                        <a id="id66"></a><br>
                        <a id="id67"></a><br>
                        <a id="id68"></a><br>
                        <a id="id69"></a><br>
                        <a id="id70"></a><br>
                        <a id="id71"></a><br>
                        <a id="id72"></a><br>
                        <a id="id73"></a><br>
                        <a id="id74"></a><br>
                        <a id="id75"></a><br>
                        <a id="id76"></a><br>
                        <a id="id77"></a>
                    </div>
                    <script>
                        document.getElementById('id65').innerHTML = "true || true: " + (true||true);
                        document.getElementById('id66').innerHTML = "false || true: " + (false||true);
                        document.getElementById('id67').innerHTML = "true || false: " + (true||false);
                        document.getElementById('id68').innerHTML = "false || false: " + (false||false);
            
                        let hour2 = 9;
                        if(hour2 <10 || hour2 >18){
                            document.getElementById('id69').innerHTML = ('the ofice is closed');
                        } else document.getElementById('id70').innerHTML = (' the office is open');
            
                        let hour1 = 12;
                        let isWeekend = true;
                        if(hour1 <10 || hour1 >18 || isWeekend){
                            document.getElementById('id71').innerHTML = ('the office is closed');
                        }
            
                        document.getElementById('id72').innerHTML = "1||10: " + (1||0);
                        document.getElementById('id73').innerHTML = "true||'no matter what': " + (true||'no matter what');
                        document.getElementById('id74').innerHTML = "null||1: " + (null||1);
                        document.getElementById('id75').innerHTML =  "null||0||1: " +(null||0||1);
                        document.getElementById('id76').innerHTML = "undefined||null||0: " + (undefined||null||0);
            
                        let currentUser = "John";
                        let defaultUser = null;
                        let name1 = currentUser || defaultUser || 'unnamed';
                        document.getElementById('id77').innerHTML = name1;
                    

"Short-circuit evaluation" works with the || logical operators. The expressions are evaluated left to right.

Short circuit evaluation with ||(OR) logical operator means if the first expression evaluates to true then the whole expression will be true and the rest of the expressions will not be evaluated.

longhand

                    if (variable1 !== null || variable1 !== undefined || variable1 !== ' ') {
                        let variable2 = variable1;
                    }
                

shorthand

                    const variable2 = variable1  || 'new';
                

! : logical not

examples




code:
                    <div class="spec">
                        <a id="id78"></a><br>
                        <a id="id79"></a><br>
                        <a id="id80"></a><br>
                        <a id="id81"></a><br>
                        <a id="id82"></a>       
                    </div>
                    <script>
                        document.getElementById('id78').innerHTML = "!true: " + (!true);
                        document.getElementById('id79').innerHTML = "!false: " + (!false);
                        document.getElementById('id80').innerHTML = "!0: " + (!0);
                        document.getElementById('id81').innerHTML = "!!0: " + (!!0);
                        document.getElementById('id82').innerHTML = "!!'non-empty string': " + (!!'non-empty string');    
                    </script>
                

??: null coalescing operator

The null coalescing operator "??" returns the right-hand side if the left-hand side is null. Otherwise, it returns the value on the left.

The nullish coalescing operator ?? provides a short way to choose the first “defined” value from a list. It is used to assign default values to variables.The point of this operator, is to allow you to return a value if the evaluated expression is either null or undefined. Pretty much like the || operator, the logic behind it is the same: if the left side of the expression is evaluated to "null" or "undefined", it will return the right side, otherwise, it will return the left side.

longhand

                    if(someValue){
                        console.log(someValue)
                    } else {
                        console.log("Nothing found")
                    }
                

shorthand

                    console.log(someValue ?? "Nothing found")

                

"typeof" operator

top

The "typeof" operator returns the type of a variable, object, function, or expression

examples
code:
                    <div class="spec">
                        <a id="id83" style="margin-left:3vw;"></a>
                    </div>
                    <script>
                        document.getElementById("id83").innerHTML = 
                            typeof "John" + "<br>" + 
                            typeof 3.14 + "<br>" +
                            typeof NaN + "<br>" +
                            typeof false + "<br>" +
                            typeof [1, 2, 3, 4] + "<br>" +
                            typeof {name:'John', age:34} + "<br>" +
                            typeof new Date() + "<br>" +
                            typeof function () {} + "<br>" +
                            typeof myCar + "<br>" +
                            typeof null;
                    </script>
                

"delete" operator

top

The "delete" operator deletes a property from an object.

examples
code:
                    <div class="spec">
                        <a id="id84"></a>
                    </div>
                    <script>
                        var person = {
                            firstname:"John",
                            lastname:"Doe",
                            age:50,
                            eyecolor:"blue"
                        };
                        delete person.age;
                        document.getElementById("id84").innerHTML =
                            person.firstname + " is " + person.age + " years old.";
                    </script>
                

"in" operator

top

The "in" operator returns true if the specified property is in the specified object, otherwise false.

examples
code:
                    <div class="spec">
                        <a id="id85"></a> 
                    </div>
                    <script>
                        // Arrays
                        var cars = ["Saab", "Volvo", "BMW"];
                        // Objects
                        var person = {firstName:"John", lastName:"Doe", age:50};
                        document.getElementById("id85").innerHTML =
                            ("Saab" in cars) + "<br>" + 
                            (0 in cars) + "<br>" +
                            (1 in cars) + "<br>" +
                            (4 in cars) + "<br>" +
                            ("length" in cars) + "<br>" +
                            
                            ("firstName" in person) + "<br>" +
                            ("age" in person) + "<br>" +
                            
                            // Predefined objects
                            ("PI" in Math) + "<br>" +
                            ("NaN" in Number) + "<br>" +
                            ("length" in String);
                    </script>
                

"instanceof" operator

top

The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value. Its behavior can be customized with Symbol.hasInstance.

The "instanceof" operator returns true if the specified object is an instance of the specified object.

Syntax: object instanceof constructor

examples
code:
                    <div class="spec">
                        <a id="id86"></a>   
                    </div>
                    <script>
                        var cars = ["Saab", "Volvo", "BMW"];
                        document.getElementById("id86").innerHTML =
                            (cars instanceof Array) + "<br>" + 
                            (cars instanceof Object) + "<br>" +
                            (cars instanceof String) + "<br>" +
                            (cars instanceof Number);
                    </script>
                

"bitwise" operators

top

A "bitwise" operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers.

& — AND statement ; returns a one in each bit position for which the corresponding bits of both operands are ones.

| — OR statement ; returns a zero in each bit position for which the corresponding bits of both operands are zeros.

~ — NOT ; inverts the bits of its operand.

^ — XOR ; returns a zero in each bit position for which the corresponding bits are the same

<< — Left shift ; shifts a in binary representation b bits to the left, shifting in zeros from the right.

>> — Right shift ; shifts a in binary representation b bits to the right, discarding bits shifted off

>>> — Zero fill right shift ; shifts a in binary representation b bits to the right, discarding bits shifted off, and shifting in zeros from the left.

Double bitwise NOT operator

Instead of using the Math.floor() function to round a number down, you can use the ~~ operator as a shorthand. The bitwise NOT operator (i.e ~) will grab the numbers, it will turn them into a 32bits integer (discarding any extra bits) and then it will invert all their bits essentially turning any integer of value x into -(x+1).
The operator uses it twice on the same value, thus getting the same result as the Math.floor method.


longhand

                    Math.floor(4.9) === 4  //true
                    Math.floor(5.25) // -> 5.0
                    const floor = Math.floor(4.8); // 4

                    let x = 3.8
                    let y = ~x //this turns x into -(3 + 1), remember, the number 
                    gets turned into an integer
                    let z = ~y //this turns y (which is -4) into -(-4 + 1) which is 3

                

shorthand

                    ~~4.9 === 4  //true
                    ~~5.25 // -> 5.0
                    const floor = ~~4.8; // 4

                    let flooredX = ~~x //and this performs both steps from the left at the 
                    same time.
                

operators examples

top



code:
                <div class="spec">
                    <canvas id="canvas" width="400" height="400"></canvas><br>
                    <label for="theme">Select theme: </label>
                    <select id="theme">
                        <option value="white">White</option>
                        <option value="blue">Blue</option>
                    </select><br><br>
                </div>
                <script>
                const select = document.querySelector('select');
                const canvas = document.querySelector('canvas');
                let ctx = canvas.getContext('2d');
                ctx.font = "40px Helvetica";
                ctx.strokeText("My website!", 100, 50);
                select.onchange = function() {
                    select.value === 'blue' ? update('blue','white') : update('white','blue');        
                }
                function update(bgColor, textColor) {
                    canvas.style.backgroundColor = bgColor;
                    canvas.style.color = textColor;
                }
                </script>
            
code:
                <div class="spec">
                    <canvas id="canvas1" width="400" height="400"></canvas>
                    <button onclick="bgChange()">Change color</button>    
                </div>     
            <script>
                    function random(number) {
                        return Math.floor(Math.random()*number);
                    }
                    function bgChange() {
                        const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
                        canvas1.style.backgroundColor = rndCol;
                    }
                </script>
            

JavaScript.info - examples

examples
terms:
                let x = 1;
                x = -x;
                alert( x ); // -1, unary negation was applied

                let x = 1, y = 3;
                alert( y - x ); // 2, binary minus subtracts values
            
remainder %:
                alert( 5 % 2 ); // 1, a remainder of 5 divided by 2
                alert( 8 % 3 ); // 2, a remainder of 8 divided by 3
            
exponentiation ** :
                alert( 2 ** 2 ); // 2² = 4
                alert( 2 ** 3 ); // 2³ = 8
                alert( 2 ** 4 ); // 2⁴ = 16

                alert( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root)
                alert( 8 ** (1/3) ); // 2 (power of 1/3 is the same as a cubic root)
            
string concatenation with binary +:
                let s = "my" + "string";
                alert(s); // mystring

                alert( '1' + 2 ); // "12"
                alert( 2 + '1' ); // "21"

                alert(2 + 2 + '1' ); // "41" and not "221"

                alert('1' + 2 + 2); // "122" and not "14"

                alert( 6 - '2' ); // 4, converts '2' to a number
                alert( '6' / '2' ); // 3, converts both operands to numbers
            
numeric conversion, unary +:
                // No effect on numbers
                let x = 1;
                alert( +x ); // 1
                
                let y = -2;
                alert( +y ); // -2
                
                // Converts non-numbers
                alert( +true ); // 1
                alert( +"" );   // 0

                let apples = "2";
                let oranges = "3";
                alert( apples + oranges ); // "23", the binary plus concatenates strings

                let apples = "2";
                let oranges = "3";
                // both values converted to numbers before the binary plus
                alert( +apples + +oranges ); // 5
                // the longer variant
                // alert( Number(apples) + Number(oranges) ); // 5
            
assignment:
                let x = 2 * 2 + 1;
                alert( x ); // 5

                let a = 1;
                let b = 2;
                let c = 3 - (a = b + 1);
                alert( a ); // 3
                alert( c ); // 0

                let a, b, c;
                a = b = c = 2 + 2;
                alert( a ); // 4
                alert( b ); // 4
                alert( c ); // 4
                                    
            
modify-in-place:
                let n = 2;
                n += 5; // now n = 7 (same as n = n + 5)
                n *= 2; // now n = 14 (same as n = n * 2)
                alert( n ); // 14

                let n = 2;
                n *= 3 + 5; // right part evaluated first, same as n *= 8
                alert( n ); // 16
            
increment/decrement:
                let counter = 2;
                counter++;        // works the same as counter = counter + 1, but is shorter
                alert( counter ); // 3
                
                let counter = 2;
                counter--;        // works the same as counter = counter - 1, but is shorter
                alert( counter ); // 1

                let counter = 1;
                let a = ++counter; // (*)
                alert(a); // 2

                let counter = 1;
                let a = counter++; // (*) changed ++counter to counter++
                alert(a); // 1
            
comma:
                let a = (1 + 2, 3 + 4);
                alert( a ); // 7 (the result of 3 + 4)
            
                // three operations in one line
                for (a = 1, b = 3, c = a * b; a < 10; a++) {
                ...
                }
            
boolean is the result:
                alert( 2 > 1 );  // true (correct)
                alert( 2 == 1 ); // false (wrong)
                alert( 2 != 1 ); // true (correct)

                let result = 5 > 4; // assign the result of the comparison
                alert( result ); // true

            
string comparison:
                alert( 'Z' > 'A' ); // true
                alert( 'Glow' > 'Glee' ); // true
                alert( 'Bee' > 'Be' ); // true
            
comparison of different types:
                alert( '2' > 1 ); // true, string '2' becomes a number 2
                alert( '01' == 1 ); // true, string '01' becomes a number 1

                alert( true == 1 ); // true
                alert( false == 0 ); // true

                let a = 0;
                alert( Boolean(a) ); // false
                let b = "0";
                alert( Boolean(b) ); // true
                alert(a == b); // true!
            
strict equality:
                alert( 0 == false ); // true
                alert( '' == false ); // true

                alert( 0 === false ); // false, because the types are different
            
comparison with null and undefined:
                alert( null === undefined ); // false
                alert( null == undefined ); // true

                alert( null > 0 );  // (1) false
                alert( null == 0 ); // (2) false
                alert( null >= 0 ); // (3) true

                alert( undefined > 0 ); // false (1)
                alert( undefined < 0 ); // false (2)
                alert( undefined == 0 ); // false (3)
            
|| (or):
                result = a || b;

                alert( true || true );   // true
                alert( false || true );  // true
                alert( true || false );  // true
                alert( false || false ); // false

                if (1 || 0) { // works just like if( true || false )
                    alert( 'truthy!' );
                }

                let hour = 9;
                if (hour < 10 || hour > 18) {
                alert( 'The office is closed.' );
                }

                let hour = 12;
                let isWeekend = true;
                if (hour < 10 || hour > 18 || isWeekend) {
                alert( 'The office is closed.' ); // it is the weekend
                }
            
OR "||" finds the first truthy value:
                result = value1 || value2 || value3;

                alert( 1 || 0 ); // 1 (1 is truthy)
                alert( null || 1 ); // 1 (1 is the first truthy value)
                alert( null || 0 || 1 ); // 1 (the first truthy value)
                alert( undefined || null || 0 ); // 0 (all falsy, returns the last value)

                let firstName = "";
                let lastName = "";
                let nickName = "SuperCoder";
                alert( firstName || lastName || nickName || "Anonymous"); // SuperCoder

                true || alert("not printed");
                false || alert("printed");
            
&& (AND):
                result = a && b;

                alert( true && true );   // true
                alert( false && true );  // false
                alert( true && false );  // false
                alert( false && false ); // false

                let hour = 12;
                let minute = 30;
                if (hour == 12 && minute == 30) {
                    alert( 'The time is 12:30' );
                }

                if (1 && 0) { // evaluated as true && false
                    alert( "won't work, because the result is falsy" );
                }
            
AND "&&" finds the first falsy value:
                result = value1 && value2 && value3;

                // if the first operand is truthy,
                // AND returns the second operand:
                alert( 1 && 0 ); // 0
                alert( 1 && 5 ); // 5

                // if the first operand is falsy,
                // AND returns it. The second operand is ignored
                alert( null && 5 ); // null
                alert( 0 && "no matter what" ); // 0

                alert( 1 && 2 && null && 3 ); // null

                alert( 1 && 2 && 3 ); // 3, the last one
            
!(NOT):
                result = !value;

                alert( !true ); // false
                alert( !0 ); // true

                alert( !!"non-empty string" ); // true
                alert( !!null ); // false

            
nullish coalescing operator '??':
                let user;
                alert(user ?? "Anonymous"); // Anonymous (user is undefined)
                
                let user = "John";
                alert(user ?? "Anonymous"); // John (user is not null/udefined)

                let firstName = null;
                let lastName = null;
                let nickName = "Supercoder";
                // shows the first defined value:
                alert(firstName ?? lastName ?? nickName ?? "Anonymous"); // Supercoder

                let height = 0;
                alert(height || 100); // 100
                alert(height ?? 100); // 0
            

Github - expressions examples

examples
expressions-arithmetic:
                // Number addition and subtraction
                console.log(2 + 3 - 1);
                // expected output: 4
                // Number multiplication and division
                console.log(4 * 3 / 2); // 12 / 2
                // expected output: 6
                // Number remainder and exponential
                console.log(11 % 3 ** 2); // 11 % 9
                // expected output: 2
            
expressions-assignment:
                let x = 2;
                const y = 3;
                console.log(x);
                // expected output: 2
                console.log(x = y + 1); // 3 + 1
                // expected output: 4
                console.log(x = x * y); // 4 * 3
                // expected output: 12
            
expressions-bitwiseoperators:
                console.log(5 & 13); // 0101 & 1101 = 0101
                // expected output: 5;
                console.log(parseInt('0101', 2) & parseInt('1101', 2));
                // expected output: 5;
                console.log(5 & 13 & 3); // 0101 & 1101 & 0011 = 0001
                // expected output: 1;
                console.log(5 | 13); // 0101 | 1101 = 1101
                // expected output: 13
            
expressions-classexpressions:
                const Rectangle = class {
                    constructor(height, width) {
                    this.height = height;
                    this.width = width;
                    }
                    area() {
                    return this.height * this.width;
                    }
                };
                console.log(new Rectangle(5, 8).area());
                // expected output: 40
            
expressions-commaoperators:
                let x = 1;
                x = (x++, x);
                console.log(x);
                // expected output: 2
                x = (2, 3);
                console.log(x);
                // expected output: 3
            
expressions-comparisonoperators:
                console.log(1 == 1);
                // expected output: true
                console.log('1' == 1);
                // expected output: true
                console.log(1 === 1);
                // expected output: true
                console.log('1' === 1);
                // expected output: false
            
expressions-conditionaloperators:
                function getFee(isMember) {
                    return (isMember ? '$2.00' : '$10.00');
                }
                console.log(getFee(true));
                // expected output: "$2.00"
                console.log(getFee(false));
                // expected output: "$10.00"
                console.log(getFee(1));
                // expected output: "$2.00"
            
expressions-deleteoperators:
                const Employee = {
                    firstname: 'John',
                    lastname: 'Doe'
                };
                console.log(Employee.firstname);
                // expected output: "John"
                delete Employee.firstname;
                console.log(Employee.firstname);
                // expected output: undefined
                
            
expressions-destructuringassignment:
                let a, b, rest;
                [a, b] = [10, 20];
                console.log(a);
                // expected output: 10
                console.log(b);
                // expected output: 20
                [a, b, ...rest] = [10, 20, 30, 40, 50];
                console.log(rest);
                // expected output: Array [30,40,50]
            
expressions-functionasteriskexpression:
                function* foo() {
                    yield 'a';
                    yield 'b';
                    yield 'c';
                }
                let str = '';
                for (const val of foo()) {
                str = str + val;
                }
                console.log(str);
                // expected output: "abc"
            
expressions-functionexpression:
                const getRectArea = function(width, height) {
                    return width * height;
                };
                console.log(getRectArea(3, 4));
                // expected output: 12
            
expressions-groupingoperator:
                console.log(1 + 2 * 3); // 1 + 6
                // expected output: 7
                console.log(1 + (2 * 3)); // 1 + 6
                // expected output: 7
                console.log((1 + 2) * 3); // 3 * 3
                // expected output: 9
                console.log(1 * 3 + 2 * 3); // 3 + 6
                // expected output: 9
            
expressions-inoperator:
                const car = { make: 'Honda', model: 'Accord', year: 1998 };
                console.log('make' in car);
                // expected output: true
                delete car.make;
                if ('make' in car === false) {
                car.make = 'Suzuki';
                }
                console.log(car.make);
                // expected output: "Suzuki"
            
expressions-logical-and:
                const a = 3;
                const b = -2;
                console.log(a > 0 && b > 0);
                // expected output: false
            
expressions-logical-not:
                const a = 3;
                const b = -2;
                console.log(!(a > 0 || b > 0));
                // expected output: false
            
expressions-logical-or:
                const a = 3;
                const b = -2;
                console.log(a > 0 || b > 0);
                // expected output: true
            
expressions-newoperator:
                function Car(make, model, year) {
                    this.make = make;
                    this.model = model;
                    this.year = year;
                }
                const car1 = new Car('Eagle', 'Talon TSi', 1993);
                console.log(car1.make);
                // expected output: "Eagle"
            
expressions-newtarget:
                function Foo() {
                if (!new.target) { throw 'Foo() must be called with new'; }
                }
                try {
                    Foo();
                } catch (e) {
                    console.log(e);
                    // expected output: "Foo() must be called with new"
                }
            
expressions-nullishcoalescingoperator:
                const foo = null ?? 'default string';
                console.log(foo);
                // expected output: "default string"
                const baz = 0 ?? 42;
                console.log(baz);
                // expected output: 0
            
expressions-objectinitializer:
                const object1 = { a: 'foo', b: 42, c: {} };
                console.log(object1.a);
                // expected output: "foo"
                const a = 'foo';
                const b = 42;
                const c = {};
                const object2 = { a: a, b: b, c: c };
                console.log(object2.b);
                // expected output: 42
                const object3 = { a, b, c };
                console.log(object3.a);
                // expected output: "foo"
            
expressions-operatorsprecedence:
                console.log(3 + 4 * 5); // 3 + 20
                // expected output: 23
                console.log(4 * 3 ** 2); // 4 * 9
                // expected output: 36
                let a;
                let b;
                console.log(a = b = 5);
                // expected output: 5
            
expressions-optionalchainingoperator:
                const adventurer = {
                    name: 'Alice',
                    cat: {
                    name: 'Dinah'
                    }
                };
                const dogName = adventurer.dog?.name;
                console.log(dogName);
                // expected output: undefined
                console.log(adventurer.someNonExistentMethod?.());
                // expected output: undefined
            
expressions-propertyaccessors:
                const person1 = {};
                person1['firstname'] = 'Mario';
                person1['lastname'] = 'Rossi';
                console.log(person1.firstname);
                // expected output: "Mario"
                const person2 = {
                firstname: 'John',
                lastname: 'Doe'
                };
                console.log(person2['lastname']);
                // expected output: "Doe"
            
expressions-spreadsyntax:
                function sum(x, y, z) {
                    return x + y + z;
                }
                const numbers = [1, 2, 3];
                console.log(sum(...numbers));
                // expected output: 6
                console.log(sum.apply(null, numbers));
                // expected output: 6
            
expressions-this:
                const test = {
                    prop: 42,
                    func: function() {
                    return this.prop;
                    },
                };
                console.log(test.func());
                // expected output: 42
            
expressions-typeof:
                console.log(typeof 42);
                // expected output: "number"
                console.log(typeof 'blubber');
                // expected output: "string"
                console.log(typeof true);
                // expected output: "boolean"
                console.log(typeof undeclaredVariable);
                // expected output: "undefined";
            
expressions-voidoperator:
                void function test() {
                    console.log('boo!');
                    // expected output: "boo!"
                }();
                try {
                    test();
                } catch (e) {
                    console.log(e);
                    // expected output: ReferenceError: test is not defined
                }
            
expressions-yield:
                function* foo(index) {
                    while (index < 2) {
                    yield index++;
                    }
                }
                const iterator = foo(0);
                console.log(iterator.next().value);
                // expected output: 0
                console.log(iterator.next().value);
                // expected output: 1
            
expressions-yieldasterisk:
                function* func1() {
                    yield 42;
                }
                function* func2() {
                    yield* func1();
                }
                const iterator = func2();
                console.log(iterator.next().value);
                // expected output: 42