Chapter 7 Beginner 57 Questions

Practice Questions — Functions - Regular, Arrow, and Callback

← Back to Notes
11 Easy
12 Medium
10 Hard

Topic-Specific Questions

Question 1
Easy
What is the output of the following code?
function greet() {
  console.log("Hello!");
}

greet();
greet();
The function is called twice.
Hello!
Hello!
Question 2
Easy
What is the output?
function add(a, b) {
  return a + b;
}

console.log(add(3, 7));
The function returns the sum of a and b.
10
Question 3
Easy
What is the output?
function multiply(a, b) {
  a * b;
}

console.log(multiply(4, 5));
Look carefully - is there a return statement?
undefined
Question 4
Easy
What is the output?
const double = (n) => n * 2;

console.log(double(6));
This is an arrow function with implicit return.
12
Question 5
Easy
What is the output?
function greet(name = "Student") {
  console.log("Hello, " + name);
}

greet("Diya");
greet();
The second call passes no argument, so the default value is used.
Hello, Diya
Hello, Student
Question 6
Easy
What is the output?
sayHello();

function sayHello() {
  console.log("Hello!");
}
Function declarations are hoisted.
Hello!
Question 7
Medium
What is the output?
function sum(...nums) {
  let total = 0;
  for (const n of nums) {
    total += n;
  }
  return total;
}

console.log(sum(1, 2, 3, 4, 5));
Rest parameters collect all arguments into an array.
15
Question 8
Medium
What is the output?
const greet = function(name) {
  return "Hi, " + name;
};

console.log(greet("Arjun"));
console.log(typeof greet);
A function expression stored in a variable. What is the type of a function?
Hi, Arjun
function
Question 9
Medium
What is the output?
function test(a, b, c) {
  console.log(a, b, c);
}

test(1, 2);
What happens when fewer arguments are passed than parameters?
1 2 undefined
Question 10
Medium
What is the output?
const calc = (a, b, operation) => {
  return operation(a, b);
};

const subtract = (x, y) => x - y;

console.log(calc(10, 3, subtract));
subtract is passed as a callback to calc.
7
Question 11
Medium
What is the output?
function outer() {
  const x = 10;
  function inner() {
    console.log(x);
  }
  inner();
}

outer();
Inner functions can access variables from outer functions.
10
Question 12
Hard
What is the output?
function createCounter() {
  let count = 0;
  return function() {
    count++;
    return count;
  };
}

const counter = createCounter();
console.log(counter());
console.log(counter());
console.log(counter());
The returned function remembers the count variable from createCounter.
1
2
3
Question 13
Hard
What is the output?
(function(name) {
  console.log("Hello, " + name);
})("Priya");
This is an IIFE with an argument.
Hello, Priya
Question 14
Hard
What is the output?
const funcs = [];
for (let i = 0; i < 3; i++) {
  funcs.push(() => i);
}

console.log(funcs[0]());
console.log(funcs[1]());
console.log(funcs[2]());
let creates a new variable for each iteration.
0
1
2
Question 15
Hard
What is the output?
function apply(arr, fn) {
  const result = [];
  for (const item of arr) {
    result.push(fn(item));
  }
  return result;
}

const nums = [1, 2, 3, 4];
console.log(apply(nums, n => n * n));
The callback squares each number. What does the result array look like?
[1, 4, 9, 16]
Question 16
Easy
What is the difference between a parameter and an argument?
One is in the definition, the other is in the call.
A parameter is a variable name listed in the function definition (like a placeholder). An argument is the actual value you pass when calling the function. In function greet(name) { }, name is a parameter. In greet("Aarav"), "Aarav" is an argument.
Question 17
Medium
What is a callback function? Give a simple example of when you would use one.
A function passed as an argument to another function.
A callback is a function passed as an argument to another function. The receiving function calls it when it is ready. Example: setTimeout(function() { console.log("Done"); }, 1000). Here the anonymous function is a callback that runs after 1 second. Callbacks are used in event handlers, timers, and array methods.
Question 18
Medium
What is the output?
const square = n => n * n;
const cube = n => n * n * n;

