questions on functions in javascript
questions on functions in javascript
Q1. What is a function declaration, and how does it differ from a function expression?
• Answer: A function declaration defines a named function using the function keyword,
and it is hoisted to the top of its scope. A function expression defines a function as part of
an expression and is not hoisted.
Q2. Can you call a function declared using a function declaration before it's defined?
• Answer: Yes, you can call a function declared using a function declaration before it's
defined due to hoisting.
Q3. Write a function declaration that takes two parameters and returns their sum.
• Answer:
javascript
Copy code
function sum(a, b) {
return a + b;
}
Function Expression
Q4. What is a function expression, and when should you use it?
javascript
Copy code
const greet = function() {
console.log("Hello!");
};
• Answer: Named function expressions have a name, which can be useful for recursion or
debugging. Anonymous function expressions do not have a name and are often used in
inline callbacks.
Arrow Function
Q7. What are arrow functions, and how do they differ from regular functions?
• Answer: Arrow functions provide a concise syntax and do not have their own this
context. They inherit this from the surrounding code and cannot be used as constructors.
Q8. How would you rewrite the following function as an arrow function?
javascript
Copy code
function multiply(a, b) {
return a * b;
}
• Answer:
javascript
Copy code
const multiply = (a, b) => a * b;
Q9. Can you use the arguments object in arrow functions? Why or why not?
• Answer: No, arrow functions do not have their own arguments object. They inherit
arguments from the outer function.
Anonymous Function
Q11. Write an anonymous function that logs "Hello, World!" and pass it as a callback to
setTimeout.
• Answer:
javascript
Copy code
setTimeout(function() {
console.log("Hello, World!");
}, 1000);
• Answer: Anonymous functions can make debugging harder because they lack a name,
making it difficult to identify them in stack traces.
• Answer: An IIFE is a function that is defined and immediately executed. It's used to
create a private scope and avoid polluting the global scope.
Q14. Write a simple IIFE that logs "This is an IIFE" to the console.
• Answer:
javascript
Copy code
(function() {
console.log("This is an IIFE");
})();
Q15. How did IIFEs help developers before the introduction of block-scoped variables like
let and const?
• Answer: IIFEs helped simulate block scope in JavaScript before let and const by
creating private scopes for variables, preventing variable leakage into the global scope.
Higher-Order Function
javascript
Copy code
function higherOrder(fn) {
return function() {
fn();
};
}
Q17. Explain how map and filter are examples of higher-order functions.
• Answer: map and filter are higher-order functions because they take a callback
function as an argument, applying it to each element of an array.
Q18. Write a higher-order function that takes a function and a number as arguments, and
calls the function that many times.
• Answer:
javascript
Copy code
function repeat(fn, times) {
for (let i = 0; i < times; i++) {
fn();
}
}
Callback Function
Q19. What is a callback function, and why are they important in JavaScript?
Q20. Explain the concept of "callback hell" and how it can be mitigated.
• Answer: "Callback hell" refers to the situation where multiple nested callbacks make
code difficult to read and maintain. It can be mitigated using promises, async/await, or
modularizing the code.
• Answer:
javascript
Copy code
function sayHello() {
console.log("Hello, after 2 seconds");
}
setTimeout(sayHello, 2000);
Recursive Function
Q22. What is recursion, and when would you use a recursive function?
• Answer: Recursion is when a function calls itself to solve a problem. Recursive functions
are used when a problem can be broken down into smaller instances of the same problem,
like calculating factorials or traversing a tree structure.
• Answer:
javascript
Copy code
function factorial(n) {
if (n === 1) return 1;
return n * factorial(n - 1);
}
Q24. What is the base case in recursion, and why is it important?
• Answer: The base case is the condition that stops the recursion. It’s crucial because
without a base case, the function would call itself indefinitely, leading to a stack overflow
error.
Constructor Function
• Answer: A constructor function is used to create objects and is called with the new
keyword. It allows you to define properties and methods for objects created from that
constructor.
Q26. Write a constructor function for creating Person objects with name and age
properties.
• Answer:
javascript
Copy code
function Person(name, age) {
this.name = name;
this.age = age;
}
Q27. How does the new keyword work in conjunction with constructor functions?
• Answer: The new keyword creates a new object, sets this inside the constructor to that
object, and returns the object unless the constructor returns a different object explicitly.
Generator Function
Q28. What is a generator function, and how is it different from a regular function?
• Answer: A generator function is a function that can pause and resume execution using
the yield keyword. It differs from a regular function because it can produce a sequence
of values over time.
Q29. Write a generator function that yields the first three numbers.
• Answer:
javascript
Copy code
function* numbers() {
yield 1;
yield 2;
yield 3;
}
Q30. How do you use the next() method with generator functions?
1. Review the concepts: Go through each question and answer daily until you feel
comfortable with the material.
2. Code practice: Implement the code snippets in your editor to reinforce your
understanding.
3. Mock interviews: Practice explaining these concepts out loud as if you're in an
interview.
Q31. What is the difference between function scope and block scope?
• Answer: Function scope means variables declared inside a function are only accessible within
that function, while block scope restricts variables declared with let and const to the block in
which they are defined.
• Answer: A closure is a function that retains access to its lexical scope, even when the function is
executed outside that scope. This allows the function to remember and access variables from
the original context in which it was created.
• Answer:
javascript
Copy code
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
• Answer: Closures are useful for data encapsulation, creating private variables, and implementing
functions like memoization or event handlers that need to retain state.
this Keyword
Q35. How does the value of this differ in regular functions and arrow functions?
• Answer: In regular functions, this refers to the object that calls the function. In arrow
functions, this is lexically bound, meaning it retains the value of this from its surrounding
context.
Q36. How can you change the value of this inside a function?
• Answer: You can change the value of this using methods like call(), apply(), and bind().
• Answer: call() invokes the function immediately with a specified this context and
arguments. bind() returns a new function with a specified this context but doesn’t invoke it
immediately.
Q38. Write a function using bind() to permanently set the value of this.
• Answer:
javascript
Copy code
const person = {
name: "Alice",
};
function greet() {
console.log(`Hello, ${this.name}`);
}
Q39. What is the arguments object, and how is it used in regular functions?
• Answer: The arguments object is an array-like object available inside regular functions that
contains all the arguments passed to the function, regardless of the number of parameters.
Q40. Why can’t you use the arguments object in arrow functions?
• Answer: Arrow functions do not have their own arguments object; they inherit arguments
from the enclosing function or global scope.
Q41. How can you create a function that accepts a variable number of arguments using rest
parameters?
• Answer: You can use the rest parameter syntax (...args) to gather all remaining arguments
into an array.
javascript
Copy code
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
Q42. Write a function that takes any number of arguments and returns their product using
the arguments object.
• Answer:
javascript
Copy code
function product() {
let result = 1;
for (let i = 0; i < arguments.length; i++) {
result *= arguments[i];
}
return result;
}
Default Parameters
Q43. What are default parameters in JavaScript, and how do you use them?
• Answer: Default parameters allow you to specify default values for function parameters if no
argument or undefined is passed.
javascript
Copy code
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
Q44. Can you use previous parameters as default values for subsequent parameters?
Provide an example.
• Answer: Yes, you can use previous parameters as default values for subsequent parameters.
javascript
Copy code
function greet(firstName, lastName = firstName) {
return `Hello, ${firstName} ${lastName}`;
}
Function Overloading (JavaScript Simulation)
Q45. Does JavaScript support function overloading? How can you simulate it?
• Answer: JavaScript doesn’t support function overloading natively. You can simulate it by
checking the number and types of arguments passed inside the function.
javascript
Copy code
function doSomething(x, y) {
if (typeof y === "undefined") {
// Single argument logic
} else {
// Two argument logic
}
}
Q46. Write a function that behaves differently depending on the number of arguments
provided.
• Answer:
javascript
Copy code
function exampleFunction() {
if (arguments.length === 1) {
console.log("One argument passed");
} else if (arguments.length === 2) {
console.log("Two arguments passed");
}
}
Higher-Order Functions (Advanced)
Q47. How can you create a higher-order function that adds logging to any function?
• Answer:
javascript
Copy code
function logFunction(fn) {
return function(...args) {
console.log(`Arguments: ${args}`);
const result = fn(...args);
console.log(`Result: ${result}`);
return result;
};
}
• Answer: Currying is a technique where a function that takes multiple arguments is transformed
into a series of functions, each taking one argument.
javascript
Copy code
function curry(fn) {
return function(a) {
return function(b) {
return fn(a, b);
};
};
}
• Answer: Function composition is the process of combining two or more functions to produce a
new function. It's useful for creating complex operations from simple functions.
javascript
Copy code
const add = x => x + 1;
const multiply = x => x * 2;
const composedFunction = x => multiply(add(x));
console.log(composedFunction(2)); // 6
Q50. Write a function composition utility that takes two functions and returns their
composition.
• Answer:
javascript
Copy code
function compose(fn1, fn2) {
return function(x) {
return fn1(fn2(x));
};
}
Interview-Oriented Questions
• Answer: JavaScript’s single-threaded nature means it can only execute one task at a time.
Asynchronous functions like setTimeout and promises help handle tasks that might take time
(e.g., network requests) without blocking the main thread.
• Answer: In asynchronous functions using async/await, you handle errors with try...catch.
In promises, use .catch() to handle errors.
javascript
Copy code
async function fetchData() {
try {
const response = await fetch(url);
const data = await response.json();
} catch (error) {
console.error(error);
}
}
Q53. Explain the difference between synchronous and asynchronous functions with an
example.
• Answer: Synchronous functions block the execution of code until they complete, while
asynchronous functions allow the code to continue executing without waiting for the function to
finish.
javascript
Copy code
// Synchronous
function syncFunction() {
console.log("Start");
console.log("End");
}
syncFunction(); // Start, End
// Asynchronous
function asyncFunction() {
console.log("Start");
setTimeout(() => console.log("End"), 1000);
}
asyncFunction(); // Start, End (after 1 second)
• Answer: Function hoisting allows you to use functions before they are defined in the code. This
works only for function declarations, not function expressions or arrow functions.
Q55. How does JavaScript's event loop handle functions that include asynchronous code
like setTimeout?
• Answer: The event loop handles asynchronous code by first executing all synchronous code.
Then, it checks the message queue for tasks like setTimeout callbacks and executes them
when the call stack is empty.