Top 30 Trending JavaScript Coding Examples

To understand these JavaScript examples, you should know the following:

1. Write a function to reverse a string in JavaScript

Code:

function reverseString(str) {
    return str.split('').reverse().join('');
}

console.log(reverseString("JavaScript"));

Output:

tpircSavaJ

Explanation: split(”) converts the string into an array of characters, reverse() reverses the array in place, and join(”) combines the characters back into a string.

2. Check if a string is a palindrome in JavaScript

Code:

function isPalindrome(str) {
    const cleanStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');
    return cleanStr === cleanStr.split('').reverse().join('');
}

console.log(isPalindrome("A man, a plan, a canal: Panama"));

Output:

true

Explanation: Uses regex to remove non-alphanumeric characters and convert to lower case before comparing the string to its reversed version.

3. Flatten a nested array using Array.prototype.flat() in JavaScript

Code:

const nested = [1, [2, [3, 4]], 5];
const flattened = nested.flat(2);

console.log(flattened);

Output:

[ 1, 2, 3, 4, 5 ]

Explanation: Array.prototype.flat(depth) recursively flattens sub-array elements up to the specified depth parameter.

4. Remove duplicate elements from an array using Set in JavaScript

Code:

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];

console.log(uniqueNumbers);

Output:

[ 1, 2, 3, 4, 5 ]

Explanation: Passing an array into new Set() removes duplicate entries because Sets only store unique values. The spread operator … converts it back into an array.

5. Solve the Two Sum problem using a Map for optimal lookup performance in JavaScript

Code:

function twoSum(nums, target) {
    const map = new Map();
    for (let i = 0; i < nums.length; i++) {
        const diff = target - nums[i];
        if (map.has(diff)) {
            return [map.get(diff), i];
        }
        map.set(nums[i], i);
    }
}

console.log(twoSum([2, 7, 11, 15], 9));

Output:

[ 0, 1 ]

Explanation: Stores seen values and their respective array indices inside a JavaScript Map to achieve linear O(n) runtime complexity.

6. Deep clone an object using structuredClone() in JavaScript

Code:

const original = { a: 1, b: { c: 2 } };
const clone = structuredClone(original);

clone.b.c = 42;
console.log(original.b.c);
console.log(clone.b.c);

Output:

2
42

Explanation: The native structuredClone() API creates a true deep copy of JS objects including nested references without modifying original objects.

7. Create a Debounce function to delay function execution in JavaScript

Code:

function debounce(fn, delay) {
    let timer;
    return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => fn.apply(this, args), delay);
    };
}

const log = debounce(() => console.log("Debounced Execution!"), 100);
log();
log();

Output:

Debounced Execution!

Explanation: Debouncing cancels pending timers using clearTimeout whenever triggered again before the delay completes, executing the call only once.

8. Handle asynchronous tasks concurrently using Promise.all() in JavaScript

Code:

const fetchData1 = () => new Promise(resolve => setTimeout(() => resolve("Data 1"), 100));
const fetchData2 = () => new Promise(resolve => setTimeout(() => resolve("Data 2"), 50));

Promise.all([fetchData1(), fetchData2()]).then(results => {
    console.log(results);
});

Output:

[ 'Data 1', 'Data 2' ]

Explanation: Promise.all takes an iterable of promises and returns a single promise that resolves into an array of results once all input promises resolve.

9. Use async/await with try-catch for error handling with JavaScript

Code:

async function fetchUser() {
    try {
        const response = await Promise.resolve({ id: 1, name: "Alice" });
        console.log(response.name);
    } catch (error) {
        console.error("Error:", error);
    }
}

fetchUser();

Output:

Alice

Explanation: async/await provides a cleaner syntax to work with promises synchronously inside try/catch blocks.

10. Group array items by property using Object.groupBy() with JavaScript

Code:

const inventory = [
    { name: "Apples", type: "fruit" },
    { name: "Carrots", type: "vegetable" },
    { name: "Bananas", type: "fruit" }
];

const grouped = Object.groupBy(inventory, item => item.type);
console.log(grouped);

Output:

{
  fruit: [ { name: 'Apples', type: 'fruit' }, { name: 'Bananas', type: 'fruit' } ],
  vegetable: [ { name: 'Carrots', type: 'vegetable' } ]
}