function applyTo5(fn) {
  return fn(5);
}

console.log(applyTo5(square));
console.log(applyTo5(cube));
applyTo5 calls whatever function you pass with the argument 5.
25
125
Question 19
Hard
What is the output?
function makeGreeter(greeting) {
  return (name) => greeting + ", " + name + "!";
}

const hello = makeGreeter("Hello");
const namaste = makeGreeter("Namaste");

console.log(hello("Vikram"));
console.log(namaste("Ananya"));
console.log(hello("Kavya"));
Each call to makeGreeter returns a new function that remembers the greeting.
Hello, Vikram!
Namaste, Ananya!
Hello, Kavya!
Question 20
Easy
What is the output?
const isEven = n => n % 2 === 0;

console.log(isEven(4));
console.log(isEven(7));
The modulo operator % gives the remainder. Even numbers have remainder 0 when divided by 2.
true
false

Mixed & Application Questions

Question 1
Easy
What is the output?
function max(a, b) {
  if (a > b) return a;
  return b;
}

console.log(max(15, 8));
console.log(max(3, 12));
The function returns the larger of two numbers.
15
12
Question 2
Easy
What is the output?
const lengths = ["cat", "elephant", "dog"].map(w => w.length);
console.log(lengths);
map transforms each element. The callback returns the length of each word.
[3, 8, 3]
Question 3
Medium
What is the output?
function repeat(str, times) {
  let result = "";
  for (let i = 0; i < times; i++) {
    result += str;
  }
  return result;
}

console.log(repeat("Ha", 3));
console.log(repeat("*", 5));
The function concatenates the string 'times' number of times.
HaHaHa
*****
Question 4
Medium
What is the output?
const operations = {
  add: (a, b) => a + b,
  sub: (a, b) => a - b,
  mul: (a, b) => a * b
};

console.log(operations.add(5, 3));
console.log(operations.sub(10, 4));
console.log(operations.mul(6, 7));
Functions stored as object properties (methods).
8
6
42
Question 5
Medium
What is the output?
function first(a) {
  return function second(b) {
    return a + b;
  };
}

console.log(first(10)(20));
first(10) returns a function. That function is immediately called with 20.
30
Question 6
Hard
What is the output?
function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}

console.log(factorial(5));
This is a recursive function. It calls itself with a smaller number each time.
120
Question 7
Hard
What is the output?
const pipeline = [n => n * 2, n => n + 10, n => n / 3];

let value = 5;
for (const fn of pipeline) {
  value = fn(value);
}
console.log(value);
Apply each function in sequence: 5 -> *2 -> +10 -> /3.
6.666666666666667
Question 8
Hard
What is the output?
function compose(f, g) {
  return (x) => f(g(x));
}

const double = n => n * 2;
const addOne = n => n + 1;

const doubleThenAdd = compose(addOne, double);
console.log(doubleThenAdd(5));
compose returns a function that applies g first, then f.
11
Question 9
Medium
What is the output?
console.log("Start");
setTimeout(() => console.log("Timer"), 0);
console.log("End");
Even with 0ms delay, setTimeout is asynchronous.
Start
End
Timer
Question 10
Easy
What is the output?
const sayName = (name) => {
  console.log("Name: " + name);
};

sayName("Meera");
Arrow function with braces needs no return for console.log.
Name: Meera
Question 11
Hard
What is an IIFE and why would you use one?
It stands for Immediately Invoked Function Expression.
An IIFE is a function that is defined and immediately called: (function() { })();. It creates a private scope where variables do not pollute the global namespace. It was commonly used before let and const existed to prevent variable leaks. It is still useful for initialization code that should run once and for module patterns.
Question 12
Hard
What is the output?
function once(fn) {
  let called = false;
  let result;
  return function(...args) {
    if (!called) {
      called = true;
      result = fn(...args);
    }
    return result;
  };
}

