Operators and Expressions in JavaScript
Key Concepts
- Arithmetic Operators
- Assignment Operators
- Comparison Operators
- Logical Operators
- String Operators
- Conditional (Ternary) Operator
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations on numbers. These include addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
Example:
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
Assignment Operators
Assignment operators are used to assign values to variables. The basic assignment operator is (=), but there are also compound assignment operators like +=, -=, *=, /=, and %=.
Example:
let x = 10; x += 5; // x is now 15 x -= 3; // x is now 12 x *= 2; // x is now 24 x /= 4; // x is now 6 x %= 5; // x is now 1
Comparison Operators
Comparison operators are used to compare two values and return a Boolean result (true or false). These include == (equal to), === (equal value and type), != (not equal), !== (not equal value or type), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to).
Example:
let num1 = 10; let num2 = 5; let isEqual = num1 == num2; // false let isIdentical = num1 === num2; // false let isNotEqual = num1 != num2; // true let isGreater = num1 > num2; // true let isLessOrEqual = num1 <= num2; // false
Logical Operators
Logical operators are used to combine multiple conditions. These include && (logical AND), || (logical OR), and ! (logical NOT).
Example:
let isTrue = true; let isFalse = false; let andResult = isTrue && isFalse; // false let orResult = isTrue || isFalse; // true let notResult = !isTrue; // false
String Operators
String operators are used to concatenate strings. The + operator can be used to combine two or more strings.
Example:
let firstName = "John"; let lastName = "Doe"; let fullName = firstName + " " + lastName; // "John Doe"
Conditional (Ternary) Operator
The conditional operator is a shorthand way to write conditional statements. It takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is true, followed by a colon (:), and finally an expression to execute if the condition is false.
Example:
let age = 20; let canVote = (age >= 18) ? "Yes" : "No"; // "Yes"
Conclusion
Understanding operators and expressions is fundamental to mastering JavaScript. By using arithmetic, assignment, comparison, logical, string, and conditional operators, you can perform a wide range of operations and make your code more dynamic and efficient.