Interesting Code Snippets in JavaScript
JavaScript is a flexible and powerful programming language that can solve problems in clever and simple ways. Here are some fun JavaScript code snippets that highlight its features and quirks. Whether you're a beginner or an experienced developer, these examples will spark your interest.
1. Flattening an Array
Want to flatten a nested array quickly? JavaScript's flat() method simplifies this task. The Infinity parameter ensures all levels of nesting are flattened.
let a= [1,2,[3,4],[[5,7]]];
let Flat= a.flat(Infinity);
console.log(Flat);
Output
[ 1, 2, 3, 4, 5, 7 ]
In this example
- The flat() method is used to flatten the array a.
- The Infinity parameter ensures that all levels of nesting are flattened.
- The result is a single-level array.
2. Swapping Variables Without a Temporary Variable
Swap the values of two variables in a single line of code using array destructuring.
let n1 = 5;
let n2 = 10;
[n1, n2] = [n2, n1];
console.log(n1, n2);
Output
10 5
In this example
- Array destructuring is used to swap the values of n1 and n2.
- No temporary variable is needed.
- The variables a and b exchange their values directly.
3. Shuffling an Array
The Fisher-Yates algorithm is a common way to shuffle an array, but here’s a concise version using sort() and Math.random():
const a = [1, 2, 3, 4, 5];
const shuffled = a.sort(() => Math.random() - 0.5);
console.log(shuffled);
Output
[ 2, 3, 1, 4, 5 ]
In this example
- The sort() method rearranges array elements in a.
- Math.random() generates a random number to randomize the sorting.
- Keep in mind, this method isn't perfectly random but works well for quick tasks.
4. Quick Array Filtering Using Boolean
Filtering out falsy values (like null, undefined, 0, false, "") is easy using the Boolean constructor.
const a = [0, "hello", false, null, 42, "", undefined];
const falsy = a.filter(value=>!value);
const truthy=a.filter(Boolean);
console.log(falsy);
console.log(truthy);
Output
[ 0, false, null, '', undefined ] [ 'hello', 42 ]
- By the use of Boolean contructor only the truthy value's can be returned from an array .
- By the use of ! operator with any type of data can lead to keeping all the falsy value's in the array in this case the ! operator first convert's all the data to it's corresponding Boolean value's implicitly and then it apply' s negation to that value.
5. Unique Values in an Array
Use the Set object to quickly filter unique values from an array.
const a = [1, 2, 2, 3, 4, 4, 5];
const unique = [...new Set(a)];
console.log(unique);
Output
[ 1, 2, 3, 4, 5 ]
In this example
- The Set object automatically removes duplicate values from a.
- The spread operator ... converts the Set back into an array.
- The result is an array with unique elements.
6. Short-Circuit Evaluation
Simplify conditional assignments using logical operators.
const logged = false;
const greet = logged && 'Welcome back!';
console.log(greet);
const fallback = logged || 'Please log in';
console.log(fallback);
Output
false Please log in
In this example
- && returns the second value if the first is truthy, otherwise it returns the first value.
- || returns the first truthy value it encounters.
- These operators simplify conditional logic.
7. Generate a Random Hex Color
Create random hex colors using JavaScript.
const random = () => `#${Math.floor(Math.random() * 16777215).toString(16)}`;
console.log(random());
Output
#2a3518
In this example
- Math.random() generates a random number.
- Math.floor() ensures the number is an integer.
- The number is converted to a hexadecimal string to form a color code.
8. Debounce Function
Optimize performance by limiting the rate at which a function executes using debounce.
const debounce = (fn, delay) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
};
const log = debounce(() => console.log('Debounced!'), 1000);
window.addEventListener('resize', log);
In this example
- The debounce function delays the execution of fn.
- It clears the timeout if the function is called again within the delay period.
- This prevents rapid, repeated function calls (e.g., during window resizing).
9. Memoization
Improve function efficiency by caching results of expensive calculations.
const memoize = fn => {
const cache = {};
return (...args) => {
const key = JSON.stringify(args);
if (!cache[key]) {
cache[key] = fn(...args);
}
return cache[key];
};
};
const fact = memoize(n => (n <= 1 ? 1 : n * fact(n - 1)));
console.log(fact(5)); // 120
console.log(fact(6)); // 720, but calculates faster
Output
120 720
In this example
- The memoize function stores results of previous calculations in a cache object.
- It checks the cache before running the function to save time.
- This is useful for functions with repeated inputs.
10. Sleep Function
Simulate a sleep function in JavaScript using Promises.
const sleep = ms =>
new Promise(resolve =>
setTimeout(resolve, ms));
async function fun() {
console.log('Start');
await sleep(2000);
console.log('End after 2 seconds');
}
fun();
In this example
- The sleep function returns a promise that resolves after a delay.
- await pauses the execution of the async function until the promise resolves.
- This creates a delay between code executions.