50+ Crucial Questions on JavaScript Functions for Coders

Photo by Luca Bravo on Unsplash

50+ Crucial Questions on JavaScript Functions for Coders

Table of contents

Hello all fellow programmers, In this guide, you'll find a collection of 50+ function-related coding questions, designed to help you master key concepts and techniques.

Each question is accompanied by a detailed answer, explaining the logic, steps, and best practices involved in solving it.

Whether you're a beginner looking to build a solid foundation or an experienced developer aiming to refine your skills, these questions cover a wide range of topics, from basic function syntax to advanced functional programming concepts. Let’s begin.

Basic Function Questions

1. Write a function greet(name) that takes a name and returns "Hello, [name]!".

function greet(name) {
    return `Hello, ${name}!`;
}

console.log(greet("Bob")); // Output: "Hello, Bob!"

2. Write a function add(a, b) that returns the sum of two numbers.

function add(a, b) {
    return a + b;
}

console.log(add(3, 5)); // Output: 8

3. Write a function isEven(num) that returns true if a number is even, else false.

function isEven(num) {
    return num % 2 === 0;
}

console.log(isEven(4)); // Output: true
console.log(isEven(7)); // Output: false

4. Write a function maxOfTwo(a, b) that returns the larger number.

function maxOfTwo(a, b) {
    return a > b ? a : b;
}

console.log(maxOfTwo(10, 20)); // Output: 20

5. Write a function square(num) that returns the square of a number.

function square(num) {
    return num * num;
}

console.log(square(5)); // Output: 25

6. Write a function sumArray(arr) that returns the sum of an array of numbers.

function sumArray(arr) {
    return arr.reduce((sum, num) => sum + num, 0);
}

console.log(sumArray([1, 2, 3, 4])); // Output: 10

7. Write a function reverseString(str) that returns a reversed string.

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

console.log(reverseString("hello")); // Output: "olleh"

8. Write a function factorial(n) that returns the factorial of n.

function factorial(n) {
    return n === 0 ? 1 : n * factorial(n - 1);
}

console.log(factorial(5)); // Output: 120

9. Write a function isPalindrome(str) that checks if a string is a palindrome.

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

console.log(isPalindrome("madam")); // Output: true

10. Write a function countVowels(str) that returns the number of vowels in a string.

function countVowels(str) {
    return (str.match(/[aeiou]/gi) || []).length;
}

console.log(countVowels("hello world")); // Output: 3

11. Write a function findMax(arr) that returns the largest number in an array.

function findMax(arr) {
    return Math.max(...arr);
}

console.log(findMax([3, 7, 2, 8, 10])); // Output: 10

12. Write a function removeDuplicates(arr) that removes duplicate values from an array.

function removeDuplicates(arr) {
    return [...new Set(arr)];
}

console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); // Output: [1, 2, 3, 4, 5]

13. Write a function fibonacci(n) that returns the nth Fibonacci number.

function fibonacci(n) {
    return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}

console.log(fibonacci(6)); // Output: 8

14. Write a function capitalizeFirstLetter(str) that capitalizes the first letter of each word.

function capitalizeFirstLetter(str) {
    return str.replace(/\b\w/g, char => char.toUpperCase());
}

console.log(capitalizeFirstLetter("hello world")); // Output: "Hello World"

15. Write a function calculateArea(radius) that returns the area of a circle.

function calculateArea(radius) {
    return Math.PI * Math.pow(radius, 2);
}

console.log(calculateArea(5)); // Output: 78.54

16. Write a function isPrime(num) that checks if a number is prime.

function isPrime(num) {
    if (num < 2) return false;
    for (let i = 2; i <= Math.sqrt(num); i++) {
        if (num % i === 0) return false;
    }
    return true;
}

console.log(isPrime(7)); // Output: true

17. Write a function mergeArrays(arr1, arr2) that merges two arrays without duplicates.

function mergeArrays(arr1, arr2) {
    return [...new Set([...arr1, ...arr2])];
}

console.log(mergeArrays([1, 2, 3], [2, 3, 4])); // Output: [1, 2, 3, 4]

18. Write a function sumDigits(num) that returns the sum of digits in a number.

function sumDigits(num) {
    return [...num.toString()].reduce((sum, digit) => sum + parseInt(digit), 0);
}

console.log(sumDigits(123)); // Output: 6

19. Write a function chunkArray(arr, size) that splits an array into chunks.

function chunkArray(arr, size) {
    let 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, 6], 2)); // Output: [[1, 2], [3, 4], [5, 6]]

20. Write a function debounce(func, delay) that prevents frequent function calls.

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

// Example Usage
const logMessage = debounce(() => console.log("Executed"), 2000);
logMessage(); // Waits 2 seconds before executing

Higher-Order & Callback Function Questions

21. Write a function mapArray(arr, callback) that mimics Array.prototype.map.

function mapArray(arr, callback) {
    let result = [];
    for (let item of arr) {
        result.push(callback(item));
    }
    return result;
}

console.log(mapArray([1, 2, 3], num => num * 2)); // Output: [2, 4, 6]

22. Write a function filterArray(arr, callback) that mimics Array.prototype.filter.

