Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

? JavaScript Functions master

The document provides an overview of JavaScript functions, including regular function declarations, function expressions, and arrow functions, highlighting their syntax, features, and differences. It includes common interview problems related to function behavior, such as using 'this' in different contexts, converting functions to arrow functions, and coding tasks to practice. Additionally, it presents advanced-level questions on closures, scope, async functions, and function behavior, aimed at preparing for technical interviews.

Uploaded by

bikkykarki171
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)
7 views

? JavaScript Functions master

The document provides an overview of JavaScript functions, including regular function declarations, function expressions, and arrow functions, highlighting their syntax, features, and differences. It includes common interview problems related to function behavior, such as using 'this' in different contexts, converting functions to arrow functions, and coding tasks to practice. Additionally, it presents advanced-level questions on closures, scope, async functions, and function behavior, aimed at preparing for technical interviews.

Uploaded by

bikkykarki171
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
You are on page 1/ 13

JavaScript Functions

✅ Regular Function Declaration:

javascript
CopyEdit
function add(a, b) {
return a + b;
}

• Hoisting: Function declarations are hoisted.


• this Binding: this refers to the calling object (depends on how the function
is called).

✅ Function Expression:

javascript
CopyEdit
const multiply = function(a, b) {
return a * b;
};

• Not hoisted.
• Used as first-class citizens (pass to other functions, assign to variables).

Arrow Functions

✅ Syntax:

javascript
CopyEdit
const add = (a, b) => a + b;

✅ Features:

• Shorter syntax.
• No binding of this, arguments, super, or new.target.
• Cannot be used as a constructor.
• Implicit return if only one expression (no {} needed).

❌ Not suitable for:

• Methods that need this context.


• Using as constructors.
• Using arguments object.

Differences: Function vs Arrow Function

Feature Regular Function Arrow Function


Syntax Verbose Concise
this Dynamic (based on caller) Lexical (based on context)
arguments Available Not available
Constructor Use Can be used with new Cannot be used as constructor
Common Interview Problems & Questions

1. Guess the Output

javascript
CopyEdit
const person = {
name: "Alex",
greet: function () {
console.log("Hi, I'm " + this.name);
},
arrowGreet: () => {
console.log("Hi, I'm " + this.name);
},
};

person.greet(); // ?
person.arrowGreet(); // ?

✅ Output:

rust
CopyEdit
Hi, I'm Alex
Hi, I'm undefined

Reason: arrowGreet doesn't have its own this. It uses the outer lexical context
(likely window), where this.name is undefined.
2. Convert a Function to Arrow Function

Question:

Convert this to an arrow function:

javascript
CopyEdit
function square(x) {
return x * x;
}

Answer:

javascript
CopyEdit
const square = x => x * x;

3. this in SetTimeout

javascript
CopyEdit
const person = {
name: "Alice",
greet() {
setTimeout(function() {
console.log("Hello, " + this.name);
}, 1000);
}
};

person.greet(); // ?

✅ Output:

javascript
CopyEdit
Hello, undefined

Because function() creates its own this. Fix using an arrow function:

javascript
CopyEdit
setTimeout(() => {
console.log("Hello, " + this.name);
}, 1000);

Now it correctly uses this.name from the person object.

4. IIFE with Arrow Function

javascript
CopyEdit
(() => {
console.log("This is an IIFE arrow function");
})();

✅ Output: This is an IIFE arrow function


This is a commonly asked question to test understanding of syntax and scope.

5. Map with Arrow Function

javascript
CopyEdit
const numbers = [1, 2, 3];
const squared = numbers.map(n => n * n);
console.log(squared); // ?

✅ Output:

csharp
CopyEdit
[1, 4, 9]

Shows concise use of arrow function for transformations.

Mini Coding Task (Asked in Interviews)

Write a function to return all even numbers in an array

javascript
CopyEdit
const getEvens = arr => arr.filter(num => num % 2 === 0);
console.log(getEvens([1, 2, 3, 4, 5])); // [2, 4]
Basic Level

1. Write a function that returns the sum of two numbers.


o Then convert it into an arrow function.
2. Create a function that checks if a number is even or odd.
3. Write a function to find the maximum of three numbers.
4. Create an arrow function that returns the square of a number.
5. Write a function that converts a temperature from Celsius to
Fahrenheit.
6. Write a function that returns the factorial of a number.
o Use recursion inside the function.
7. Create a function that takes an array of numbers and returns only the
odd numbers.
o Use .filter() with an arrow function.
8. Write a function that reverses a string.
o Then write the same using an arrow function.
9. Write an arrow function that returns true if a string is a palindrome.
10.Create a function that takes two parameters and returns the greater
one.
o Try solving it with a ternary operator inside an arrow function.

Intermediate Level

11.Write a function that uses setTimeout() to log "Hello" after 1 second.


o What happens if you use an arrow function inside setTimeout?
12.Write a function that counts the number of vowels in a string.
13.Create a function that returns a new array with each element squared.
o Use .map() and arrow functions.
14.Write a function that flattens a nested array (e.g., [1, [2, [3]]] → [1,
2, 3]).

15.Write a function that checks if all elements in an array are positive.


o Use .every() with an arrow function.
16.Write a function using arguments to sum an unknown number of
parameters.
o Why can’t you do this with an arrow function?
17.Write a function that takes a string and returns an object with each
character and its frequency.
18.Write a function that filters out all non-numeric values from an array.
19.Write a function to check whether a given year is a leap year.
20.Write a function that uses a callback (another function) and call it with
an arrow function as the argument.

javascript
CopyEdit
function performOperation(a, b, operation) {
return operation(a, b);
}

const result = performOperation(5, 3, (x, y) => x + y);


console.log(result); // 8

Great! Here's a list of 20 advanced-level JavaScript questions focused on


functions and arrow functions. These are the kind of challenges you might face
in Google, Amazon, Meta, or advanced frontend/backend developer
interviews. These questions test conceptual depth, scope, closures, currying,
callbacks, and async behavior.

Advanced JavaScript Function & Arrow Function


Questions

Closures & Scope

1. Write a function that returns another function which adds a fixed


number to its argument.
o Example: const addFive = createAdder(5); addFive(10); // 15

2. Explain the output:

javascript
CopyEdit
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}

const fn = outer();
fn(); fn(); fn(); // ?
3. Create a function once that allows a function to run only once, and then
always returns the first result.

this and Arrow Function Pitfalls

4. What will be the output? Why?

javascript
CopyEdit
const obj = {
name: "Alice",
greet: () => {
console.log(`Hello, ${this.name}`);
}
};

obj.greet(); // ?

5. Fix the following function to correctly log the person’s name after 1
second:

javascript
CopyEdit
function Person(name) {
this.name = name;
setTimeout(function () {
console.log("Hi, " + this.name);
}, 1000);
}

new Person("Bob");
Currying and Higher-Order Functions

6. Write a curried function that sums three numbers: sum(1)(2)(3) // 6

7. Write a higher-order function repeatFn(fn, n) that calls a given


function fn exactly n times.
8. Write a function compose(f, g) that returns a function such that
compose(f, g)(x) is the same as f(g(x)).

Async Functions with Arrow Syntax

9. Convert the following async function into an arrow function:

javascript
CopyEdit
async function fetchData() {
const res = await fetch('https://api.example.com');
return await res.json();
}

10.Create an async arrow function that waits 2 seconds using setTimeout


and then resolves a message.

Function Behavior & Inheritance

11.Can arrow functions be used as constructors with new keyword?


Explain why with an example.
12.Write a function that mimics the behavior of
Function.prototype.bind()

Real-world Mini Problems

13.Implement a debounce function using closures.


14.Create a memoized version of a factorial function.
15.Write a polyfill for .map() method on an array.

arguments and Rest Parameters

16.Explain the difference between arguments object and rest parameter


...args.

Show with examples for both regular and arrow functions.


17.What will be the output of this code?

javascript
CopyEdit
const fn = (...args) => {
console.log(arguments.length);
};
fn(1, 2, 3); // ?

Function Identity & Equality

18.Why does this return false?


javascript
CopyEdit
const a = () => {};
const b = () => {};
console.log(a === b); // false

19.Write a function that takes another function and returns a throttled


version of it.
20.Create a chainable function like:

javascript
CopyEdit
add(1).add(2).add(3).value(); // 6

You might also like