things I've come across in the wild lately in js land im adding to my bag of tricks
-
Arrow Functions vs. Traditional Functions:
- Arrow Functions (New):
const add = (a, b) => a + b;
- Traditional Functions (Old):
const add = function(a, b) { return a + b; };
- Comparison:
Arrow functions are more concise, especially for simple one-liner functions. They also have a lexicalthis
and no binding of their ownthis
, making them useful for certain scenarios.
- Arrow Functions (New):
-
Destructuring Assignment vs. Traditional Assignment:
- Destructuring Assignment (New):
const [first, second] = [1, 2];
- Traditional Assignment (Old):
const first = arr[0]; const second = arr[1];
- Comparison:
Destructuring is more concise and expressive when extracting values from arrays or objects. It reduces the need for multiple lines of assignment statements.
- Destructuring Assignment (New):
-
Template Literals vs. String Concatenation:
- Template Literals (New):
const greeting = `Hello, ${name}!`;
- String Concatenation (Old):
const greeting = "Hello, " + name + "!";
- Comparison:
Template literals provide a cleaner and more readable way to concatenate strings, especially when including variables or expressions within the string.
- Template Literals (New):
-
Default Parameters vs. Manual Default Values:
- Default Parameters (New):
function greet(name = "Guest") { /* ... */ }
- Manual Default Values (Old):
function greet(name) { name = name || "Guest"; // ... }
- Comparison:
Default parameters offer a more explicit and less error-prone way to define default values for function parameters.
- Default Parameters (New):
-
Spread Syntax vs. Concatenation:
- Spread Syntax (New):
const arr2 = [...arr1, 4, 5];
- Concatenation (Old):
const arr2 = arr1.concat([4, 5]);
- Comparison:
Spread syntax is concise and provides a more visually appealing way to merge arrays or objects.
- Spread Syntax (New):
-
Object Literal Enhancements vs. Traditional Object Creation:
- Object Literal Enhancements (New):
const point = { x, y, draw() { /* method implementation */ } };
- Traditional Object Creation (Old):
const point = { x: x, y: y, draw: function() { /* method implementation */ } };
- Comparison:
Object literal enhancements reduce redundancy and make the syntax more concise for defining properties and methods.
- Object Literal Enhancements (New):
-
Promises/Async-Await vs. Callbacks:
- Promises/Async-Await (New):
async function fetchData() { const data = await fetchDataFromAPI(); console.log(data); }
- Callbacks (Old):
fetchDataFromAPI(function(data) { console.log(data); });
- Comparison:
Promises and async-await provide a more structured and readable way to handle asynchronous operations compared to nested callbacks.
- Promises/Async-Await (New):
No comments:
Post a Comment