? JavaScript Functions master
? JavaScript Functions master
javascript
CopyEdit
function add(a, b) {
return a + b;
}
✅ 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).
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:
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);
javascript
CopyEdit
(() => {
console.log("This is an IIFE 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]
javascript
CopyEdit
const getEvens = arr => arr.filter(num => num % 2 === 0);
console.log(getEvens([1, 2, 3, 4, 5])); // [2, 4]
Basic Level
Intermediate Level
javascript
CopyEdit
function performOperation(a, b, operation) {
return operation(a, b);
}
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.
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
javascript
CopyEdit
async function fetchData() {
const res = await fetch('https://api.example.com');
return await res.json();
}
javascript
CopyEdit
const fn = (...args) => {
console.log(arguments.length);
};
fn(1, 2, 3); // ?
javascript
CopyEdit
add(1).add(2).add(3).value(); // 6