#Tricky#Event Loop

Get smart in javascript

Level up your JavaScript expertise with advanced tips, tricks, and gotchas. Master closures, hoisting, coercion, and event loop behavior to write cleaner, bug-free code.

By Pratik Rai

A collection of useful JavaScript patterns and shortcuts that every developer should know. For a deeper dive, check out the MDN JavaScript Guide and JavaScript.info.


1. Array Destructuring

Extract values from arrays or function returns cleanly using destructuring assignment:

JSfile.javascript
1function getValues() { 2 const valA = "abc"; 3 const valB = "def"; 4 return [valA, valB]; 5} 6 7const [a, b] = getValues(); 8console.log(a, b); // "abc" "def"

2. Sorting Numbers Correctly

JavaScript's default sort() converts elements to strings. Use a compare function for numbers:

JSfile.javascript
1const nums = [2, 20, 10]; 2nums.sort((x, y) => x - y); 3console.log(nums); // [2, 10, 20]

3. Remove Duplicates

Use Set to quickly remove duplicate values from an array:

JSfile.javascript
1const arr = [1, 2, 2, 3]; 2const uniqueArr = [...new Set(arr)]; 3console.log(uniqueArr); // [1, 2, 3]

4. Cloning Objects

Shallow Clone

Copies only the first level of properties:

JSfile.javascript
1const obj = { 2 a: "hello", 3 b: "hello again", 4 c: { d: "new hello", e: "new hello again" } 5}; 6 7const clone1 = { ...obj };

Deep Clone

structuredClone creates a true deep copy, handling nested objects, arrays, dates, and more:

JSfile.javascript
1const deepClone = structuredClone(obj); 2deepClone.c.d = "new deep hello"; 3console.log(obj.c.d); // "new hello" 4console.log(deepClone.c.d); // "new deep hello"

5. Creating Arrays

1D Array

JSfile.javascript
1const oneD = new Array(10).fill(2); 2// [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]

2D Array

JSfile.javascript
1const twoD = Array.from({ length: 3 }, () => Array(5).fill(0)); 2// [[0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]]

6. Array Testing: some() & every()

  • some() — returns true if at least one element passes the test
  • every() — returns true if all elements pass the test
JSfile.javascript
1const arrOne = [1, 2, 3, 4]; 2const hasEven = arrOne.some((value) => value % 2 === 0); // true 3const allEven = arrOne.every((value) => value % 2 === 0); // false

7. Finding Min & Max

Use the spread operator with Math.min() and Math.max():

JSfile.javascript
1const numsOne = [1, 2, 3, 5]; 2const mini = Math.min(...numsOne); // 1 3const maxi = Math.max(...numsOne); // 5

8. Easy Variable Swap

Swap two variables without a temporary variable:

JSfile.javascript
1let aa = 10; 2let bb = 20; 3[aa, bb] = [bb, aa]; 4// aa = 20, bb = 10

9. Object to Array Conversions

Extract keys, values, or entries from objects:

JSfile.javascript
1const obj = { a: 1, b: 2, c: 3 }; 2 3const keys = Object.keys(obj); // ["a", "b", "c"] 4const values = Object.values(obj); // [1, 2, 3] 5const entries = Object.entries(obj); // [["a", 1], ["b", 2], ["c", 3]]

10. Swap Object Keys and Values

Swap object keys and values using Object.entries() and Object.fromEntries():

  • Object.entries() returns an array of [key, value] pairs.
  • Object.fromEntries() creates an object from an array of [key, value] pairs.
JSfile.javascript
1const roles = { admin: 1, user: 2, guest: 3 }; 2const swapped = Object.fromEntries( 3 Object.entries(roles).map(([key, value]) => [value, key]) 4); 5console.log(swapped); // { 1: "admin", 2: "user", 3: "guest" }

11. Capitalize First Letter

This pattern splits text into words, capitalizes the first letter while preserving the rest, then joins them back :

JSfile.javascript
1const text = 'hello world from javascript'; 2const capitalized = text.split(' ') 3 .map(word => word[0].toUpperCase() + word.slice(1)) 4 .join(' '); 5console.log(capitalized); 6// 'Hello World From Javascript'

Goal: Learn and memorize these JavaScript tips and tricks. Practice using them in your daily coding.

Frequently asked questions

Are these patterns worth memorising for an interview?
The useful ones are worth recognising instantly, because they save time you would rather spend on the actual problem. Destructuring, `Set` for deduplication, optional chaining and nullish coalescing all remove a few lines from an answer without anybody having to read them carefully.
Which one catches people out most often?
`sort()` without a comparator. It converts elements to strings, so `[2, 20, 10].sort()` gives `[10, 2, 20]`. It is the most common silent bug in this whole list, and it appears in interviews precisely because the wrong answer looks plausible.
What is the difference between a shallow and a deep clone here?
Spread and `Object.assign` copy one level — nested objects are still shared by reference, so mutating one changes both. `structuredClone` is the built-in deep copy and handles cycles, `Map`, `Set` and dates; `JSON.parse(JSON.stringify(x))` is the old approach and quietly loses functions, `undefined`, dates and symbols.
How should these be used in an interview answer?
Deliberately. A concise idiom is good when the reader gains from it and bad when it hides the logic being assessed. If a one-liner makes your reasoning harder to follow, write the longer version and say why.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

JS Output Challenges

Test your JavaScript skills by predicting console output for tricky code snippets. Covers hoisting, closures, this binding, async operations, and event loop quiz questions.

JavaScript · ES6Pratik Rai ·

JavaScript

Promise Output Challenges

Challenge yourself with Promise output quiz questions. Test your understanding of async execution order, resolve/reject behavior, microtasks, and the JavaScript event loop.

JavaScript · ES6Pratik Rai ·

JavaScript

Memoize

Cache a function by its arguments so the same call never computes twice.

JavaScript · ES6Pratik Rai ·