This content originally appeared on DEV Community and was authored by Shafayet Hossain
Whether you’re new to JavaScript or have been coding for years, there are always new tricks and tips that can make your coding life easier. In this post, we’ll dive into 30 essential JavaScript tricks that will not only improve your code but also boost your productivity!
1. Use const
and let
Instead of var
Say goodbye to var! Using const and let helps prevent scope-related issues and makes your code more predictable.
2. Default Function Parameters
Set default values for function parameters to avoid undefined values.
function greet(name = "Guest") {
console.log(`Hello, ${name}`);
}
3. Arrow Functions for Cleaner Code
Arrow functions offer a cleaner syntax and handle this
context more intuitively.
const add = (a, b) => a + b;
4. Destructuring Arrays and Objects
Destructuring simplifies extracting values from arrays and objects.
const [x, y] = [1, 2];
const { name, age } = { name: "John", age: 30 };
5. Spread Operator for Merging Arrays/Objects
Spread syntax is great for copying and merging arrays or objects.
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]
6. Template Literals for Cleaner Strings
Use backticks for multi-line strings and variable interpolation.
const name = "Alice";
console.log(`Hello, ${name}!`);
7. Optional Chaining (?.)
Access deeply nested object properties without worrying about errors.
const user = { address: { street: "Main St" } };
console.log(user?.address?.street); // Main St
8. Nullish Coalescing Operator (??)
Use ??
to handle nullish values (null
or undefined
).
let name = null;
console.log(name ?? "Guest"); // Guest
9. Array .map()
Method
Easily transform array values.
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2); // [2, 4, 6]
10. Array .filter()
Method
Filter elements based on a condition.
const numbers = [1, 2, 3, 4];
const evenNumbers = numbers.filter(n => n % 2 === 0); // [2, 4]
11. Array .reduce() Method
Reduce an array to a single value, like sum or product.
const numbers = [1, 2, 3];
const sum = numbers.reduce((total, num) => total + num, 0); // 6
12. Short-Circuit Evaluation
Use &&
and ||
for concise conditional logic.
const loggedInUser = user && user.name;
13. Immediately Invoked Function Expressions (IIFE)
Run a function as soon as it's defined.
(function() {
console.log("This runs immediately!");
})();
14. Memoization for Performance Boosts
Store function results to improve performance in expensive operations.
const memoize = fn => {
const cache = {};
return (...args) => {
if (cache[args]) return cache[args];
const result = fn(...args);
cache[args] = result;
return result;
};
};
15. Debouncing and Throttling
Optimize event listeners to improve performance by limiting how often functions are called.
const debounce = (func, delay) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => func(...args), delay);
};
};
16. Object Property Shorthand
Shorthand for defining object properties with the same name as variables.
const name = "Alice";
const user = { name };
17. Object Method Shorthand
Use shorthand syntax for object methods.
const obj = {
greet() {
console.log("Hello!");
}
};
18. Set Timeout and Set Interval
Control function execution timing using setTimeout()
and setInterval()
.
setTimeout(() => console.log("Runs once after 2 seconds"), 2000);
19. Ternary Operator for Simple Conditions
Make simple if-else statements more concise.
const isAdult = age >= 18 ? "Yes" : "No";
20. Object.freeze() to Make Immutable Objects
Prevent changes to an object.
const obj = Object.freeze({ name: "Alice" });
21. Object.keys(), Object.values(), Object.entries()
Quickly retrieve keys, values, or key-value pairs from an object.
const user = { name: "John", age: 30 };
console.log(Object.keys(user)); // ["name", "age"]
22. Async/Await for Clean Asynchronous Code
Handle asynchronous operations in a more readable way.
async function fetchData() {
const data = await fetch('/api/data');
return data.json();
}
23. Promise.all() for Concurrent Async Tasks
Run multiple Promises in parallel and wait for all to resolve.
Promise.all([fetchData1(), fetchData2()]).then(results => console.log(results));
24. Destructuring Function Arguments
Use destructuring directly in function parameters for cleaner code.
function display({ name, age }) {
console.log(`${name} is ${age} years old`);
}
25. The Power of this
Learn how this
behaves in different contexts (functions, classes, arrow functions).
const obj = {
name: "Alice",
greet() {
console.log(this.name);
}
};
26. Handling Asynchronous Loops
Async functions inside loops require careful handling with await
.
for (const item of items) {
await processItem(item);
}
27. Dynamic Property Names
Use dynamic property keys in objects.
const key = "name";
const user = { [key]: "Alice" };
28. Array .some()
and .every()
Methods
Check if some or all elements meet a condition.
javascript
const numbers = [1, 2, 3];
console.log(numbers.some(n => n > 2)); // true
console.log(numbers.every(n => n > 0)); // true
29. Named vs Default Exports
Understand the difference between named and default exports in modules.
export default function() {}
export const myFunction = () => {};
30. Debugging with console.table()
Use console.table()
for visualizing objects or arrays in a table format.
console.table([{ name: "Alice", age: 25 }, { name: "Bob", age: 30 }]);
Conclusion
These 30 JavaScript tricks cover a wide range of techniques that every developer should have in their toolkit. Whether you’re looking to improve performance, clean up your code, or enhance readability, these tips will help you write better, more efficient JavaScript. Comment down below if you have any questions...
My website: https://shafayet.zya.me
A meme for you😉
This content originally appeared on DEV Community and was authored by Shafayet Hossain
Shafayet Hossain | Sciencx (2024-10-23T04:01:00+00:00) Top 30 JavaScript Tricks Every Developer Should Know. Retrieved from https://www.scien.cx/2024/10/23/top-30-javascript-tricks-every-developer-should-know/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.