JavaScript Operators: Performing Calculations and Comparisons
Operators in JavaScript are symbols used to perform operations on values and variables. They are essential for calculations, comparisons, and decision-making in your code.
πΉ Arithmetic Operators
Used for basic math operations:
- + (Addition) β 5 + 3 = 8
- - (Subtraction) β 10 - 4 = 6
- * (Multiplication) β 2 * 3 = 6
- / (Division) β 12 / 4 = 3
- % (Modulus) β 10 % 3 = 1 (remainder)
- ** (Exponentiation) β 2 ** 3 = 8
πΉ Assignment Operators
Used to assign values to variables:
- = β Assigns a value (let x = 5;)
- += β Adds and assigns (x += 2;)
- -= β Subtracts and assigns (x -= 1;)
- *= β Multiplies and assigns (x *= 3;)
πΉ Comparison Operators
Used to compare values:
- == β Equal to (checks value only)
- === β Strict equal (checks value and type)
- != β Not equal
- !== β Strict not equal
- > β Greater than
- < β Less than
- >= β Greater than or equal to
- <= β Less than or equal to
πΉ Logical Operators
Used to combine conditions:
- && (AND) β True if both conditions are true
- || (OR) β True if at least one condition is true
- ! (NOT) β Reverses the condition
Example:
let age = 20;
if (age >= 18 && age < 30) {
console.log("You are a young adult.");
}
πΉ Best Practices
- Use === instead of == to avoid type conversion issues.
- Keep expressions simple for readability.
- Combine logical operators carefully to avoid confusion.
By mastering JavaScript operators, youβll be able to perform calculations, make decisions, and control the flow of your programs effectively.
Comments (Write a comment)
Showing comments related to this blog.