Example

Assignment Operators

HTML

<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Assignment Operators</title>
</head>  
<body>
<!--
    Assignment Operators : assign values to JavaScript variables.
        Operator	Example	    Same As
            =	    x = y	    
            +=	    x += y	    x = x + y
            -=	    x -= y	    x = x - y
            *=	    x *= y	    x = x * y
            /=	    x /= y	    x = x / y
            %=	    x %= y	    x = x % y
            **=	    x **= y	    x = x ** y
    The += assignment operator can also be used to add (concatenate) strings.
-->

    <h1>Demo: Assignment Operators</h1>

    <!-- JavaScript code Starts here -->
    <script>

        /************************************************/
        // JavaScript Assignment Operators 
        // Example on Numbers datatype
        //
        let a = b = c = 3;
        let p = q = r = 6;
        let t = u = v = 9;

        a += b;    // Same as a = a + b
        r -= c;    // Same as r = r - c
        p *= q;    // Same as p = p * q
        t /= q;    // Same as t = t / q
        u %= b;    // Same as u = u % b
        v **= c;   // Same as v = v ** c
        document.write(" a = " + a + "<BR>" +
                        " r = " + r + "<BR>" +
                        " p = " + p + "<BR>" +
                        " t = " + t + "<BR>" +
                        " u = " + u + "<BR>" +
                        " v = " + v + "<BR><BR>")
            

        /************************************************/
        // JavaScript Assignment Operator(+=) 
        // Example on Strings datatype
        //
        let _name = "Argentina wins";
        _name += " - FIFA World Cup 2022"; // On strings, the + operator is called concatenation operator
        document.write(_name + "<BR><BR>")    


        /************************************************/
        // JavaScript Assignment Operator(+=)  
        // Example on Numbers & Strings datatype will result in string concatenation
        //
        let subject = 'Math'    
        subject += 99;    // Same as subject = subject + 99
        document.write(subject + "<BR><BR>") 

    </script>
    <!-- JavaScript code Ends here -->

</body>
</html>

Output

View original