Getting Familiar: What are Operators and Expressions?
Operators are as friendly as our primary school math buddies, addition (+), subtraction (-), multiplication (*) and division (/), and as sophisticated as assignment (=), comparison (==, =, !=, !) and logical (&&, ||, !) operators.
Expressions are like recipes, mixing these operators with values to whip up something interesting, such as
2 + 2, or
x = 5, or even
(3 * 4) > 10.
Confused? Well, no worries! We're in this together. Let's break it down.
Peeling Back the Layers: Various Types of Operators
let apples = 10; let oranges = 5; console.log(apples + oranges); // Output: 15 console.log(apples - oranges); // Output: 5 console.log(apples * oranges); // Output: 50 console.log(apples / oranges); // Output: 2
Just like a teacher assigns homework to students, assignment operators are used to assign values to variables. The
let score = 10; // Assigns 10 to score score += 5; // Reassigns score as score + 5, i.e., 15 score -= 3; // Reassigns score as score - 3, i.e., 12 score *= 2; // Reassigns score as score * 2, i.e., 24 score /= 4; // Reassigns score as score / 4, i.e., 6 console.log(score); // Output: 6
Comparison operators are like those judgmental folks who always compare. They compare two values and spill out a
let a = 10; let b = 20; console.log(a == b); // Output: false, because 10 is not equal to 20 console.log(a != b); // Output: true, because 10 is not equal to 20 console.log(a === b); // Output: false, because 10 is not strictly equal to 20 console.log(a !== b); // Output: true, because 10 is not strictly equal to 20 console.log(a > b); // Output: false, because 10 is not greater than 20 console.log(a < b); // Output: true, because 10 is less than 20 console.log(a >= b); // Output: false, because 10 is not greater than or equal to 20 console.log(a <= b); // Output: true, because 10 is less than or equal to 20
Did you notice the double and triple equals signs? The double equals (
==) checks for value equality, while the triple equals (
Logical operators are the wise folks who consider all possibilities before making a decision. These operators work on Boolean values (
false) and return a Boolean result. They include AND (
&&), OR (
||), and NOT (
let x = true; let y = false; console.log(x && y); // Output: false, because one value is false console.log(x || y); // Output: true, because one value is true console.log(!x); // Output: false, because x is not false
prefix) or after (
postfix) the operator. The most common ones are
-- (decrement), and
let score = 10; score++; // score becomes 11 score--; // score becomes 10 again console.log(typeof score); // Output: "number"
?:). It's like a mini if-else statement, deciding what to do based on a condition.
let isRaining = true; let activity = isRaining ? 'Stay indoors' : 'Go outside'; console.log(activity); // Output: "Stay indoors"