function filterArray(arr, callback) {
    let result = [];
    for (let item of arr) {
        if (callback(item)) result.push(item);
    }
    return result;
}

console.log(filterArray([1, 2, 3, 4, 5], num => num % 2 === 0)); // Output: [2, 4]

23. Write a function reduceArray(arr, callback, initialValue) that mimics Array.prototype.reduce.

function reduceArray(arr, callback, initialValue) {
    let accumulator = initialValue;
    for (let item of arr) {
        accumulator = callback(accumulator, item);
    }
    return accumulator;
}

console.log(reduceArray([1, 2, 3, 4], (sum, num) => sum + num, 0)); // Output: 10

24. Write a function compose(f, g) that composes two functions f(g(x)).

function compose(f, g) {
    return function (x) {
        return f(g(x));
    };
}

// Example usage:
const addOne = x => x + 1;
const double = x => x * 2;

const addOneThenDouble = compose(double, addOne);
console.log(addOneThenDouble(5)); // Output: 12

25. Write a function pipe(...functions) that applies functions in sequence from left to right.

function pipe(...functions) {
    return function (value) {
        return functions.reduce((acc, func) => func(acc), value);
    };
}

// Example usage:
const increment = x => x + 1;
const triple = x => x * 3;
const square = x => x * x;

const pipeline = pipe(increment, triple, square);
console.log(pipeline(2)); // Output: 81

26. Write a function memoize(fn) that optimizes expensive function calls by caching results.

function memoize(fn) {
    let cache = {};
    return function (...args) {
        let key = JSON.stringify(args);
        if (!cache[key]) {
            cache[key] = fn(...args);
        }
        return cache[key];
    };
}

// Example: Optimized factorial using memoization
const memoizedFactorial = memoize(factorial);
console.log(memoizedFactorial(5)); // Output: 120
console.log(memoizedFactorial(6)); // Output: 720 (faster since 5! is cached)

27. Write a function once(fn) that ensures a function can only be called once.

function once(fn) {
    let called = false;
    return function (...args) {
        if (!called) {
            called = true;
            return fn(...args);
        }
    };
}

// Example usage:
const logOnce = once(() => console.log("This runs only once"));
logOnce(); // Output: "This runs only once"
logOnce(); // No output

28. Write a function curry(fn) that converts a function to curried form.

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

// Example usage:
const multiply = (a, b, c) => a * b * c;
const curriedMultiply = curry(multiply);

console.log(curriedMultiply(2)(3)(4)); // Output: 24

29. Write a function throttle(fn, limit) that limits function execution to once per interval.

function throttle(fn, limit) {
    let lastCall = 0;
    return function (...args) {
        const now = Date.now();
        if (now - lastCall >= limit) {
            lastCall = now;
            fn(...args);
        }
    };
}

// Example usage:
const logMessage = throttle(() => console.log("Throttled!"), 2000);
logMessage(); // Runs immediately
logMessage(); // Ignored if called before 2 seconds

30. Write a function delay(fn, ms) that delays the execution of a function by ms milliseconds.

function delay(fn, ms) {
    return function (...args) {
        setTimeout(() => fn(...args), ms);
    };
}

// Example usage:
const delayedHello = delay(() => console.log("Hello after 3 seconds"), 3000);
delayedHello();

1. Write a function multiply(a, b) that returns the product of two numbers.

function multiply(a, b) {
    return a * b;
}

console.log(multiply(3, 4)); // Output: 12

2. Write a function divide(a, b) that returns the quotient of two numbers (handle division by zero).

function divide(a, b) {
    if (b === 0) {
        return 'Error: Division by zero';
    }
    return a / b;
}

console.log(divide(10, 2)); // Output: 5
console.log(divide(10, 0)); // Output: Error: Division by zero

3. Write a function getFullName(firstName, lastName) that returns the full name.

function getFullName(firstName, lastName) {
    return `${firstName} ${lastName}`;
}

console.log(getFullName("John", "Doe")); // Output: John Doe

4. Write a function isEven(num) that returns true if the number is even, false otherwise.

function isEven(num) {
    return num % 2 === 0;
}

console.log(isEven(4)); // Output: true
console.log(isEven(5)); // Output: false

5. Write a function isOdd(num) that returns true if the number is odd, false otherwise.

function isOdd(num) {
    return num % 2 !== 0;
}

console.log(isOdd(3)); // Output: true
console.log(isOdd(6)); // Output: false

6. Write a function sum(...args) that returns the sum of any number of arguments passed to it.

function sum(...args) {
    return args.reduce((acc, num) => acc + num, 0);
}

console.log(sum(1, 2, 3, 4)); // Output: 10

7. Write a function reverseString(str) that returns the reversed version of a string.

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

console.log(reverseString("hello")); // Output: "olleh"

8. Write a function findMax(arr) that returns the largest number in an array.

function findMax(arr) {
    return Math.max(...arr);
}

console.log(findMax([1, 5, 3, 9])); // Output: 9

9. Write a function findMin(arr) that returns the smallest number in an array.

function findMin(arr) {
    return Math.min(...arr);
}

console.log(findMin([10, 3, 7, 5])); // Output: 3

