
10 lesser known JavaScript tricks part 2
Hello again coding friends! I’ve compiled a list of 10 awesome tricks to help you get the most out of your coding. Whether you’re just getting started or you’re already in the game, these tips will give your coding projects a boost.
01. The void operator
Use the void operator to evaluate an expression and return undefined.
const result = void function() {
// Some code here
}();02. Dynamic property names
Create dynamic object properties using square bracket notation.
const dynamicPropertyName = 'color';
const myObject = {
[dynamicPropertyName]: 'blue'
};03. Using Promise.allSettled()
Handle multiple promises with Promise.allSettled(), which returns an array of promise states regardless of fulfillment or rejection.
const promises = [promise1, promise2, promise3];
Promise.allSettled(promises)
.then(results => console.log(results));04. Negative indexing in arrays
Access array elements from the end using negative indexing.
const array = [1, 2, 3, 4, 5];
const lastElement = array.slice(-1)[0];05. Creating unique arrays
Remove duplicate values from an array by converting it to a Set and back.
const uniqueArray = [...new Set(originalArray)];06. String reversal
Reverse a string using the split(), reverse(), and join() methods.
const reversedString = 'Hello'.split('').reverse().join('');07. Fading elements
Create a smooth fade effect using requestAnimationFrame().Call fadeIn(element, duration) to gradually fade in an element.
function fadeIn(element, duration) {
let start = null;
function animate(timestamp) {
if (!start) start = timestamp;
const progress = timestamp - start;
element.style.opacity = Math.min(progress / duration, 1);
if (progress < duration) {
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate);
}08. Intersection observer for lazy loading
Use the Intersection Observer API for lazy loading images or triggering animations when elements come into view.
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// Trigger your action
entry.target.classList.add('animate');
}
});
});
// Start observing a target element
observer.observe(targetElement);09. async and await for asynchronous code
Simplify asynchronous code using the async and await keywords.
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
}10. Array.reduce() for aggregation
Use Array.reduce() to aggregate values from an array.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);





