Learn about JavaScript operators, including arithmetic, logical, and bitwise operators.
Explore examples and use cases for each operator type.”
JavaScript operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated first. In cases where operators have the same precedence, the evaluation order is from left to right. Understanding operator precedence is crucial for writing correct and predictable JavaScript code.
Here is a list of JavaScript operators sorted by precedence from highest to lowest:
Parentheses are used to group expressions, and the expression inside the parentheses is evaluated first.
The dot operator is used to access properties and methods of objects.
Square brackets are used to access object properties with dynamic or computed keys.
Function calls are evaluated before other operators, and arguments are passed to functions within the parentheses.
new – The new keyword is used to create instances of objects and call constructor functions.
++ (postfix and prefix), — (postfix and prefix) –
These operators increment or decrement a variable’s value.
The logical NOT operator negates a Boolean value.
The bitwise NOT operator inverts the bits of a number.
These operators are used for positive and negative signs.
The typeof operator is used to determine the data type of a value.
The void operator discards the result of an expression and returns undefined.
These operators perform multiplication, division, and modulo operations.
These operators perform addition and subtraction.
These operators perform bitwise left shift, bitwise right shift (with sign extension), and bitwise right shift (without sign extension).
These operators compare values and return Boolean results. The in operator checks for the existence of a property in an object, and the instanceof operator checks if an object is an instance of a particular class or constructor.
These operators compare values for equality and inequality. The strict equality operators (=== and !==) compare both value and type, while the non-strict operators (== and !=) perform type coercion.
The bitwise AND operator performs a bitwise AND operation between two numbers.
The bitwise XOR
operator performs a bitwise XOR operation between two numbers.
The bitwise OR operator performs a bitwise OR operation between two numbers.
The logical AND operator performs a logical AND operation between two Boolean values.
The logical OR operator performs a logical OR operation between two Boolean values.
The conditional operator allows you to create conditional expressions. It has the form condition ? expr1 : expr2 and returns expr1 if the condition is true and expr2 otherwise.
=, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, ^=, |= –
These operators assign values to variables and perform operations in combination with assignment.
The comma operator allows you to evaluate multiple expressions in sequence, from left to right. It returns the value of the last expression.
Understanding operator precedence is essential for writing correct expressions and avoiding unexpected behavior in your JavaScript code. If you’re ever unsure about the precedence of operators in a complex expression, you can use parentheses to explicitly specify the order of evaluation.
Here’s a complete HTML example that demonstrates the use of grouping with parentheses in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Grouping with Parentheses</title> </head> <body> <h1>Grouping with Parentheses in JavaScript</h1> <p>This example shows how to use parentheses for grouping in JavaScript expressions:</p> <script> // Example 1: Using parentheses to control the order of operations let result1 = 10 + 2 * 5; // Without parentheses, multiplication takes precedence let result2 = (10 + 2) * 5; // With parentheses, addition is performed first document.write("Result 1: " + result1 + "<br>"); // Output: Result 1: 20 document.write("Result 2: " + result2 + "<br>"); // Output: Result 2: 60 // Example 2: Using parentheses to group expressions let x = 5; let y = 10; let z = (x + y) * (x - y); document.write("Result 3: " + z + "<br>"); // Output: Result 3: -75 </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript expressions displayed on the web page, demonstrating the use of grouping with parentheses.
Here’s a complete HTML example that demonstrates member access in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Member Access in JavaScript</title> </head> <body> <h1>Member Access in JavaScript</h1> <p>This example shows how to access object properties and methods using the dot operator in JavaScript:</p> <script> // Example 1: Accessing object properties const person = { firstName: "Omar", lastName: "Abubakr", age: 30 }; let fullName = person.firstName + " " + person.lastName; document.write("Full Name: " + fullName + "<br>"); // Output: Full Name: Omar Abubakr // Example 2: Accessing object methods const calculator = { add: function(a, b) { return a + b; }, subtract: function(a, b) { return a - b; } }; let result1 = calculator.add(5, 3); let result2 = calculator.subtract(10, 4); document.write("Result 1: " + result1 + "<br>"); // Output: Result 1: 8 document.write("Result 2: " + result2 + "<br>"); // Output: Result 2: 6 </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating member access using the dot operator.
Here’s a complete HTML example that demonstrates computed member access in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Computed Member Access in JavaScript</title> </head> <body> <h1>Computed Member Access in JavaScript</h1> <p>This example shows how to access object properties with computed keys using square brackets in JavaScript:</p> <script> // Example 1: Accessing object properties with computed keys const person = { firstName: "Omar", lastName: "Abubakr", age: 30 }; let propertyKey = "lastName"; let lastName = person[propertyKey]; document.write("Last Name: " + lastName + "<br>"); // Output: Last Name: Abubakr // Example 2: Computed property names in object literals const fruit = "apple"; const quantity = 5; const groceryList = { [fruit]: quantity, ["orange"]: 3, ["banana"]: 2 }; document.write("Grocery List: " + JSON.stringify(groceryList) + "<br>"); // Output: Grocery List: {"apple":5,"orange":3,"banana":2} </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating computed member access using square brackets.
Here’s a complete HTML example that demonstrates function calls and passing arguments in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Function Calls and Arguments in JavaScript</title> </head> <body> <h1>Function Calls and Arguments in JavaScript</h1> <p>This example shows how to define and call functions with arguments in JavaScript:</p> <script> // Example 1: Function call with arguments function greet(name) { return "Hello, " + name + "!"; } let greeting1 = greet("Alice"); let greeting2 = greet("Bob"); document.write("Greeting 1: " + greeting1 + "<br>"); // Output: Greeting 1: Hello, Alice! document.write("Greeting 2: " + greeting2 + "<br>"); // Output: Greeting 2: Hello, Bob! // Example 2: Function call without arguments function sayHello() { return "Hello, World!"; } let helloMessage = sayHello(); document.write("Hello Message: " + helloMessage + "<br>"); // Output: Hello Message: Hello, World! </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating function calls and passing arguments.
Here’s a complete HTML example that demonstrates the use of the new keyword to create instances of objects, both with and without constructor arguments in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>New Keyword in JavaScript</title> </head> <body> <h1>New Keyword in JavaScript</h1> <p>This example shows how to create instances of objects using the <code>new</code> keyword:</p> <script> // Example 1: Creating an instance of an object without arguments function Person() { this.firstName = "Omar"; this.lastName = "Abubakr"; } const person1 = new Person(); document.write("Person 1: " + JSON.stringify(person1) + "<br>"); // Output: Person 1: {"firstName":"Omar","lastName":"Abubakr"} // Example 2: Creating an instance of an object with arguments function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } const car1 = new Car("Toyota", "Camry", 2022); const car2 = new Car("Ford", "Mustang", 2023); document.write("Car 1: " + JSON.stringify(car1) + "<br>"); // Output: Car 1: {"make":"Toyota","model":"Camry","year":2022} document.write("Car 2: " + JSON.stringify(car2) + "<br>"); // Output: Car 2: {"make":"Ford","model":"Mustang","year":2023} </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating the use of the new keyword to create instances of objects.
Here’s a complete HTML example that demonstrates the use of the increment (++) and decrement (–) operators in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Increment and Decrement Operators in JavaScript</title> </head> <body> <h1>Increment and Decrement Operators in JavaScript</h1> <p>This example shows how to use the increment and decrement operators:</p> <script> // Example 1: Using the increment (++) operator let count = 5; count++; // Increment count by 1 document.write("Count after increment: " + count + "<br>"); // Output: Count after increment: 6 // Example 2: Using the decrement (--) operator let quantity = 10; quantity--; // Decrement quantity by 1 document.write("Quantity after decrement: " + quantity + "<br>"); // Output: Quantity after decrement: 9 // Example 3: Using the operators in expressions let x = 8; let y = 3; let result1 = x++; // Post-increment: result1 gets the current value of x (8), then x is incremented let result2 = --y; // Pre-decrement: y is decremented first, then result2 gets the updated value of y (2) document.write("Result 1: " + result1 + "<br>"); // Output: Result 1: 8 document.write("Result 2: " + result2 + "<br>"); // Output: Result 2: 2 document.write("Updated x: " + x + "<br>"); // Output: Updated x: 9 document.write("Updated y: " + y + "<br>"); // Output: Updated y: 2 </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating the use of the increment and decrement operators.
Here’s a complete HTML example that demonstrates the use of the logical NOT (!) operator in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Logical NOT Operator in JavaScript</title> </head> <body> <h1>Logical NOT Operator in JavaScript</h1> <p>This example shows how to use the logical NOT operator:</p> <script> // Example 1: Using the logical NOT (!) operator with a Boolean value let isTrue = true; let isFalse = false; let notTrue = !isTrue; let notFalse = !isFalse; document.write("notTrue: " + notTrue + "<br>"); // Output: notTrue: false document.write("notFalse: " + notFalse + "<br>"); // Output: notFalse: true // Example 2: Using the logical NOT (!) operator with expressions let num = 10; let isZero = !num; // The logical NOT operator converts a non-zero number to false, and 0 to true document.write("isZero: " + isZero + "<br>"); // Output: isZero: false // Example 3: Using the logical NOT (!) operator for negating a condition let hasPermission = false; if (!hasPermission) { document.write("Access denied. You do not have permission.<br>"); } else { document.write("Access granted. You have permission.<br>"); } </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating the use of the logical NOT operator (!).
Here’s a complete HTML example that demonstrates the use of the bitwise NOT (~) operator in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Bitwise NOT Operator (~) in JavaScript</title> </head> <body> <h1>Bitwise NOT Operator (~) in JavaScript</h1> <p>This example shows how to use the bitwise NOT operator:</p> <script> // Example 1: Using the bitwise NOT (~) operator let num1 = 5; // Binary representation: 00000101 let bitwiseNotNum1 = ~num1; // Binary representation: 11111010 (Two's complement) document.write("Bitwise NOT of num1: " + bitwiseNotNum1 + "<br>"); // Output: Bitwise NOT of num1: -6 // Example 2: Using the bitwise NOT (~) operator with positive and negative numbers let num2 = 7; // Binary representation: 00000111 let bitwiseNotNum2 = ~num2; // Binary representation: 11111000 (Two's complement) document.write("Bitwise NOT of num2: " + bitwiseNotNum2 + "<br>"); // Output: Bitwise NOT of num2: -8 // Example 3: Using the bitwise NOT (~) operator with a negative number let negativeNum = -3; // Binary representation (32-bit): 11111111 11111111 11111111 11111101 let bitwiseNotNegativeNum = ~negativeNum; // Binary representation (32-bit): 00000000 00000000 00000000 00000010 (Two's complement) document.write("Bitwise NOT of negativeNum: " + bitwiseNotNegativeNum + "<br>"); // Output: Bitwise NOT of negativeNum: 2 </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating the use of the bitwise NOT operator (~).
Here’s a complete HTML example that demonstrates the use of the unary plus (+) and unary minus (-) operators in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Unary Plus and Minus Operators in JavaScript</title> </head> <body> <h1>Unary Plus and Minus Operators in JavaScript</h1> <p>This example shows how to use the unary plus and minus operators:</p> <script> // Example 1: Using the unary plus (+) operator let positiveNumber = 42; let unaryPlusResult = +positiveNumber; document.write("Unary Plus Result: " + unaryPlusResult + "<br>"); // Output: Unary Plus Result: 42 // Example 2: Using the unary minus (-) operator let negativeNumber = -17; let unaryMinusResult = -negativeNumber; document.write("Unary Minus Result: " + unaryMinusResult + "<br>"); // Output: Unary Minus Result: 17 // Example 3: Using the unary plus and minus with strings let numericString = "123"; let stringToNumber = +numericString; // Convert a numeric string to a number using unary plus let stringToNegativeNumber = -numericString; // Applying unary minus to a numeric string (coerces to a number and negates) document.write("String to Number: " + stringToNumber + "<br>"); // Output: String to Number: 123 document.write("String to Negative Number: " + stringToNegativeNumber + "<br>"); // Output: String to Negative Number: -123 </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating the use of the unary plus and minus operators (+ and -).
Here’s a complete HTML example that demonstrates the use of the typeof operator in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>typeof Operator in JavaScript</title> </head> <body> <h1>typeof Operator in JavaScript</h1> <p>This example shows how to use the typeof operator:</p> <script> // Example 1: Using the typeof operator with primitive data types let num = 42; let str = "Hello, World!"; let bool = true; let undef; let n = null; let typeofNum = typeof num; let typeofStr = typeof str; let typeofBool = typeof bool; let typeofUndef = typeof undef; let typeofNull = typeof n; document.write("typeof num: " + typeofNum + "<br>"); // Output: typeof num: number document.write("typeof str: " + typeofStr + "<br>"); // Output: typeof str: string document.write("typeof bool: " + typeofBool + "<br>"); // Output: typeof bool: boolean document.write("typeof undef: " + typeofUndef + "<br>"); // Output: typeof undef: undefined document.write("typeof null: " + typeofNull + "<br>"); // Output: typeof null: object (Note: This is a known quirk in JavaScript) // Example 2: Using the typeof operator with objects and functions let obj = { key: "value" }; let arr = [1, 2, 3]; let func = function() {}; let typeofObj = typeof obj; let typeofArr = typeof arr; let typeofFunc = typeof func; document.write("typeof obj: " + typeofObj + "<br>"); // Output: typeof obj: object document.write("typeof arr: " + typeofArr + "<br>"); // Output: typeof arr: object document.write("typeof func: " + typeofFunc + "<br>"); // Output: typeof func: function </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating the use of the typeof operator.
Here’s a complete HTML example that demonstrates the use of the void operator in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>void Operator in JavaScript</title> </head> <body> <h1>void Operator in JavaScript</h1> <p>This example shows how to use the void operator:</p> <script> // Example 1: Using the void operator to discard a value and return undefined let result1 = void 42; let result2 = void "Hello, World!"; let result3 = void true; document.write("Result 1: " + result1 + "<br>"); // Output: Result 1: undefined document.write("Result 2: " + result2 + "<br>"); // Output: Result 2: undefined document.write("Result 3: " + result3 + "<br>"); // Output: Result 3: undefined // Example 2: Using the void operator with an expression function redirectToGoogle() { window.location.href = "https://www.google.com"; } let result4 = void redirectToGoogle(); document.write("Result 4: " + result4 + "<br>"); // Output: Result 4: undefined </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating the use of the void operator.
Here’s a complete HTML example that demonstrates multiplication (*), division (/), and remainder (%) operations in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Multiplication, Division, and Remainder Operations in JavaScript</title> </head> <body> <h1>Multiplication, Division, and Remainder Operations in JavaScript</h1> <p>This example shows how to perform multiplication, division, and remainder operations:</p> <script> // Example 1: Multiplication let num1 = 5; let num2 = 3; let product = num1 * num2; document.write("Multiplication Result: " + product + "<br>"); // Output: Multiplication Result: 15 // Example 2: Division let dividend = 20; let divisor = 4; let quotient = dividend / divisor; document.write("Division Result: " + quotient + "<br>"); // Output: Division Result: 5 // Example 3: Remainder (Modulus) let dividend2 = 17; let divisor2 = 5; let remainder = dividend2 % divisor2; document.write("Remainder Result: " + remainder + "<br>"); // Output: Remainder Result: 2 </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating multiplication, division, and remainder operations.
Here’s a complete HTML example that demonstrates addition (+) and subtraction (-) operations in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Addition and Subtraction Operations in JavaScript</title> </head> <body> <h1>Addition and Subtraction Operations in JavaScript</h1> <p>This example shows how to perform addition and subtraction operations:</p> <script> // Example 1: Addition let num1 = 10; let num2 = 5; let sum = num1 + num2; document.write("Addition Result: " + sum + "<br>"); // Output: Addition Result: 15 // Example 2: Subtraction let minuend = 20; let subtrahend = 7; let difference = minuend - subtrahend; document.write("Subtraction Result: " + difference + "<br>"); // Output: Subtraction Result: 13 </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating addition and subtraction operations.
Here’s a complete HTML example that demonstrates bitwise shift operations (<<, >>, >>>) in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Bitwise Shift Operations in JavaScript</title> </head> <body> <h1>Bitwise Shift Operations in JavaScript</h1> <p>This example shows how to perform bitwise shift operations:</p> <script> // Example 1: Left Shift (<<) let num = 5; // Binary representation: 00000101 let leftShifted = num << 2; // Shift left by 2 positions document.write("Left Shift Result: " + leftShifted + "<br>"); // Output: Left Shift Result: 20 // Example 2: Right Shift (>>) let num2 = 20; // Binary representation: 00010100 let rightShifted = num2 >> 2; // Shift right by 2 positions document.write("Right Shift Result: " + rightShifted + "<br>"); // Output: Right Shift Result: 5 // Example 3: Unsigned Right Shift (>>>) let num3 = -20; // Binary representation (32-bit): 11111111 11111111 11111111 11101100 let unsignedRightShifted = num3 >>> 2; // Unsigned shift right by 2 positions document.write("Unsigned Right Shift Result: " + unsignedRightShifted + "<br>"); // Output: Unsigned Right Shift Result: 1073741820 </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating bitwise shift operations.
Here’s a complete HTML example that demonstrates relational operators (<, <=, >, >=, in) in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Relational Operators in JavaScript</title> </head> <body> <h1>Relational Operators in JavaScript</h1> <p>This example shows how to use relational operators:</p> <script> // Example 1: Less Than (<) let num1 = 5; let num2 = 10; let isLessThan = num1 < num2; document.write("Is num1 less than num2? " + isLessThan + "<br>"); // Output: Is num1 less than num2? true // Example 2: Less Than or Equal To (<=) let num3 = 15; let num4 = 15; let isLessThanOrEqual = num3 <= num4; document.write("Is num3 less than or equal to num4? " + isLessThanOrEqual + "<br>"); // Output: Is num3 less than or equal to num4? true // Example 3: Greater Than (>) let str1 = "apple"; let str2 = "banana"; let isGreaterThan = str1 > str2; document.write("Is str1 greater than str2? " + isGreaterThan + "<br>"); // Output: Is str1 greater than str2? false // Example 4: Greater Than or Equal To (>=) let arr1 = [1, 2, 3]; let arr2 = [1, 2, 3]; let isGreaterThanOrEqual = arr1 >= arr2; document.write("Is arr1 greater than or equal to arr2? " + isGreaterThanOrEqual + "<br>"); // Output: Is arr1 greater than or equal to arr2? true // Example 5: in Operator let person = { name: "Alice", age: 30 }; let hasAge = "age" in person; document.write("Abubakrs 'age' property exist in person? " + hasAge + "<br>"); // Output: Abubakrs 'age' property exist in person? true let hasEmail = "email" in person; document.write("Abubakrs 'email' property exist in person? " + hasEmail + "<br>"); // Output: Abubakrs 'email' property exist in person? false </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating relational operators and the in operator.
Here’s a complete HTML example that demonstrates equality (==, ===) and inequality (!=, !==) operators in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Equality and Inequality Operators in JavaScript</title> </head> <body> <h1>Equality and Inequality Operators in JavaScript</h1> <p>This example shows how to use equality and inequality operators:</p> <script> // Example 1: Equality (Loose Equality, ==) let num1 = 5; let num2 = "5"; let looseEquality = num1 == num2; document.write("Loose Equality Result: " + looseEquality + "<br>"); // Output: Loose Equality Result: true // Example 2: Strict Equality (===) let num3 = 5; let num4 = 5; let strictEquality = num3 === num4; document.write("Strict Equality Result: " + strictEquality + "<br>"); // Output: Strict Equality Result: true // Example 3: Inequality (!=) let str1 = "apple"; let str2 = "banana"; let inequality = str1 != str2; document.write("Inequality Result: " + inequality + "<br>"); // Output: Inequality Result: true // Example 4: Strict Inequality (!==) let arr1 = [1, 2, 3]; let arr2 = [1, 2, 3]; let strictInequality = arr1 !== arr2; document.write("Strict Inequality Result: " + strictInequality + "<br>"); // Output: Strict Inequality Result: true </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating equality and inequality operators.
Here’s a complete HTML example that demonstrates the bitwise AND (&) operator in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Bitwise AND Operator (&) in JavaScript</title> </head> <body> <h1>Bitwise AND Operator (&) in JavaScript</h1> <p>This example shows how to use the bitwise AND operator:</p> <script> // Example 1: Bitwise AND between two numbers let num1 = 5; // Binary representation: 00000101 let num2 = 3; // Binary representation: 00000011 let bitwiseAndResult = num1 & num2; // Binary result: 00000001 (Decimal: 1) document.write("Bitwise AND Result: " + bitwiseAndResult + "<br>"); // Output: Bitwise AND Result: 1 // Example 2: Using bitwise AND to perform bit masking let color = 0xFFAABB; // RGB color in hexadecimal let redComponent = (color & 0xFF0000) >> 16; // Extracting the red component document.write("Red Component: " + redComponent + "<br>"); // Output: Red Component: 255 </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating the bitwise AND operator (&).
Here’s a complete HTML example that demonstrates the bitwise XOR (^) operator in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Bitwise XOR Operator (^) in JavaScript</title> </head> <body> <h1>Bitwise XOR Operator (^) in JavaScript</h1> <p>This example shows how to use the bitwise XOR operator:</p> <script> // Example 1: Bitwise XOR between two numbers let num1 = 5; // Binary representation: 00000101 let num2 = 3; // Binary representation: 00000011 let bitwiseXorResult = num1 ^ num2; // Binary result: 00000110 (Decimal: 6) document.write("Bitwise XOR Result: " + bitwiseXorResult + "<br>"); // Output: Bitwise XOR Result: 6 // Example 2: Using bitwise XOR to toggle bits let flags = 0b1010; // Binary representation: 1010 let mask = 0b0011; // Binary representation: 0011 let toggledFlags = flags ^ mask; // Binary result: 1001 (Decimal: 9) document.write("Toggled Flags: " + toggledFlags + "<br>"); // Output: Toggled Flags: 9 </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating the bitwise XOR operator (^).
Here’s a complete HTML example that demonstrates the bitwise OR (|) operator in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Bitwise OR Operator (|) in JavaScript</title> </head> <body> <h1>Bitwise OR Operator (|) in JavaScript</h1> <p>This example shows how to use the bitwise OR operator:</p> <script> // Example 1: Bitwise OR between two numbers let num1 = 5; // Binary representation: 00000101 let num2 = 3; // Binary representation: 00000011 let bitwiseOrResult = num1 | num2; // Binary result: 00000111 (Decimal: 7) document.write("Bitwise OR Result: " + bitwiseOrResult + "<br>"); // Output: Bitwise OR Result: 7 // Example 2: Using bitwise OR to set specific bits let flags = 0b0101; // Binary representation: 0101 let mask = 0b0010; // Binary representation: 0010 let setFlags = flags | mask; // Binary result: 0111 (Decimal: 7) document.write("Set Flags: " + setFlags + "<br>"); // Output: Set Flags: 7 </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating the bitwise OR operator (|).
Here’s a complete HTML example that demonstrates the logical AND (&&) operator in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Logical AND Operator (&&) in JavaScript</title> </head> <body> <h1>Logical AND Operator (&&) in JavaScript</h1> <p>This example shows how to use the logical AND operator:</p> <script> // Example 1: Logical AND with boolean values let isTrue = true; let isFalse = false; let result1 = isTrue && isFalse; document.write("Result 1: " + result1 + "<br>"); // Output: Result 1: false // Example 2: Logical AND with expressions let num1 = 5; let num2 = 10; let result2 = (num1 < num2) && (num2 > 0); document.write("Result 2: " + result2 + "<br>"); // Output: Result 2: true // Example 3: Short-circuit behavior let value = false; let result3 = value && someUndefinedVariable; // This won't throw an error document.write("Result 3: " + result3 + "<br>"); // Output: Result 3: false </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating the logical AND operator (&&).
Here’s a complete HTML example that demonstrates the logical OR (||) operator in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Logical OR Operator (||) in JavaScript</title> </head> <body> <h1>Logical OR Operator (||) in JavaScript</h1> <p>This example shows how to use the logical OR operator:</p> <script> // Example 1: Logical OR with boolean values let isTrue = true; let isFalse = false; let result1 = isTrue || isFalse; document.write("Result 1: " + result1 + "<br>"); // Output: Result 1: true // Example 2: Logical OR with expressions let num1 = 5; let num2 = -1; let result2 = (num1 > 0) || (num2 > 0); document.write("Result 2: " + result2 + "<br>"); // Output: Result 2: true // Example 3: Short-circuit behavior let value = true; let result3 = value || someUndefinedVariable; // This won't throw an error document.write("Result 3: " + result3 + "<br>"); // Output: Result 3: true </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating the logical OR operator (||).
Here’s a complete HTML example that demonstrates the conditional (ternary) operator (? 🙂 in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Conditional (Ternary) Operator (? :) in JavaScript</title> </head> <body> <h1>Conditional (Ternary) Operator (? :) in JavaScript</h1> <p>This example shows how to use the conditional operator:</p> <script> // Example 1: Using the ternary operator for simple conditional assignments let age = 25; let isAdult = age >= 18 ? "Yes" : "No"; document.write("Is the person an adult? " + isAdult + "<br>"); // Output: Is the person an adult? Yes // Example 2: Using the ternary operator for more complex expressions let num1 = 10; let num2 = 5; let isGreater = num1 > num2 ? "num1 is greater" : "num2 is greater"; document.write(isGreater + "<br>"); // Output: num1 is greater // Example 3: Nesting ternary operators for multiple conditions let temperature = 25; let weather = temperature > 30 ? "Hot" : temperature > 20 ? "Warm" : "Cool"; document.write("The weather is: " + weather + "<br>"); // Output: The weather is: Warm </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating the conditional (ternary) operator (? :).
Assignment operators are used to assign values to variables. They include the simple assignment (=) operator as well as compound assignment operators like +=, -=, *=, /=, and %=. Here’s a complete HTML example that demonstrates various assignment operators in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Assignment Operators in JavaScript</title> </head> <body> <h1>Assignment Operators in JavaScript</h1> <p>This example shows how to use assignment operators:</p> <script> // Simple Assignment (=) Operator let x = 10; document.write("Simple Assignment: x = " + x + "<br>"); // Output: Simple Assignment: x = 10 // Compound Assignment (+=) Operator let y = 5; y += 3; // Equivalent to: y = y + 3 document.write("Compound Assignment (+=): y = " + y + "<br>"); // Output: Compound Assignment (+=): y = 8 // Compound Assignment (-=) Operator let z = 15; z -= 7; // Equivalent to: z = z - 7 document.write("Compound Assignment (-=): z = " + z + "<br>"); // Output: Compound Assignment (-=): z = 8 // Compound Assignment (*=) Operator let a = 4; a *= 2; // Equivalent to: a = a * 2 document.write("Compound Assignment (*=): a = " + a + "<br>"); // Output: Compound Assignment (*=): a = 8 // Compound Assignment (/=) Operator let b = 16; b /= 4; // Equivalent to: b = b / 4 document.write("Compound Assignment (/=): b = " + b + "<br>"); // Output: Compound Assignment (/=): b = 4 // Compound Assignment (%=) Operator let c = 23; c %= 7; // Equivalent to: c = c % 7 document.write("Compound Assignment (%=): c = " + c + "<br>"); // Output: Compound Assignment (%=): c = 2 </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating different assignment operators.
The comma operator (,) is used to evaluate multiple expressions and return the result of the last expression. Here’s a complete HTML example that demonstrates the comma operator in JavaScript within an HTML document:
<!DOCTYPE html> <html> <head> <title>Comma Operator (,) in JavaScript</title> </head> <body> <h1>Comma Operator (,) in JavaScript</h1> <p>This example shows how to use the comma operator:</p> <script> // Example 1: Using the comma operator in a variable declaration let x = 5, y = 10, z; // Example 2: Using the comma operator in expressions let a = (x++, y++, x + y); document.write("Example 1: x = " + x + ", y = " + y + "<br>"); // Output: Example 1: x = 6, y = 11 document.write("Example 2: a = " + a + "<br>"); // Output: Example 2: a = 17 </script> </body> </html>
In this example:
When you open this HTML file in a web browser, you will see the results of the JavaScript code displayed on the web page, demonstrating the comma operator (,).
Here’s a multiple-choice quiz based on the lesson about JavaScript operators, their types, and usage. Each question has one correct answer.
a) Assignment
b) Mathematical
c) Logical
d) Function
Answer: d) Function
a) 16
b) 11
c) 13
d) 26
Answer: c) 13
a) &
b) ||
c) |
d) ^
Answer: c) |
a) Checks if two values are equal
b) Checks if a property exists in an object
c) Returns the type of a value or expression
d) Performs a logical OR operation
Answer: c) Returns the type of a value or expression
a) It performs a bitwise AND operation
b) It performs a logical AND operation
c) It assigns a value to a variable
d) It increments a variable
Answer: b) It performs a logical AND operation
a) :
b) ?
c) ::
d) ;
Answer: b) ?
a) To concatenate strings
b) To separate function arguments
c) To evaluate multiple expressions and return the result of the last one
d) To perform bitwise operations
Answer: c) To evaluate multiple expressions and return the result of the last one
a) &
b) |
c) ^
d) ~
Answer: c) ^
a) true
b) false
c) undefined
d) NaN
Answer: a) true
a) Equality with type coercion
b) Inequality with type coercion
c) Strict equality without type coercion
d) Strict inequality without type coercion
Answer: d) Strict inequality without type coercion
a) ++
b) +=
c) —
d) -=
Answer: a) ++
a) true
b) false
c) NaN
d) undefined
Answer: b) false
a) +
b) –
c) *
d) /
Answer: a) +
a) It converts a value to a boolean.
b) It specifies an empty function.
c) It evaluates an expression and discards the result.
d) It checks if a variable is undefined.
Answer: c) It evaluates an expression and discards the result.
a) It performs division and returns the quotient.
b) It calculates the remainder after division.
c) It multiplies two numbers.
d) It checks if two values are equal.
Answer: b) It calculates the remainder after division.
a) **
b) ^
c) ^
d) **=
Answer: a) ** (e.g., 2 ** 3 equals 8)
a) Performs bitwise left shift
b) Performs bitwise right shift
c) Performs logical AND operation
d) Performs logical OR operation
Answer: a) Performs bitwise left shift
a) “function”
b) “object”
c) “undefined”
d) “string”
Answer: a) “function”
a) .
b) :
c) ::
d) ;
Answer: a) .
a) A number that is not even
b) A special value representing “undefined”
c) A result that is not a valid number
d) A number that is not divisible by 2
Answer: c) A result that is not a valid number
a) +
b) *
c) concat()
d) join()
Answer: c) concat()
a) 10
b) 0
c) Infinity
d) NaN
Answer: c) Infinity
a) %
b) *
c) ==
d) ++
Answer: c) ==
a) Performs bitwise NOT operation
b) Calculates the square root
c) Converts a string to a number
d) Checks if a value is null
Answer: a) Performs bitwise NOT operation
a) /
b) %
c) *
d) ++
Answer: b) %