Javascript
Javascript
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice")); // Output: Hello, Alice
1. Function Declaration
2. Function Expression
3. Arrow Function
// Function Declaration
function add(a, b) {
return a + b;
}
// Function Expression
const multiply = function(a, b) {
return a * b;
};
// Arrow Function
const divide = (a, b) => a / b;
function sum(a, b) {
return a + b;
}
fi
fi
fi
fi
// ❌ Function Expression won't work before definition
console.log(product(5, 5)); // ❌ ReferenceError
(function() {
console.log("IIFE is executed!");
})();
function testScope() {
let localVar = "I am local";
console.log(globalVar); // ✅ Accessible
}
console.log(localVar); // ❌ Error: Not accessible
• Encapsulation
• Data hiding
• Maintaining state
Example: Creating a private counter
function Counter() {
let count = 0;
return {
increment: function() {
count++;
console.log(count);
},
decrement: function() {
count--;
console.log(count);
}
};
}
3. Higher-Order Functions
What is a higher-order function?
function sum(x, y) {
return x + y;
}
function multiplyBy(factor) {
return function(num) {
return num * factor;
};
}
// map()
const squared = arr.map(num => num * num);
console.log(squared); // [1, 4, 9, 16]
// filter()
const evenNumbers = arr.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
// forEach()
arr.forEach(num => console.log(num * num)); // 1, 4, 9, 16
function greet(message) {
console.log(message + ", " + this.name);
}
Method Example
getElementById() document.getElementById("myId")
getElementsByClassNam document.getElementsByClassName("myCla
e() ss")
querySelector() document.querySelector(".myClass")
querySelectorAll() document.querySelectorAll("div")
document.getElementById("demo").innerText = "Hello!";
document.getElementById("demo").innerHTML = "<b>Bold Text</
b>";
Method Description
Changes or adds an
setAttribute() attribute
getAttribute() Gets an attribute's value
removeAttribute(
Removes an attribute
)
• An object is a collection of key-value pairs where keys are strings (properties) and values
can be any data type.
Example:
let person = {
name: "Alice",
age: 25,
greet: function() {
return "Hello, " + this.name;
}
};
console.log(person.greet()); // Output: Hello, Alice
// Object Literal
let car = { brand: "Toyota", model: "Camry" };
// Constructor Function
function Person(name, age) {
this.name = name;
this.age = age;
}
let person1 = new Person("John", 30);
// ES6 Class
class Animal {
constructor(name) {
this.name = name;
}
}
let dog = new Animal("Bulldog");
// Accessing
console.log(person.name); // John
console.log(person["age"]); // 30
// Modifying
person.age = 35;
person["name"] = "Alice";
• Using for...in
• Using Object.keys()
• Using Object.entries()
Example:
// Using for...in
for (let key in user) {
console.log(key, user[key]);
}
// Using Object.keys()
Object.keys(user).forEach(key => console.log(key,
user[key]));
// Using Object.entries()
Object.entries(user).forEach(([key, value]) =>
console.log(key, value));
Feature Example
Spread
let obj2 = { ...obj1 };
(...)
function display({ name, ...rest })
Rest (...)
{ console.log(rest); }
Example:
let obj1 = { a: 1, b: 2 };
let obj2 = { ...obj1, c: 3 }; // Spread
console.log(obj2); // { a: 1, b: 2, c: 3 }
• The Fetch API is used to make HTTP requests to fetch resources from a server.
• It returns a Promise that resolves to a Response object.
Example:
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
• Use the method: "POST" and pass a body with JSON data.
Example:
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Hello", body: "World" })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
• Fetch does not reject for HTTP errors (like 404, 500).
• You must manually check response.ok.
Example:
fetch("https://jsonplaceholder.typicode.com/invalid-url")
.then(response => {
if (!response.ok) {
throw new Error("HTTP error: " + response.status);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error("Fetch error:", error));
2. Callback Hell
Q5: What is Callback Hell?
• Callback Hell happens when multiple nested callbacks make the code hard to read and
maintain.
Example of Callback Hell:
function step1(callback) {
setTimeout(() => {
console.log("Step 1");
callback();
}, 1000);
}
function step2(callback) {
setTimeout(() => {
console.log("Step 2");
callback();
}, 1000);
}
function step3() {
setTimeout(() => {
console.log("Step 3");
}, 1000);
}
3. Promises in JavaScript
Q7: What is a Promise in JavaScript?
myPromise
.then(result => console.log(result))
.catch(error => console.error(error));
Example:
function step1() {
return new Promise(resolve => {
setTimeout(() => {
console.log("Step 1");
resolve();
}, 1000);
});
}
function step2() {
return new Promise(resolve => {
setTimeout(() => {
console.log("Step 2");
resolve();
}, 1000);
});
}
function step3() {
return new Promise(resolve => {
setTimeout(() => {
console.log("Step 3");
resolve();
}, 1000);
});
}
// Chaining Promises
step1()
.then(step2)
.then(step3)
.catch(error => console.error("Error:", error));
• async and await are used to handle asynchronous operations in JavaScript in a more
readable way.
• async makes a function return a Promise.
• await pauses execution until the Promise is resolved.
Promises
Feature async/await
(.then()/.catch())
More readable, looks like synchronous
Readability More complex, chaining required
code
Error
Uses try...catch Uses .catch()
Handling
Syntax Synchronous-style Chained calls
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Q4: What happens if you don’t use await inside an async function?
• If await is not used, the function returns a Promise, but does not wait for resolution.