Episode 1 — Fundamentals / 1.20 — Functions

1.20 — Exercise Questions: Functions

Practice questions for all seven subtopics in Section 1.20. Mix of short-answer, prediction, code-writing, and debugging tasks.

How to use this material (instructions)

  1. Read lessons in orderREADME.md, then 1.20.a1.20.g.
  2. Answer closed-book first — then compare to the matching lesson.
  3. Use DevTools Console — test your answers by running code.
  4. Interview prep1.20-Interview-Questions.md.
  5. Quick review1.20-Quick-Revision.md.

1.20.a — Declaration vs Expression (Q1–Q10)

Q1. What is the key syntax difference between a function declaration and a function expression?

Q2. Predict the output. Does this code throw an error? Why or why not?

console.log(greet("Alice"));

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

Q3. Predict the output. Does this code throw an error? Why or why not?

console.log(add(2, 3));

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

Q4. What is the difference between an anonymous function expression and a named function expression? Give one advantage of named expressions.

Q5. Explain what "functions are first-class citizens" means. Give three things you can do with a function because of this.

Q6. Write an IIFE (Immediately Invoked Function Expression) that logs "Hello from IIFE" and does not create any global variables.

Q7. What is the module pattern using IIFE? Write a minimal example with one private variable and one public method.

Q8. Predict the output:

console.log(typeof myFunc);
var myFunc = function () { return 42; };
console.log(typeof myFunc);

Q9. Why should you avoid putting a function declaration inside an if block?

Q10. The Function constructor (new Function(...)) creates functions from strings. Name two reasons why this is almost never used in production code.


1.20.b — Parameters and Arguments (Q11–Q20)

Q11. What is the difference between a parameter and an argument?

Q12. Predict the output:

function demo(a, b, c) {
  console.log(a, b, c);
}
demo(1, 2);

Q13. Write a function greet(name, greeting) where greeting defaults to "Hello". Show what happens when called as greet("Alice") and greet("Alice", "Hi").

Q14. Does passing null trigger a default parameter? What about undefined?

Q15. Write a function sum(...numbers) using rest parameters that returns the sum of all arguments.

Q16. Why are rest parameters preferred over the arguments object? List three reasons.

Q17. Predict the output:

function modify(obj) {
  obj.x = 100;
}

const point = { x: 1, y: 2 };
modify(point);
console.log(point.x);

Q18. Predict the output:

function reassign(obj) {
  obj = { x: 999 };
}

const point = { x: 1 };
reassign(point);
console.log(point.x);

Q19. Write a function that uses destructured parameters to accept an object with name, age, and optional role (default "user").

Q20. What happens if you call a function with destructured parameters but pass no argument, and you forgot = {}? Example:

function demo({ name, age }) {
  console.log(name, age);
}
demo(); // What happens?

1.20.c — Return Values and Scope (Q21–Q33)

Q21. What does a function return if it has no return statement?

Q22. Write a function that returns multiple values (a minimum and maximum) from an array. Show how to destructure the result.

Q23. Rewrite this deeply nested code using early return guard clauses:

function process(input) {
  if (input) {
    if (typeof input === "string") {
      if (input.length > 0) {
        return input.toUpperCase();
      }
    }
  }
  return null;
}

Q24. Name the three scope levels in JavaScript and which variable keywords belong to each.

Q25. What is the difference between var, let, and const regarding block scope?

Q26. Explain lexical scoping in one sentence.

Q27. What is the scope chain? Describe how JavaScript resolves a variable name.

Q28. What is variable shadowing? Is it a bug or a feature?

Q29. Define closure in your own words.

Q30. Write a createCounter() function that uses a closure to maintain private state. It should return an object with increment(), decrement(), and getCount() methods.

Q31. Predict the output:

function makeAdder(x) {
  return function (y) {
    return x + y;
  };
}

const add5 = makeAdder(5);
const add10 = makeAdder(10);
console.log(add5(3));
console.log(add10(3));

Q32. Predict the output and explain:

for (var i = 0; i < 3; i++) {
  setTimeout(function () {
    console.log(i);
  }, 100);
}

