Here are 10 coding-based questions on
JavaScript functions
- Write
a function that takes two numbers as parameters and returns their sum.
- Create a function that
accepts a string as an argument and returns the string reversed.
- Define a function that
checks whether a given number is even or odd and returns the corresponding
result.
- Write a function that
calculates the factorial of a given number using recursion.
- Implement a function that
accepts an array of numbers and returns the largest number in the array.
- Create a higher-order function
that takes a function and a value as arguments, applies the function to
the value, and returns the result.
- Define a function with
default parameters that calculates the area of a rectangle (default length
= 1 and width = 1).
- Write an arrow function that
accepts two arrays, combines them, and returns the resulting array.
- Create a function that takes
any number of arguments, calculates their sum, and returns the result
using rest parameters.
- Write an Immediately Invoked Function
Expression (IIFE) that logs "Welcome to JavaScript Functions!"
to the console.
Solutions for above questions
1. Sum of Two Numbers
Manual:
javascript
// Function to add two numbers
function add(a, b) {
// Return the sum of the
two numbers
return a + b;
}
console.log(add(3, 5)); // Output: 8
Brute Force:
javascript
// Function to add two numbers with
input validation
function add(a, b) {
// Check if both inputs
are numbers
if (typeof a !==
"number" || typeof b !== "number") return "Invalid
inputs!";
// Return the sum if
inputs are valid
return a + b;
}
console.log(add(3, "5"));
// Output: Invalid inputs!
Intermediate:
javascript
// Function with default values for
parameters
function add(a = 0, b = 0) {
// Return the sum of a
and b
return a + b;
}
console.log(add(3)); // Output: 3 (b
defaults to 0)
High-Level:
javascript
// Simplified arrow function for
addition
const add = (a, b) => a + b;
console.log(add(3, 5)); // Output: 8
2. Reverse a String
Manual:
javascript
// Function to reverse a string
manually
function reverseString(str) {
let reversed =
""; // Initialize an empty string for the result
for (let i = str.length -
1; i >= 0; i--) {
// Add each
character from the end of the string
reversed +=
str[i];
}
return reversed;
}
console.log(reverseString("hello"));
// Output: "olleh"
Intermediate:
javascript
// Function using array methods to
reverse a string
function reverseString(str) {
return
str.split("").reverse().join("");
// Step 1: Convert the
string to an array of characters using split()
// Step 2: Reverse the
array using reverse()
// Step 3: Join the array
back into a string using join()
}
console.log(reverseString("hello"));
// Output: "olleh"
High-Level:
javascript
// Simplified arrow function using
spread operator and array methods
const reverseString = (str) =>
[...str].reverse().join("");
// Spread operator (...) splits the
string into an array of characters
console.log(reverseString("hello"));
// Output: "olleh"
3. Even or Odd
Manual:
javascript
// Function to check if a number is
even or odd
function isEvenOrOdd(num) {
// Use modulo operator to
check divisibility by 2
if (num % 2 === 0) return
"Even";
return "Odd";
}
console.log(isEvenOrOdd(7)); //
Output: "Odd"
Intermediate:
javascript
// Function with additional
validation for integer inputs
function isEvenOrOdd(num) {
if
(!Number.isInteger(num)) return "Not an integer!"; // Check for
non-integer inputs
return num % 2 === 0 ?
"Even" : "Odd"; // Ternary operator for concise condition
}
console.log(isEvenOrOdd(7.5)); //
Output: "Not an integer!"
High-Level:
javascript
// Simplified arrow function to check
even/odd
const isEvenOrOdd = (num) => (num
% 2 === 0 ? "Even" : "Odd");
console.log(isEvenOrOdd(10)); //
Output: "Even"
4. Factorial
Manual:
javascript
// Function to calculate factorial
iteratively
function factorial(n) {
if (n === 0) return 1; //
Base case: factorial of 0 is 1
let result = 1;
for (let i = 1; i <=
n; i++) {
result *= i;
// Multiply result by current number
}
return result;
}
console.log(factorial(5)); // Output:
120
Intermediate (Recursive):
javascript
// Recursive function to calculate
factorial
function factorial(n) {
if (n <= 1) return 1;
// Base case: factorial of 0 or 1 is 1
return n * factorial(n -
1); // Multiply current number by factorial of (n-1)
}
console.log(factorial(5)); // Output:
120
High-Level:
javascript
// Optimized recursive function with
memoization
const memo = {}; // Cache for storing
computed results
const factorial = (n) => {
if (n <= 1) return 1;
// Base case
if (memo[n]) return
memo[n]; // Return cached result if available
return (memo[n] = n *
factorial(n - 1)); // Store and return result
};
console.log(factorial(5)); // Output:
120
5. Largest Number in
an Array
Manual:
javascript
// Function to find the largest
number in an array
function findLargest(arr) {
let max = arr[0]; //
Initialize max with the first element
for (let num of arr) {
if (num >
max) max = num; // Update max if current number is greater
}
return max;
}
console.log(findLargest([2, 5, 9,
1])); // Output: 9
Intermediate:
javascript
// Function using Math.max and spread
operator
function findLargest(arr) {
return Math.max(...arr);
// Spread array elements into Math.max
}
console.log(findLargest([2, 5, 9,
1])); // Output: 9
High-Level:
javascript
// High-level function with edge case
handling
const findLargest = (arr) =>
(arr.length ? Math.max(...arr) : null);
// Return null if the array is empty
console.log(findLargest([])); //
Output: null
6. Higher-Order
Function
Manual:
javascript
// Higher-order function that takes
another function as an argument
function operate(a, b, fn) {
return fn(a, b); // Call
the passed function with a and b
}
function multiply(a, b) {
return a * b;
}
console.log(operate(3, 4, multiply));
// Output: 12
Intermediate:
javascript
// Using an inline function as a
parameter
console.log(operate(3, 4, (a, b)
=> a + b)); // Output: 7
7. Area of Rectangle
Manual:
javascript
// Function to calculate area of a
rectangle
function calculateArea(length, width)
{
return length * width;
}
console.log(calculateArea(5, 10)); //
Output: 50
Intermediate:
javascript
// Function with default parameter
values
function calculateArea(length = 1,
width = 1) {
return length * width;
}
console.log(calculateArea(5)); //
Output: 5
High-Level:
javascript
// Simplified arrow function with
default values
const calculateArea = (length = 1,
width = 1) => length * width;
console.log(calculateArea()); //
Output: 1
8. Combine Two Arrays
Manual:
javascript
// Function to combine two arrays
using concat
function combineArrays(arr1, arr2) {
return arr1.concat(arr2);
}
console.log(combineArrays([1, 2], [3,
4])); // Output: [1, 2, 3, 4]
Intermediate:
javascript
// Using spread operator to combine
arrays
function combineArrays(arr1, arr2) {
return [...arr1,
...arr2];
}
console.log(combineArrays([1, 2], [3,
4])); // Output: [1, 2, 3, 4]
9. Sum of Multiple
Arguments
Manual:
javascript
// Function to sum multiple arguments
using arguments object
function sum() {
let total = 0; //
Initialize sum
for (let i = 0; i <
arguments.length; i++) {
total +=
arguments[i]; // Add each argument to total
}
return total;
}
console.log(sum(1, 2, 3)); // Output:
6
Intermediate:
javascript
// Function using rest parameters
function sum(...nums) {
return nums.reduce((acc,
num) => acc + num, 0); // Use reduce to sum up numbers
}
console.log(sum(1, 2, 3, 4)); //
Output: 10
High-Level:
javascript
// Arrow function with rest
parameters
const sum = (...nums) =>
nums.reduce((acc, num) => acc + num, 0);
console.log(sum(1, 2, 3, 4)); //
Output: 10
10. IIFE
Manual:
javascript
// Immediately Invoked Function
Expression
(function () {
console.log("Welcome
to JavaScript Functions!"); // Execute immediately
})();
High-Level:
javascript
// Arrow function version of IIFE
(() => console.log("Welcome
to JavaScript Functions!"))();