1. Use let
and const
Over var
🔥 Why?
-
Scope:
let
andconst
are block-scoped, making your code more predictable and avoiding those nasty bugs. -
Hoisting: They don't suffer from the hoisting issues
var
does.
let score = 100; // Use for variables that will change
const pi = 3.14159; // Use for constants
2. Master Arrow Functions
🔥 Why?
- Concise: Cleaner and shorter syntax.
-
Lexical
this
: They do not bind their ownthis
, which can be very handy.
const add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5
3. Template Literals for Better Strings
🔥 Why?
- Readability: Easier to read and write strings, especially with variables.
- Multi-line Strings: No need for awkward concatenation or escaping.
const name = 'Alice';
const greeting = `Hello, ${name}! Welcome to Wonderland.`;
console.log(greeting);
4. Destructure for Simplicity
🔥 Why?
- Clarity: Makes your code more readable and concise.
- Efficiency: Pulls out exactly what you need from objects and arrays.
const user = { name: 'John', age: 30 };
const { name, age } = user;
console.log(name, age); // Output: John 30
5. Use Default Parameters
🔥 Why?
- Safety: Ensures functions have sensible default values.
- Simplicity: Reduces the need for manual checks.
function greet(name = 'Stranger') {
return `Hello, ${name}!`;
}
console.log(greet()); // Output: Hello, Stranger!
6. Spread and Rest Operators
🔥 Why?
-
Versatility: Spread (
...
) and rest (...
) operators simplify many tasks like copying arrays, merging objects, and handling function arguments.
// Spread
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5, 6];
console.log(arr2); // Output: [1, 2, 3, 4, 5, 6]
// Rest
function sum(...args) {
return args.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
7. Short-Circuit Evaluation
🔥 Why?
- Efficiency: Helps in writing concise and safer code, especially with default values.
const name = user && user.name;
const defaultValue = input || 'default';
8. Optional Chaining
🔥 Why?
- Safety: Avoids errors when accessing deeply nested properties.
const user = { address: { city: 'Paris' } };
const city = user?.address?.city;
console.log(city); // Output: Paris
9. Avoid ==
and Use ===
🔥 Why?
-
Precision:
===
checks for both value and type, reducing unexpected behavior.
console.log(0 == false); // Output: true
console.log(0 === false); // Output: false
10. Keep Your Code DRY
🔥 Why?
- Maintainability: DRY (Don’t Repeat Yourself) principles make your code easier to maintain and understand.
function calculateTotal(price, tax) {
return price * (1 + tax);
}
const item1Total = calculateTotal(100, 0.15);
const item2Total = calculateTotal(200, 0.15);
Remember, the best way to learn is by doing. So, pick a tip, try it out, and watch your code transform! 🔄
Cheers! 🍻
Follow us: Webcrumbs