10. Write a function countVowels(str) that returns the number of vowels in a string.

function countVowels(str) {
    return str.match(/[aeiouAEIOU]/g)?.length || 0;
}

console.log(countVowels("hello")); // Output: 2

11. Write a function factorial(n) that returns the factorial of a number using recursion.

function factorial(n) {
    if (n === 0 || n === 1) return 1;
    return n * factorial(n - 1);
}

console.log(factorial(5)); // Output: 120

12. Write a function fibonacci(n) that returns the nth Fibonacci number using recursion.

function fibonacci(n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

console.log(fibonacci(6)); // Output: 8

13. Write a function getSquare(num) that returns the square of a number.

function getSquare(num) {
    return num * num;
}

console.log(getSquare(4)); // Output: 16

14. Write a function multiplyByTwo(arr) that multiplies each element of an array by 2.

function multiplyByTwo(arr) {
    return arr.map(num => num * 2);
}

console.log(multiplyByTwo([1, 2, 3])); // Output: [2, 4, 6]

15. Write a function isPalindrome(str) that checks if a string is a palindrome.

function isPalindrome(str) {
    const reversed = str.split('').reverse().join('');
    return str === reversed;
}

console.log(isPalindrome("madam")); // Output: true
console.log(isPalindrome("hello")); // Output: false

16. Write a function filterNumbers(arr) that filters out only the numbers from an array.

function filterNumbers(arr) {
    return arr.filter(item => typeof item === 'number');
}

console.log(filterNumbers([1, 'a', 2, 'b'])); // Output: [1, 2]

17. Write a function sumDigits(num) that returns the sum of the digits of a number.

function sumDigits(num) {
    return num.toString().split('').reduce((sum, digit) => sum + Number(digit), 0);
}

console.log(sumDigits(123)); // Output: 6

18. Write a function convertToUpper(str) that converts a string to uppercase.

function convertToUpper(str) {
    return str.toUpperCase();
}

console.log(convertToUpper("hello")); // Output: "HELLO"

19. Write a function convertToLower(str) that converts a string to lowercase.

function convertToLower(str) {
    return str.toLowerCase();
}

console.log(convertToLower("HELLO")); // Output: "hello"

20. Write a function calculateArea(radius) that calculates the area of a circle.

function calculateArea(radius) {
    return Math.PI * radius * radius;
}

console.log(calculateArea(5)); // Output: 78.53981633974483

21. Write a function sortArray(arr) that sorts an array in ascending order.

function sortArray(arr) {
    return arr.sort((a, b) => a - b);
}

console.log(sortArray([4, 2, 8, 1])); // Output: [1, 2, 4, 8]

22. Write a function isLeapYear(year) that checks if a year is a leap year.

function isLeapYear(year) {
    return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}

console.log(isLeapYear(2020)); // Output: true
console.log(isLeapYear(2021)); // Output: false

23. Write a function generateRandom(min, max) that generates a random number between min and max.

function generateRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(generateRandom(1, 100)); // Output: A random number between 1 and 100

24. Write a function countWords(str) that counts the number of words in a string.

function countWords(str) {
    return str.split(' ').filter(Boolean).length;
}

console.log(countWords("Hello world! This is JavaScript.")); // Output: 5

25. Write a function parseJSON(str) that parses a JSON string and handles errors.

function parseJSON(str) {
    try {
        return JSON.parse(str);
    } catch (error) {
        return 'Invalid JSON';
    }
}

console.log(parseJSON('{"name": "John"}')); // Output: { name: "John" }
console.log(parseJSON('{name: John}')); // Output: Invalid JSON

26. Write a function convertToDate(str) that converts a string into a Date object.

function convertToDate(str) {
    return new Date(str);
}

console.log(convertToDate("2022-01-01")); // Output: Sat Jan 01 2022 ...

27. Write a function generateID() that returns a random 8-character alphanumeric string.

function generateID() {
    return Math.random().toString(36).substr(2, 8);
}

console.log(generateID()); // Output: Random 8-character string (e.g., "abc12345")

28. Write a function addToArray(arr, item) that adds an item to the end of an array.

function addToArray(arr, item) {
    arr.push(item);
    return arr;
}

console.log(addToArray([1, 2], 3)); // Output: [1, 2, 3]

29. Write a function removeFromArray(arr, item) that removes an item from an array.

function removeFromArray(arr, item) {
    const index = arr.indexOf(item);
    if (index !== -1) {
        arr.splice(index, 1);
    }
    return arr;
}

console.log(removeFromArray([1, 2, 3], 2)); // Output: [1, 3]

30. Write a function shuffleArray(arr) that shuffles the elements of an array randomly.

function shuffleArray(arr) {
    for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[j]] = [arr[j], arr[i]]; // Swap elements
    }
    return arr;
}

console.log(shuffleArray([1, 2, 3, 4])); // Output: Randomly shuffled array

Conclusion :

These questions will give you a great range of practice, from simple functions to more advanced topics involving recursion, array manipulation, closures, and async programming. Try experimenting with variations of each!

Did you find this article valuable?

Support CodeWords by becoming a sponsor. Any amount is appreciated!