Sure, here are some useful JavaScript tricks that can help you in your development:
1. Destructuring Assignment
You can extract values from arrays or properties from objects into distinct variables.
// Array Destructuring
const [first, second] = [10, 20];
console.log(first); // 10
console.log(second); // 20 // Object Destructuring
const { name, age } = { name: 'Alice', age: 25 };
console.log(name); // Alice
console.log(age); // 25
2. Template Literals
Use backticks `
for strings that include variables or expressions.
const name = 'Alice';
const greeting = `Hello, ${name}!`;
console.log(greeting); // Hello, Alice!
3. Default Parameters
You can set default values for function parameters.
function greet(name = 'Guest') { return `Hello, ${name}!`;
}
console.log(greet()); // Hello, Guest!
console.log(greet('Alice')); // Hello, Alice!
4. Arrow Functions
A shorter syntax for writing functions.
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
5. Spread Operator
Spread operator ...
allows an iterable such as an array to be expanded.
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]
6. Rest Parameters
Rest parameters allow you to represent an indefinite number of arguments as an array.
function sum(...numbers) { return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
7. Short-circuit Evaluation
Using &&
and ||
for conditionals.
const user = { name: 'Alice' };
const username = user.name || 'Guest';
console.log(username); // Alice const isLoggedIn = true;
isLoggedIn && console.log('User is logged in'); // User is logged in
8. Optional Chaining
Access deeply nested properties without worrying if an intermediate property is null or undefined.
const user = { address: { street: 'Main St' } };
const street = user?.address?.street;
console.log(street); // Main St
9. Nullish Coalescing Operator
Provides a default value when the left-hand side is null
or undefined
.
const foo = null ?? 'default value';
console.log(foo); // default value
10. Debouncing
Optimize performance by limiting the rate at which a function executes.
function debounce(func, delay) { let debounceTimer; return function() { const context = this; const args = arguments; clearTimeout(debounceTimer); debounceTimer = setTimeout(() => func.apply(context, args), delay); };
} const handleScroll = debounce(() => { console.log('Scrolled!');
}, 300); window.addEventListener('scroll', handleScroll);
These tricks can help you write cleaner, more efficient, and more readable JavaScript code.
Discover more from Coursity
Subscribe to get the latest posts sent to your email.