const addOnce = once((a, b) => a + b);
console.log(addOnce(3, 4));
console.log(addOnce(10, 20));
console.log(addOnce(100, 200));
The function only executes the original function on the first call.
7
7
7
Question 13
Medium
What is the output?
const arr = [1, 2, 3];
arr.forEach((val, idx) => {
  console.log(idx + ": " + val);
});
forEach passes each value and its index to the callback.
0: 1
1: 2
2: 3

Multiple Choice Questions

MCQ 1
What keyword is used to send a value back from a function?
  • A. send
  • B. output
  • C. return
  • D. give
Answer: C
C is correct. The return keyword sends a value back to the caller and stops the function. The other options are not valid JavaScript keywords for this purpose.
MCQ 2
What does a function return if there is no return statement?
  • A. null
  • B. 0
  • C. undefined
  • D. An empty string
Answer: C
C is correct. By default, JavaScript functions return undefined when there is no explicit return statement. This is different from null (option A), which must be returned explicitly.
MCQ 3
Which of these is an arrow function?
  • A. function add(a, b) { return a + b; }
  • B. const add = (a, b) => a + b;
  • C. const add = new Function("a", "b", "return a + b");
  • D. add = def(a, b) { a + b }
Answer: B
B is correct. Arrow functions use the => syntax. Option A is a function declaration. Option C uses the Function constructor (rarely used). Option D is not valid JavaScript syntax.
MCQ 4
What is the term for a function passed as an argument to another function?
  • A. Nested function
  • B. Callback function
  • C. Arrow function
  • D. Static function
Answer: B
B is correct. A function passed as an argument to another function is called a callback. The receiving function decides when and how to call it. Callbacks are fundamental to JavaScript.
MCQ 5
Which type of function is hoisted in JavaScript?
  • A. Arrow functions
  • B. Function expressions
  • C. Function declarations
  • D. All of the above
Answer: C
C is correct. Only function declarations (using the function keyword as a statement) are hoisted. Function expressions and arrow functions stored in variables are NOT hoisted.
MCQ 6
What is the output of: const f = (a, b = 5) => a + b; console.log(f(3));
  • A. 3
  • B. 8
  • C. NaN
  • D. undefined
Answer: B
B is correct. The parameter b has a default value of 5. Since only one argument (3) is passed, a = 3 and b = 5. The function returns 3 + 5 = 8.
MCQ 7
What does rest parameter syntax look like?
  • A. function f(args...)
  • B. function f(...args)
  • C. function f(args[])
  • D. function f(*args)
Answer: B
B is correct. Rest parameters use three dots BEFORE the parameter name: ...args. This collects all remaining arguments into an array. Option D is Python syntax, not JavaScript.
MCQ 8
What does setTimeout do?
  • A. Pauses the entire program for the specified time
  • B. Runs a function once after a delay
  • C. Runs a function repeatedly at intervals
  • D. Sets a time limit on a function
Answer: B
B is correct. setTimeout schedules a function to run once after a specified delay. It does NOT pause the program (option A). Option C describes setInterval.
MCQ 9
What is an IIFE?
  • A. A function that runs in a loop
  • B. A function that calls itself recursively
  • C. A function that is defined and immediately called
  • D. A function with no parameters
Answer: C
C is correct. IIFE stands for Immediately Invoked Function Expression. It is a function wrapped in parentheses and called right away: (function() { })();. It creates a private scope.
MCQ 10
In the arrow function const f = x => x * 2, why are there no parentheses around x?
  • A. Arrow functions never need parentheses
  • B. When there is exactly one parameter, parentheses are optional
  • C. It is a syntax error that happens to work
  • D. Parentheses are only needed for return values
Answer: B
B is correct. Arrow functions allow omitting parentheses when there is exactly one parameter. With zero parameters () => ... or multiple parameters (a, b) => ..., parentheses are required.
MCQ 11
What is the output?
const f = () => {};
console.log(f());
  • A. {}
  • B. null
  • C. undefined
  • D. Error
Answer: C
C is correct. The arrow function has an empty body (the {} is the function block, not an object literal). With no return statement, it returns undefined. If you wanted to return an empty object, you would write () => ({}).
MCQ 12
What is a higher-order function?
  • A. A function defined at the top of the file
  • B. A function that takes a function as argument or returns a function
  • C. A function with more than 5 parameters
  • D. A function that calls itself
