[Go to site: main page, start]

0% found this document useful (0 votes)
2 views4 pages

JavaScript Function Real-Time Practice Questions

The document provides a comprehensive overview of JavaScript functions, including definitions, examples, and explanations of various types such as function expressions, arrow functions, closures, recursion, and more. It also covers advanced concepts like debouncing, throttling, and memoization, along with practical applications like event handling and fetching data with promises. Each section includes code snippets demonstrating the concepts in action.

Uploaded by

mk2275000
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views4 pages

JavaScript Function Real-Time Practice Questions

The document provides a comprehensive overview of JavaScript functions, including definitions, examples, and explanations of various types such as function expressions, arrow functions, closures, recursion, and more. It also covers advanced concepts like debouncing, throttling, and memoization, along with practical applications like event handling and fetching data with promises. Each section includes code snippets demonstrating the concepts in action.

Uploaded by

mk2275000
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

©️HackNow Call/WhatsApp: +91 8984988593 Visit: [Link]

in

JavaScript Function Real-Time Practice Questions

1. Define a Function
function greet(name) {
return `Hello, ${name}!`;
}
[Link](greet("John")); // Output: Hello, John!
Explanation: This function takes a name parameter and returns a greeting string using template literals.

2. Function Expression
const square = function(num) {
return num * num;
};
[Link](square(4)); // Output: 16
Explanation: This is a function expression assigned to the variable square, which calculates the square of a number.

3. Anonymous Function
const add = function(a, b) {
return a + b;
};
[Link](add(3, 5)); // Output: 8
Explanation: This is an anonymous function that takes two numbers and returns their sum, assigned to the variable add.

4. Arrow Function
const multiply = (a, b) => a * b;
[Link](multiply(2, 3)); // Output: 6
Explanation: This is an arrow function that takes two parameters and returns their product.

5. Default Parameters
function calculateArea(radius = 1) {
return [Link] * radius * radius;
}
[Link](calculateArea()); // Output: 3.14159...
Explanation: This function calculates the area of a circle and uses a default value of 1 for the radius if no argument is provided.

Intermediate Function Questions

6. Higher-Order Function
function filterEvenNumbers(arr) {
return [Link](num => num % 2 === 0);
}
[Link](filterEvenNumbers([1, 2, 3, 4, 5])); // Output: [2, 4]
Explanation: This function takes an array and returns a new array containing only the even numbers using the filter method.

7. Callback Function
function processArray(arr, callback) {
return [Link](callback);
}
const result = processArray([1, 2, 3], x => x * 2);
[Link](result); // Output: [2, 4, 6]
Explanation: This function takes an array and a callback function, applies the callback to each element using map, and returns a new array.

8. IIFE (Immediately Invoked Function Expression)


(function() {
[Link]("This is an IIFE!");
})();
Explanation: This is an IIFE that executes immediately and logs a message to the console.

9. Function Scope
function example() {
var x = 10; // Function scope
if (true) {
let y = 20; // Block scope
[Link](x); // Output: 10
[Link](y); // Output: 20
}
// [Link](y); // Error: y is not defined
}
example();
Explanation: var is function-scoped, while let is block-scoped. The variable y cannot be accessed outside the block.

©️HackNow Call/WhatsApp: +91 8984988593 Visit: [Link]


©️HackNow Call/WhatsApp: +91 8984988593 Visit: [Link]

10. Closure
function makeCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = makeCounter();
[Link](counter()); // Output: 1
[Link](counter()); // Output: 2

Explanation: This function returns another function that increments and returns a counter, demonstrating closure.

Advanced Function Questions

11. Recursion
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
[Link](factorial(5)); // Output: 120
Explanation: This recursive function calculates the factorial of a number by calling itself.

12. Function Currying


javascript

Copy Code
function add(a) {
return function(b) {
return a + b;
};
}
[Link](add(2)(3)); // Output: 5
Explanation: This curried function takes one argument and returns another function that takes the second argument.

Advanced Function Questions (continued)

13. Debouncing

function debounce(func, delay) {


let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
[Link](this, args);
}, delay);
};
}

const log = debounce(() => [Link]("Debounced!"), 1000);


log(); // Will log "Debounced!" after 1 second if not called again within that time

Explanation: The debounce function limits the rate at which a function can fire. It clears the previous timeout and sets a new one, ensuring that
the function is only called after the specified delay.

©️HackNow Call/WhatsApp: +91 8984988593 Visit: [Link]


©️HackNow Call/WhatsApp: +91 8984988593 Visit: [Link]

14. Throttling

function throttle(func, limit) {


let lastFunc;
let lastRan;
return function(...args) {
if (!lastRan) {
[Link](this, args);
lastRan = [Link]();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(() => {
if (([Link]() - lastRan) >= limit) {
[Link](this, args);
lastRan = [Link]();
}
}, limit - ([Link]() - lastRan));
}
};
}

const log = throttle(() => [Link]("Throttled!"), 2000);


setInterval(log, 500); // Will log "Throttled!" every 2 seconds

Explanation: The throttle function ensures that a function is only called at most once in a specified time interval. It uses a combination of
setTimeout and timestamps to control the execution.

15. Using bind

const person = {
name: "Alice",
greet: function() {
[Link](`Hello, my name is ${[Link]}`);
}
};

const greetAlice = [Link](person);


greetAlice(); // Output: Hello, my name is Alice
Explanation: The bind method creates a new function that, when called, has its this keyword set to the provided value (in this case, the person
object).

Practical Application Questions

16. Event Handling

const button = [Link]("button");


[Link] = "Click me";
[Link](button);

[Link]("click", () => {
[Link]("Button clicked!");
});

Explanation: This code creates a button and adds an event listener that logs a message to the console when the button is clicked.

17. Promise-based Function

function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data fetched!");
}, 2000);
});
}

fetchData().then(data => [Link](data)); // Output: Data fetched! (after 2 seconds)


Explanation: This function returns a promise that resolves with a message after a 2-second delay.

©️HackNow Call/WhatsApp: +91 8984988593 Visit: [Link]


©️HackNow Call/WhatsApp: +91 8984988593 Visit: [Link]

18. Async/Await

async function fetchData() {


const response = await fetch("[Link]
const data = await [Link]();
[Link](data);
}

fetchData(); // Logs the fetched data from the API


Explanation: This async function fetches data from a public API and logs the result to the console using await to handle the promise.

19. Function Composition

function double(x) {
return x * 2;
}

function increment(x) {
return x + 1;
}

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

const doubleThenIncrement = compose(increment, double);


[Link](doubleThenIncrement(3)); // Output: 7 (double: 6, increment: 7)
Explanation: This code defines two simple functions and a compose function that takes two functions and returns a new function that applies
them in sequence.

20. Memoization

function memoize(fn) {
const cache = {};
return function(...args) {
const key = [Link](args);
if (cache[key]) {
return cache[key];
}
const result = fn(...args);
cache[key] = result;
return result;
};
}

const fibonacci = memoize(function(n) {


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

[Link](fibonacci(10)); // Output: 55
[Link](fibonacci(10)); // Output: 55 (retrieved from cache)
[Link](fibonacci(5)); // Output: 5

Explanation: The memoize function creates a cache to store results of previous function calls. The fibonacci function is wrapped in the memoize
function, allowing it to cache results. When the same input is provided again, the cached result is returned instead of recalculating it, improving
performance significantly for recursive calls.

©️HackNow Call/WhatsApp: +91 8984988593 Visit: [Link]

You might also like