Explanation: Modern Object.groupBy() categorizes elements of an iterable according to string keys returned by a callback function.

11. Safely access deeply nested object properties using optional chaining with JavaScript

Code:

const user = { name: "Bob", details: { age: 30 } };

console.log(user?.details?.age);
console.log(user?.address?.city);

Output:

30
undefined

Explanation: The optional chaining operator ?. stops evaluation and returns undefined instead of throwing a TypeError if the target reference is nullish.

12. Provide fallback values using the Nullish Coalescing Operator in JavaScript

Code:

const count = 0;
const text = "";

console.log(count ?? 10);
console.log(text ?? "Default");
console.log(null ?? "Fallback");

Output:

0

Fallback

Explanation: The nullish coalescing operator ?? returns its right-hand side operand only when its left-hand side operand is null or undefined, unlike || which checks falsy values.

13. Create private class fields using the hash symbol (#) with JavaScript

Code:

class BankAccount {
    #balance = 100;

    getBalance() {
        return this.#balance;
    }
}

const account = new BankAccount();
console.log(account.getBalance());
console.log(account.#balance); // Throws SyntaxError

Output:

100
SyntaxError: Private field '#balance' must be declared in an enclosing class

Explanation: Private class fields designated by the # prefix cannot be accessed or modified outside of the class declaration.

14. Implement a Custom Event Emitter in JavaScript

Code:

class EventEmitter {
    constructor() {
        this.events = {};
    }
    on(event, listener) {
        if (!this.events[event]) this.events[event] = [];
        this.events[event].push(listener);
    }
    emit(event, data) {
        if (this.events[event]) {
            this.events[event].forEach(fn => fn(data));
        }
    }
}

const em = new EventEmitter();
em.on("greet", name => console.log(`Hello ${name}`));
em.emit("greet", "Alice");

Output:

Hello Alice

Explanation: Registers event callbacks inside an array map and executes them sequentially whenever emit() is invoked with matching keys.

15. Memoize an expensive function calculation using closures and Map in JavaScript

Code:

function memoize(fn) {
    const cache = new Map();
    return function (...args) {
        const key = JSON.stringify(args);
        if (cache.has(key)) return cache.get(key);
        const result = fn(...args);
        cache.set(key, result);
        return result;
    };
}

const slowSquare = n => n * n;
const memoizedSquare = memoize(slowSquare);

console.log(memoizedSquare(5));
console.log(memoizedSquare(5));

Output:

25
25

Explanation: Caches function call results based on stringified arguments to return precomputed answers directly for subsequent calls.

16. Curry a function to enable partial execution in JavaScript

Code:

function curry(fn) {
    return function curried(...args) {
        if (args.length >= fn.length) {
            return fn.apply(this, args);
        }
        return (...nextArgs) => curried.apply(this, args.concat(nextArgs));
    };
}

const sum = (a, b, c) => a + b + c;
const curriedSum = curry(sum);

console.log(curriedSum(1)(2)(3));

Output:

6

Explanation: Currying converts a function with multiple parameters into a sequence of functions that accept arguments one by one.

17. Iterate array elements backwards using Array.prototype.at() in JavaScript

Code:

const items = ["a", "b", "c", "d"];

console.log(items.at(-1));
console.log(items.at(-2));

Output:

d
c

Explanation: The .at(index) method accepts negative integers to count backward from the last element in the array.

18. Write a generator function that yields sequential values in JavaScript

Code:

function* numberGenerator() {
    yield 10;
    yield 20;
    yield 30;
}

const gen = numberGenerator();
console.log(gen.next().value);
console.log(gen.next().value);

Output:

10
20

Explanation: Generator functions declared with function* yield values lazily one at a time via iterator objects.

19. Check if two objects are shallowly equal in JavaScript

Code:

function shallowEqual(obj1, obj2) {
    const keys1 = Object.keys(obj1);
    const keys2 = Object.keys(obj2);

    if (keys1.length !== keys2.length) return false;

    return keys1.every(key => obj1[key] === obj2[key]);
}

console.log(shallowEqual({ a: 1, b: 2 }, { a: 1, b: 2 }));

Output:

true

Explanation: Compares key lengths and verifies that every key’s primitive value matches strict equality ===.

20. Create non-configurable object constants using Object.freeze() in JavaScript

Code:

const config = Object.freeze({
    apiEndpoint: "https://api.example.com"
});

config.apiEndpoint = "https://hack.com";
console.log(config.apiEndpoint);

Output:

https://api.example.com

Explanation: Object.freeze prevents adding, deleting, or modifying existing property descriptors on the object.

21. Format numbers into regional currencies using Intl.NumberFormat with JavaScript

Code:

const amount = 123456.78;
const formatter = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD'
});

