The origin of the term
"Syntactic sugar is a form of syntax that makes things nicer for humans, but adds no new capabilities for the machine."
Examples in JavaScript
1. Classes
class User {
constructor(name) {
this.name = name;
}
}function User(name) {
this.name = name;
}2. Arrow functions
const sum = (a, b) => a + b;function sum(a, b) {
return a + b;
}3. Destructuring
const { name, age } = user;const name = user.name;
const age = user.age;4. Optional chaining
const city = user?.address?.city;const city = user && user.address && user.address.city;How to recognize syntactic sugar
- adds no new functionality — everything can be done without it
- expands into existing constructs at compile time or runtime
- improves readability, not the language's capabilities
- can be removed without changing the program's behavior