Answer: B
B is correct. A higher-order function either takes a function as an argument, returns a function, or both. Examples include map, filter, setTimeout, and addEventListener. Option D describes a recursive function.
MCQ 13
What happens when you call a function with more arguments than it has parameters?
  • A. JavaScript throws an error
  • B. The extra arguments are silently ignored
  • C. The function runs multiple times
  • D. The extra arguments are stored in a special array
Answer: B
B is correct. Extra arguments are simply ignored. function f(a) {} called as f(1, 2, 3) just sets a=1 and ignores 2 and 3. No error is thrown. You can access all arguments using rest parameters (...args).
MCQ 14
What is the difference between clearTimeout and clearInterval?
  • A. They are identical - both work the same way
  • B. clearTimeout cancels setTimeout, clearInterval cancels setInterval
  • C. clearTimeout stops a loop, clearInterval stops a timer
  • D. clearTimeout is synchronous, clearInterval is asynchronous
Answer: B
B is correct. clearTimeout cancels a one-time timer set by setTimeout. clearInterval cancels a repeating timer set by setInterval. Each is paired with its corresponding timer function.
MCQ 15
What is the output of: function f() {} console.log(typeof f);
  • A. "object"
  • B. "function"
  • C. "undefined"
  • D. "string"
Answer: B
B is correct. Functions in JavaScript have their own type. typeof a function returns the string "function". Even though functions are technically objects, typeof distinguishes them.
MCQ 16
What does the ... (spread/rest) syntax do in a function parameter?
  • A. Spreads the function across multiple files
  • B. Collects remaining arguments into an array
  • C. Makes all parameters optional
  • D. Repeats the function call
Answer: B
B is correct. When used in function parameters, ... is the rest syntax. It collects all remaining arguments into an array. function sum(...nums) {} called as sum(1,2,3) makes nums = [1,2,3].
MCQ 17
What is the output?
const f = (x) => x * 2;
console.log(f(f(f(3))));
  • A. 6
  • B. 12
  • C. 24
  • D. 48
Answer: C
C is correct. Working from inside out: f(3) = 6, f(6) = 12, f(12) = 24. Each call doubles the input. Three doublings of 3: 3 * 2 * 2 * 2 = 24.

Coding Challenges

Challenge 1: Temperature Converter

Easy
Write two functions: celsiusToFahrenheit(c) and fahrenheitToCelsius(f). Test them with the values 0, 100, and 72.
Sample Input
(No input required)
Sample Output
0C = 32F 100C = 212F 72F = 22.22C
Use arrow functions. Formula: F = C * 9/5 + 32 and C = (F - 32) * 5/9.
const celsiusToFahrenheit = (c) => c * 9/5 + 32;
const fahrenheitToCelsius = (f) => ((f - 32) * 5/9).toFixed(2);

console.log("0C = " + celsiusToFahrenheit(0) + "F");
console.log("100C = " + celsiusToFahrenheit(100) + "F");
console.log("72F = " + fahrenheitToCelsius(72) + "C");

Challenge 2: Write a Function That Changes a Button's Color

Easy
Write a function called changeColor that takes a button's id and a color, and changes the button's background color when called. Test it with two different buttons.
Sample Input
(No input required - assumes HTML buttons exist)
Sample Output
(Button with id 'btn1' turns purple, button with id 'btn2' turns teal)
Use document.getElementById and style.backgroundColor.
function changeColor(buttonId, color) {
  const btn = document.getElementById(buttonId);
  btn.style.backgroundColor = color;
  btn.style.color = "white";
  btn.style.padding = "10px 20px";
  btn.style.border = "none";
  btn.style.borderRadius = "6px";
  btn.style.cursor = "pointer";
}

// Usage:
// changeColor("btn1", "#a855f7");
// changeColor("btn2", "#06b6d4");

Challenge 3: Array Processor with Callback

