Javascript Hacks
π‘ JavaScript Hacks That Will Surprise You! Code Like a Pro π
JavaScript is an amazing language β simple to learn yet powerful enough to build complex applications. But did you know there are some hidden hacks and pro tips that can make your coding life easier and cleaner? π€― Here are some mind-blowing JavaScript hacks along with tips for writing clean, professional code.
1. Swap Variables Without a Temporary Variable π€ΉββοΈ
Instead of using a temporary variable to swap two values, you can swap them in a single line!
π§ Hack:
let a = 5, b = 10;
[a, b] = [b, a];
console.log(a, b); // Output: 10, 5
π Pro Tip:
Use array destructuring for clean and concise code whenever possible.
2. Flatten an Array in One Line ποΈ
Got a deeply nested array? You can flatten it in a single line using flat()
.
π§ Hack:
const nestedArray = [1, [2, [3, [4]]]];
const flatArray = nestedArray.flat(Infinity);
console.log(flatArray); // Output: [1, 2, 3, 4]
π Pro Tip:
When working with deeply nested arrays, use flat(Infinity)
for simplicity, but ensure itβs supported by your target environment.
3. Remove Duplicates from an Array in One Line π
Removing duplicates can be done easily using Set
.
π§ Hack:
const array = [1, 2, 2, 3, 4, 4];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // Output: [1, 2, 3, 4]
π Pro Tip:
Use Set
for better performance when handling large datasets.
4. Short-Circuit Evaluation for Default Values π
Instead of using if
statements to check and assign default values, you can use short-circuiting.
π§ Hack:
const user = null;
const userName = user || 'Guest';
console.log(userName); // Output: Guest
π Pro Tip:
Short-circuit evaluation (||
, &&
) makes your code cleaner but be cautious when dealing with falsy values like 0
or ""
.
5. Quick Object Cloning and Merging β¨
Clone or merge objects easily using the spread operator.
π§ Hack:
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // Output: { a: 1, b: 3, c: 4 }
π Pro Tip:
For deep cloning, use structured cloning methods like structuredClone()
or libraries like lodash
.
6. Optional Chaining for Safer Access πΏ
Avoid errors when accessing deeply nested properties with optional chaining.
π§ Hack:
const person = { name: 'John', address: { city: 'New York' } };
console.log(person.address?.city); // Output: New York
console.log(person.contact?.phone); // Output: undefined
π Pro Tip:
Use optional chaining (?.
) to handle properties that may not always exist, especially in APIs.
7. Dynamic Property Keys in Objects π·οΈ
You can define object properties dynamically using computed property names.
π§ Hack:
const key = 'dynamicKey';
const obj = { [key]: 'value' };
console.log(obj); // Output: { dynamicKey: 'value' }
π Pro Tip:
Dynamic keys are useful for creating flexible and dynamic data structures.
8. Convert a NodeList to an Array Easily π
If youβre dealing with DOM elements, you might need to convert a NodeList
into an array.
π§ Hack:
const divs = document.querySelectorAll('div');
const divArray = Array.from(divs); // or [...divs]
console.log(divArray); // Output: [div, div, div...]
π Pro Tip:
Use Array.from
or the spread operator to convert array-like objects into real arrays.
9. Turn Anything Into a Boolean with !!
β
Quickly convert any value to a boolean using double negation (!!
).
π§ Hack:
console.log(!!'Hello'); // Output: true
console.log(!!0); // Output: false
π Pro Tip:
This is a handy trick for explicitly converting values to booleans.
10. Get the Last Item of an Array π
Instead of using array.length - 1
, get the last element of an array using slice
.
π§ Hack:
const numbers = [10, 20, 30, 40];
const lastItem = numbers.slice(-1)[0];
console.log(lastItem); // Output: 40
π Pro Tip:
Use slice(-1)
for clarity, especially when dealing with arrays of varying lengths.
π Final Tips to Code Like a Pro
- Use ESLint and Prettier for consistent and clean code formatting.
- Write modular code by breaking down large functions into smaller, reusable ones.
- Comment wisely β your future self will thank you! π
- Use meaningful variable names β avoid
x
,y
, or cryptic names. - Test your code regularly with tools like Jest or Mocha.
π Wrapping Up
Mastering JavaScript is all about knowing the little tricks that can boost your productivity and writing clean, readable code. Try these hacks in your next project, and youβll be amazed at how efficient and elegant your code becomes! π
Have a favorite JavaScript hack of your own? Share it in the comments below! π
Liked the blog? Share it with your developer friends! ππ»
© Lakhveer Singh Rajput - Blogs. All Rights Reserved.