7️⃣ Ternary Operator
The ternary operator is a short way to write a simple "if...else".
Instead of:
let age = 20;
let message;
if (age >= 18) {
message = "Adult";
} else {
message = "Minor";
}
You can write:
let age = 20;
let message = age >= 18 ? "Adult" : "Minor";
console.log(message);
Output:
Adult
The structure is:
condition ? valueIfTrue : valueIfFalse
Use it for simple decisions. For complicated logic, a normal "if...else" is usually easier to read.
8️⃣ Nullish Coalescing "??"
This operator is useful when you want a fallback only when a value is "null" or "undefined".
let username = null;
let name = username ?? "Guest";
console.log(name);
Output:
Guest
Compare this with "||":
let score = 0;
console.log(score || 100);
Output:
100
But:
console.log(score ?? 100);
Output:
0
Why?
Because "0" is falsy, but it is not "null" or "undefined".
This distinction becomes very useful when working with real-world data.
9️⃣ Optional Chaining "?."
Optional chaining allows you to safely access properties that may not exist.
Without optional chaining:
let user = {};
console.log(user.address.city);
This can cause an error because "address" doesn't exist.
With optional chaining:
let user = {};
console.log(user.address?.city);
Result:
undefined
Instead of immediately throwing an error.
You'll use this frequently when working with API responses and nested objects.
🔟 Operator Precedence
JavaScript doesn't simply evaluate everything from left to right.
For example:
let result = 10 + 5 * 2;
console.log(result);
Output:
20
Multiplication happens before addition.
You can use parentheses to make the intended order clear:
let result = (10 + 5) * 2;
console.log(result);
Output:
30
When in doubt, use parentheses rather than relying on complicated precedence rules.
1️⃣1️⃣ Expressions
An expression is something that produces a value.
Examples:
10 + 5
produces:
15
Another example:
age >= 18
produces either:
true
or:
false
And:
name ?? "Guest"
produces a value.
Expressions are the building blocks of JavaScript programs.
🧠 Real-World Example
Imagine an online shopping application.
let price = 2000;
let discount = 500;
let isMember = true;
let finalPrice = price - discount;
if (isMember && finalPrice > 1000) {
console.log("Member discount applied");
}
Here you're using:
• Variables
• Arithmetic operators
• Comparison operators
• Logical operators
• Conditions
This is how basic JavaScript concepts start working together in real applications.
🚀 Double Tap ❤️ For Part-4
Post #3695
1.32K
- ❤ 4
- 😈 1