4. JavaScript Operators and Expressions
Operators:
1. Arithmetic Operators:
Addition (
+
): Adds two values.Subtraction (
-
): Subtracts the right operand from the left operand.Multiplication (
*
): Multiplies two values.Division (
/
): Divides the left operand by the right operand.Modulus (
%
): Returns the remainder of a division.
let a = 10;
let b = 5;
let sum = a + b; // 15
let difference = a - b; // 5
let product = a * b; // 50
let quotient = a / b; // 2
let remainder = a % b; // 0
2. Comparison Operators:
Equal to (
==
or===
): Checks if two values are equal.Not equal to (
!=
or!==
): Checks if two values are not equal.Greater than (
>
): Checks if the left operand is greater than the right operand.Less than (
<
): Checks if the left operand is less than the right operand.Greater than or equal to (
>=
): Checks if the left operand is greater than or equal to the right operand.Less than or equal to (
<=
): Checks if the left operand is less than or equal to the right operand.
let x = 5;
let y = 10;
console.log(x === y); // false
console.log(x !== y); // true
console.log(x > y); // false
console.log(x < y); // true
3. Logical Operators:
Logical AND (
&&
): Returns true if both operands are true.Logical OR (
||
): Returns true if at least one operand is true.Logical NOT (
!
): Returns true if the operand is false, and vice versa.
let isTrue = true;
let isFalse = false;
console.log(isTrue && isFalse); // false
console.log(isTrue || isFalse); // true
console.log(!isTrue); // false
4. Assignment Operators:
Assignment (
=
): Assigns a value to a variable.Add and assign (
+=
), Subtract and assign (-=
), Multiply and assign (*=
), Divide and assign (/=
): Combine arithmetic operation with assignment.
let a = 5;
a += 3; // equivalent to a = a + 3; // 8