JavaScript, as a versatile programming language, employs various types of operators to manipulate data, perform calculations, and execute logical operations. In this post, we'll explore the different types of operators, their use cases, and provide examples to enhance your understanding.
1. Arithmetic Operators:
These operators perform mathematical calculations.
Addition (+): Adds two values.
let result = 5 + 3; // Result: 8
Subtraction (-): Subtracts the right operand from the left operand.
let result = 10 - 4; // Result: 6
Multiplication (*): Multiplies two values.
let result = 3 * 7; // Result: 21
Division (/): Divides the left operand by the right operand.
let result = 20 / 5; // Result: 4
Modulus (%): Returns the remainder of a division.
let result = 15 % 4; // Result: 3
2. Comparison Operators:
These operators compare two values and return a Boolean result.
Equal (==): Checks if two values are equal.
let isEqual = 5 == '5'; // Result: true
Not Equal (!=): Checks if two values are not equal.
let isNotEqual = 10 != 5; // Result: true
Strict Equal (===): Checks if two values are equal and of the same type.
let isStrictEqual = 5 === '5'; // Result: false
Strict Not Equal (!==): Checks if two values are not equal or not of the same type.
let isStrictNotEqual = 10 !== '10'; // Result: true
Greater Than (>): Checks if the left operand is greater than the right operand.
let isGreaterThan = 15 > 10; // Result: true
Less Than (<): Checks if the left operand is less than the right operand.
let isLessThan = 7 < 12; // Result: true
3. Logical Operators:
These operators perform logical operations.
AND (&&): Returns true if both operands are true.
let isBothTrue = true && true; // Result: true
OR (||): Returns true if at least one operand is true.
let isEitherTrue = true || false; // Result: true
NOT (!): Returns the opposite Boolean value of the operand.
let isNotTrue = !false; // Result: true
4. Ternary Operator:
The ternary operator provides a concise way to write simple if...else statements.
Syntax:
condition ? expression_if_true : expression_if_false;
let isEven = (num) => (num % 2 === 0) ? 'Even' : 'Odd';
console.log(isEven(4)); // Output: 'Even'
console.log(isEven(7)); // Output: 'Odd'
Summary:
Understanding JavaScript operators is fundamental for any developer. These operators empower you to manipulate data, make decisions, and perform various operations within your code. As you delve deeper into JavaScript, mastering the usage of operators will contribute to writing more efficient and concise code.
Top comments (0)