console.log(formatter.format(amount));

Output:

$123,456.78

Explanation: Intl.NumberFormat provides language-sensitive number and currency formatting capabilities.

22. Sort an array without mutating the original using toSorted() in JavaScript

Code:

const original = [3, 1, 4, 2];
const sorted = original.toSorted();

console.log("Original:", original);
console.log("Sorted:", sorted);

Output:

Original: [ 3, 1, 4, 2 ]
Sorted: [ 1, 2, 3, 4 ]

Explanation: toSorted() returns a newly allocated sorted copy of the array without mutating the source array.

23. Intersection of two arrays using Array.prototype.filter() and Set in JavaScript

Code:

const arr1 = [1, 2, 3, 4];
const arr2 = [3, 4, 5, 6];
const set2 = new Set(arr2);

const intersection = arr1.filter(item => set2.has(item));
console.log(intersection);

Output:

[ 3, 4 ]

Explanation: Filters elements from the first array based on whether they exist in the Set created from the second array.

24. Chunk an array into smaller sub-arrays of specified size in JavaScript

Code:

function chunkArray(arr, size) {
    const chunked = [];
    for (let i = 0; i < arr.length; i += size) {
        chunked.push(arr.slice(i, i + size));
    }
    return chunked;
}

console.log(chunkArray([1, 2, 3, 4, 5], 2));

Output:

[ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]

Explanation: Loops through array index steps equal to size and pushes slices of length size into the output array.

25. Measure function execution timing using console.time() in JavaScript

Code:

console.time("LoopTime");
let sum = 0;
for (let i = 0; i < 1000000; i++) {
    sum += i;
}
console.timeEnd("LoopTime");

Output:

LoopTime: 2.15ms

Explanation: console.time() starts a timer with a given label, and console.timeEnd() stops it and prints elapsed time.

26. Extract object key-value pairs using Object.entries() with JavaScript

Code:

const user = { name: "Alice", role: "Developer" };

for (const [key, value] of Object.entries(user)) {
    console.log(`${key}: ${value}`);
}

Output:

name: Alice
role: Developer

Explanation: Object.entries() returns an array of an object’s own enumerable string-keyed property [key, value] pairs.

27. Format relative dates dynamically using Intl.RelativeTimeFormat with JavaScript

Code:

const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });

console.log(rtf.format(-1, 'day'));
console.log(rtf.format(3, 'week'));

Output:

yesterday
in 3 weeks

Explanation: Intl.RelativeTimeFormat formats relative time durations (e.g., ago, next week) in human-readable strings.

28. Count character frequencies in a string using reduce() with JavaScript

Code:

const str = "javascript";
const freq = str.split('').reduce((acc, char) => {
    acc[char] = (acc[char] || 0) + 1;
    return acc;
}, {});

console.log(freq);

Output:

{ j: 1, a: 2, v: 1, s: 1, c: 1, r: 1, i: 1, p: 1, t: 1 }

Explanation: Array.prototype.reduce() accumulates character counts into an object accumulator.

29. Use JavaScript Proxy to intercept object property access

Code:

const target = { name: "Alice" };
const handler = {
    get: (obj, prop) => (prop in obj ? obj[prop] : "Property missing")
};

const proxy = new Proxy(target, handler);
console.log(proxy.name);
console.log(proxy.age);

Output:

Alice
Property missing

Explanation: JavaScript Proxy objects wrap target objects to redefine fundamental operations like property lookups and assignments.

30. Calculate array element sum using Array.prototype.reduce() in JavaScript

Code:

const numbers = [10, 20, 30, 40];
const total = numbers.reduce((sum, num) => sum + num, 0);

console.log(total);

Output:

100

Explanation: Iterates over the array numbers, adding each element to the running total sum initialized at 0.


If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Recommended Posts

JavaScript Strict Mode
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment