[Go to site: main page, start]

0% found this document useful (0 votes)
13 views13 pages

JavaScript Function Types and Usage

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)
13 views13 pages

JavaScript Function Types and Usage

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

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 [Link].
• 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 () {
[Link]("Hi, I'm " + [Link]);
},
arrowGreet: () => {
[Link]("Hi, I'm " + [Link]);
},
};

[Link](); // ?
[Link](); // ?

✅ 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 [Link] 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() {
[Link]("Hello, " + [Link]);
}, 1000);
}
};

[Link](); // ?

✅ Output:

javascript
CopyEdit
Hello, undefined

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

javascript
CopyEdit
setTimeout(() => {
[Link]("Hello, " + [Link]);
}, 1000);

Now it correctly uses [Link] from the person object.

4. IIFE with Arrow Function

javascript
CopyEdit
(() => {
[Link]("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 = [Link](n => n * n);
[Link](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 => [Link](num => num % 2 === 0);
[Link](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.
[Link] 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

[Link] a function that uses setTimeout() to log "Hello" after 1 second.


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

[Link] a function that checks if all elements in an array are positive.


o Use .every() with an arrow function.
[Link] a function using arguments to sum an unknown number of
parameters.
o Why can’t you do this with an arrow function?
[Link] a function that takes a string and returns an object with each
character and its frequency.
[Link] a function that filters out all non-numeric values from an array.
[Link] a function to check whether a given year is a leap year.
[Link] 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);


[Link](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++;
[Link](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: () => {
[Link](`Hello, ${[Link]}`);
}
};

[Link](); // ?

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

javascript
CopyEdit
function Person(name) {
[Link] = name;
setTimeout(function () {
[Link]("Hi, " + [Link]);
}, 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('[Link]
return await [Link]();
}

[Link] an async arrow function that waits 2 seconds using setTimeout


and then resolves a message.

Function Behavior & Inheritance

[Link] arrow functions be used as constructors with new keyword?


Explain why with an example.
[Link] a function that mimics the behavior of
[Link]()

Real-world Mini Problems

[Link] a debounce function using closures.


[Link] a memoized version of a factorial function.
[Link] a polyfill for .map() method on an array.

arguments and Rest Parameters

[Link] the difference between arguments object and rest parameter


...args.

Show with examples for both regular and arrow functions.


[Link] will be the output of this code?

javascript
CopyEdit
const fn = (...args) => {
[Link]([Link]);
};
fn(1, 2, 3); // ?

Function Identity & Equality

[Link] does this return false?


javascript
CopyEdit
const a = () => {};
const b = () => {};
[Link](a === b); // false

[Link] a function that takes another function and returns a throttled


version of it.
[Link] a chainable function like:

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

Common questions

Powered by AI

In JavaScript, regular functions have a 'this' binding that is dynamic and depends on the context in which the function is called. This means that 'this' can be different depending on how and where the function is invoked. Arrow functions, on the other hand, have a lexical 'this' binding, meaning they inherit 'this' from the surrounding code at the time of definition, not at execution. Therefore, 'this' within an arrow function refers to the same 'this' as in the outer lexical context where the function was created .

Arrow functions in JavaScript cannot be used as constructors because they do not have a prototype property or their own 'this', super, or new.target bindings. These features are necessary for using the 'new' keyword, which creates instances of a constructor function and requires a prototype to which the instance can be linked. This makes arrow functions unsuitable for instantiating new objects .

Hoisting in JavaScript is the behavior where variable and function declarations are moved to the top of their containing scope during the execution context creation phase. For function declarations, hoisting allows them to be called before they are defined in the code since the declarations are hoisted. For example, you can call "add(2, 3); function add(a, b) { return a + b; }" and it will work because of hoisting. In contrast, function expressions, like "const add = function(a, b) { return a + b; };", are not hoisted. If you attempt to call the function before the assignment, it will result in a 'TypeError' .

To implement a function that adds a fixed number to its argument using closures, define an outer function that captures the fixed number and returns an inner function. The inner function takes the number to be added as its argument and performs the addition. Here is a basic implementation: "function createAdder(fixedNumber) { return function(numberToAdd) { return fixedNumber + numberToAdd; }; }". This way, the inner function retains access to the 'fixedNumber' even after the createAdder execution context has finished, thanks to the closure .

Using an arrow function inside setTimeout affects the 'this' keyword by maintaining the 'this' value from the surrounding lexical context. This is different from regular functions, which create their own 'this' leading to common issues like 'undefined' being logged instead of the intended property. Arrow functions, by capturing the lexical 'this', ensure that 'this' remains bound to the surrounding executable context, such as the object from which the method is called, allowing access to the properties of this object correctly .

To convert a regular function for squaring a number to an arrow function, you would replace the function keyword and curly braces with a concise syntax: "const square = x => x * x;". The benefits of using an arrow function here include shorter syntax, reduced boilerplate code, and the lack of dynamic 'this' binding, which simplifies scoping issues when the 'this' keyword is not needed .

Using arrow functions can be problematic in scenarios where a method relies on the dynamic 'this' binding. For example, if an object method using an arrow function needs to access properties of the calling object through 'this', it will fail because the 'this' inside the arrow function does not refer to the calling object, but to its lexical environment. Also, arrow functions cannot be used in situations where the 'arguments' object is needed, as they do not bind this object .

Understanding the differences between arrow functions and regular functions is crucial when working with methods in objects because the way 'this' is resolved fundamentally affects method behavior. Regular functions have dynamic 'this' that refers to the object itself when called as a method, allowing access to the object's properties. Arrow functions, however, enclose 'this' based on their lexical scope, which can lead to undefined values if they attempt to access properties of the object they are supposed to be methods of. Choosing the wrong type can lead to bugs and unexpected behavior in the code .

Currying transforms a function with multiple arguments into a sequence of functions, each with a single argument. It can be implemented with arrow functions by returning a new arrow function for each argument. For example, the addition function can be curried to "const add = x => y => z => x + y + z;". This allows partial application of arguments and can lead to more modular, readable code. Benefits include the ability to easily create specialized functions by passing fewer arguments and creating new functions on-the-fly, enhancing code reusability and composability .

Function declarations are hoisted, meaning they are moved to the top of their containing scope at runtime, allowing them to be called before they are defined in the code. In contrast, function expressions are not hoisted and are only available after the expression has been evaluated. Regarding context binding, function declarations and expressions both have a 'this' that depends on how they are called ('this' refers to the calling object), whereas arrow functions do not have their own 'this' ('this' is inherited from the enclosing lexical context).

You might also like