Medium
Kavya wants to build a flexible array processor. Write a function processArray(arr, callback) that applies the callback to each element and returns a new array. Test it with doubling, squaring, and checking if numbers are even.
Sample Input
(No input required)
Sample Output
Doubled: [2, 4, 6, 8, 10] Squared: [1, 4, 9, 16, 25] Is Even: [false, true, false, true, false]
Write your own processArray function. Do not use built-in map.
function processArray(arr, callback) {
  const result = [];
  for (const item of arr) {
    result.push(callback(item));
  }
  return result;
}

const nums = [1, 2, 3, 4, 5];
console.log("Doubled:", processArray(nums, n => n * 2));
console.log("Squared:", processArray(nums, n => n * n));
console.log("Is Even:", processArray(nums, n => n % 2 === 0));

Challenge 4: Countdown Timer Function

Medium
Write a function countdown(seconds) that uses setInterval to count down from the given number to 0, printing each second. When it reaches 0, print "Time's up!" and stop the timer.
Sample Input
countdown(5)
Sample Output
5 4 3 2 1 0 Time's up!
Use setInterval and clearInterval. The function should work for any number of seconds.
function countdown(seconds) {
  let remaining = seconds;
  console.log(remaining);
  const timer = setInterval(() => {
    remaining--;
    console.log(remaining);
    if (remaining === 0) {
      console.log("Time's up!");
      clearInterval(timer);
    }
  }, 1000);
}

countdown(5);

Challenge 5: Function Composition

Hard
Arjun wants to chain functions. Write a function compose(...fns) that takes any number of functions and returns a new function that applies them right to left. Test with double, addTen, and half.
Sample Input
(No input required)
Sample Output
Result: 15 (5 -> double -> addTen -> half = 5*2=10, 10+10=20, 20/2=15... wait let me recalculate: right to left means half first, then addTen, then double) compose(double, addTen, half)(20) => double(addTen(half(20))) => double(addTen(10)) => double(20) => 40
Use rest parameters. The rightmost function runs first.
function compose(...fns) {
  return function(x) {
    let result = x;
    for (let i = fns.length - 1; i >= 0; i--) {
      result = fns[i](result);
    }
    return result;
  };
}

const double = n => n * 2;
const addTen = n => n + 10;
const half = n => n / 2;

const transform = compose(double, addTen, half);
console.log(transform(20)); // half(20)=10, addTen(10)=20, double(20)=40 => 40

Challenge 6: Memoize Function

Hard
Meera is learning about optimization. Write a function memoize(fn) that caches the results of expensive function calls. If the same arguments are passed again, return the cached result instead of recalculating.
Sample Input
(No input required)
Sample Output
First call: (calculates) 25 Second call: (from cache) 25 New call: (calculates) 100
Use an object or Map to store cached results. Handle single-argument functions.
function memoize(fn) {
  const cache = {};
  return function(arg) {
    if (arg in cache) {
      console.log("(from cache)");
      return cache[arg];
    }
    console.log("(calculating)");
    const result = fn(arg);
    cache[arg] = result;
    return result;
  };
}

const square = memoize(n => n * n);
console.log(square(5));  // (calculating) 25
console.log(square(5));  // (from cache) 25
console.log(square(10)); // (calculating) 100

Challenge 7: Debounce Function

Hard
Write a debounce function that delays calling the original function until a certain amount of time has passed since the last call. If the function is called again before the delay expires, reset the timer.
Sample Input
(No input required)
Sample Output
(Only the last call executes after the delay period)
Use setTimeout and clearTimeout. Return a new function.
function debounce(fn, delay) {
  let timerId;
  return function(...args) {
    clearTimeout(timerId);
    timerId = setTimeout(() => {
      fn(...args);
    }, delay);
  };
}

// Usage example:
const logMessage = debounce((msg) => {
  console.log("Debounced:", msg);
}, 500);

logMessage("first");  // cancelled
logMessage("second"); // cancelled
logMessage("third");  // runs after 500ms

Need to Review the Concepts?

Go back to the detailed notes for this chapter.

Read Chapter Notes

Want to learn web development with a live mentor?

Explore our Frontend Masterclass