Q33. Fix Q32 using let. Explain why it works.


1.20.d — Arrow Functions (Q34–Q42)

Q34. Rewrite as an arrow function: function double(n) { return n * 2; }

Q35. Rewrite as an arrow function: function add(a, b) { return a + b; }

Q36. What is implicit return in arrow functions? When does it apply?

Q37. What is wrong with const getObj = () => { name: "Alice" };? How do you fix it?

Q38. Explain in your own words why arrow functions have a different this behavior.

Q39. Predict the output:

const user = {
  name: "Alice",
  greet: () => {
    console.log(`Hi, I'm ${this.name}`);
  },
};
user.greet();

Q40. Why can arrow functions NOT be used as constructors with new?

Q41. Do arrow functions have their own arguments object?

Q42. Fill in the table:

FeatureRegular FunctionArrow Function
Own this?
Own arguments?
Can use new?
Implicit return?

1.20.e — Reusable Logic (Q43–Q50)

Q43. What does DRY stand for? Give a one-sentence explanation.

Q44. What is the Single Responsibility Principle for functions?

Q45. Define pure function. Give one example of a pure function and one impure function.

Q46. List four common side effects that make a function impure.

Q47. What is a higher-order function? Name two built-in JavaScript examples.

Q48. Write a higher-order function repeat(n, action) that calls action(i) for i from 0 to n-1.

Q49. Why should function names be verb-based? Give three examples of good function names.

Q50. Write a JSDoc comment for this function:

function isValidAge(age) {
  return typeof age === "number" && age >= 0 && age <= 150;
}

1.20.f — Practice Problems (Q51–Q54)

Q51. Write a function isPalindrome(str) that returns true if the string reads the same forward and backward (case-insensitive, ignore non-alphanumeric characters).

Q52. Write a function countVowels(str) that returns the number of vowels (a, e, i, o, u) in a string.

Q53. Write a function fizzBuzz(n) that returns an array from 1 to n where multiples of 3 are "Fizz", multiples of 5 are "Buzz", multiples of both are "FizzBuzz", and all others are the number.

Q54. Write a function titleCase(str) that capitalizes the first letter of each word. Example: "hello world" becomes "Hello World".


1.20.g — Recursion (Q55–Q65)

Q55. What are the two essential parts of every recursive function?

Q56. Write a recursive function countdown(n) that logs numbers from n down to 1, then logs "Done!".

Q57. Write a recursive function sum(n) that returns the sum of all positive integers from 1 to n.

Q58. Trace through factorial(4) step by step, showing each recursive call and return value.

Q59. What causes a stack overflow? Write an example of a function that would cause one.

Q60. Write a recursive fibonacci(n) function. Then explain why it is slow for large n.

Q61. Convert this recursive function to an iterative one:

function power(base, exp) {
  if (exp === 0) return 1;
  return base * power(base, exp - 1);
}

Q62. Write a recursive function flatten(arr) that flattens a nested array. Example: flatten([1, [2, [3, 4]], 5]) returns [1, 2, 3, 4, 5].

Q63. Write a recursive function reverseString(str) that reverses a string without using .reverse() or a loop.

Q64. What is tail call optimization? Why can you not rely on it in JavaScript today?

Q65. What is memoization and how does it improve recursive Fibonacci? Write a memoized version.


Answer hints

QHint
Q3const is not hoisted — ReferenceError
Q8var is hoisted as undefined, then assigned after
Q12Missing argument → undefined
Q14null does NOT trigger default; undefined does
Q17Object mutation — 100
Q18Reassignment inside function does not affect outer — 1
Q20TypeError: Cannot destructure property...
Q318 and 13 — closures capture x
Q323, 3, 3var is function-scoped, shared i
Q37Wrap in (): () => ({ name: "Alice" })
Q39"Hi, I'm undefined" — arrow has no own this
Q42Regular: Yes, Yes, Yes, No. Arrow: No, No, No, Yes
Q584 * 3 * 2 * 1 = 24
Q60O(2^n) — exponential calls, same values recalculated

← Back to 1.20 — Functions (README)