0% found this document useful (0 votes)
6 views16 pages

Javascript

basic java

Uploaded by

Akhila
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)
6 views16 pages

Javascript

basic java

Uploaded by

Akhila
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/ 16

Q1: What is a function in JavaScript?

A function is a reusable block of code designed to perform a speci c task.

function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice")); // Output: Hello, Alice

Q2: What are the different ways to de ne a function in JavaScript?

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;

Q3: What is the difference between function declaration and function


expression?

Feature Function Declaration Function Expression


Hoistin ✅ Yes (can be used before ❌ No (must be de ned
g declaration) rst)
Named? ✅ Yes ❌ Can be anonymous

console.log(sum(5, 5)); // ✅ Works due to hoisting

function sum(a, b) {
return a + b;
}
fi
fi
fi
fi
// ❌ Function Expression won't work before definition
console.log(product(5, 5)); // ❌ ReferenceError

const product = function(a, b) {


return a * b;
};

Q4: What is an Immediately Invoked Function Expression (IIFE)?

• A self-executing function that runs immediately after declaration.

(function() {
console.log("IIFE is executed!");
})();

Q5: What are default parameters in JavaScript functions?

• Default parameters allow assigning default values if no argument is provided.

function greet(name = "Guest") {


return "Hello, " + name;
}
console.log(greet()); // Output: Hello, Guest

2. Scope & Closures


Q6: What are the different types of scope in JavaScript?

1. Global Scope – Accessible from anywhere.


2. Local/Function Scope – Accessible only inside the function.
3. Block Scope (let & const) – Accessible only within {}.
4. Lexical Scope – Inner functions have access to variables of outer functions.

let globalVar = "I am global";

function testScope() {
let localVar = "I am local";
console.log(globalVar); // ✅ Accessible
}
console.log(localVar); // ❌ Error: Not accessible

Q7: What is closure in JavaScript?

• A closure is a function that remembers the scope in which it was created.


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

const counter = outer();


counter(); // Output: 1
counter(); // Output: 2

Q8: Why are closures useful?

Closures are used for:

• 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);
}
};
}

const myCounter = Counter();


myCounter.increment(); // 1
myCounter.increment(); // 2
myCounter.decrement(); // 1

Q9: What is lexical scope in JavaScript?

• Functions inherit scope from where they are de ned.


Example:
fi
function outer() {
let message = "Hello";
function inner() {
console.log(message); // ✅ Inherits message from
outer scope
}
inner();
}
outer();

3. Higher-Order Functions
What is a higher-order function?

• A higher-order function is a function that takes another function as an argument or


returns a function.

function operate(a, b, callback) {


return callback(a, b);
}

function sum(x, y) {
return x + y;
}

console.log(operate(5, 3, sum)); // Output: 8

Can a function return another function in JavaScript?

✅ Yes, functions can return functions.

function multiplyBy(factor) {
return function(num) {
return num * factor;
};
}

const double = multiplyBy(2);


console.log(double(5)); // Output: 10

What are some built-in higher-order functions in JavaScript?

• map() – Transforms elements in an array.


• filter() – Returns elements that meet a condition.
• reduce() – Accumulates values.

const numbers = [1, 2, 3, 4, 5];

// map() - Multiply each number by 2


const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

// filter() - Get even numbers


const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]

// reduce() - Sum of all numbers


const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15

What is the difference between map(), filter(), and forEach()?

Feature map() filter() forEach()


Return ✅ Returns a new ✅ Returns a new ❌ Returns
Value array array undefined
Purpose Transforms elements Filters elements Iterates over elements

const arr = [1, 2, 3, 4];

// 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

What is function composition?

• Function composition combines multiple functions.


Example:

const add2 = num => num + 2;


const multiply3 = num => num * 3;

const composedFunction = num => multiply3(add2(num));


console.log(composedFunction(5)); // (5+2) * 3 = 21

Q15: What is the call(), apply(), and bind() method in JavaScript?

Metho Description Example


d
call Invokes function with a given this value and func.call(thisArg, arg1,
() arguments separately. arg2)
appl Invokes function with this and arguments as an func.apply(thisArg,
y() array. [arg1, arg2])
bind Returns a new function with this bound to const newFunc =
() given object. func.bind(thisArg)

const obj = { name: "Alice" };

function greet(message) {
console.log(message + ", " + this.name);
}

greet.call(obj, "Hello"); // Hello, Alice


greet.apply(obj, ["Hi"]); // Hi, Alice

const newGreet = greet.bind(obj);


newGreet("Welcome"); // Welcome, Alice

JavaScript DOM (Document Object Model)


What is the DOM?

• The Document Object Model (DOM) represents an HTML document as a tree of


objects.

How to select elements in JavaScript?

Method Example
getElementById() document.getElementById("myId")
getElementsByClassNam document.getElementsByClassName("myCla
e() ss")
querySelector() document.querySelector(".myClass")
querySelectorAll() document.querySelectorAll("div")

let element = document.querySelector("#myId");


console.log(element.innerText);

How to change content in the DOM?

• innerText → Changes visible text.


• innerHTML → Changes HTML inside an element.
• textContent → Similar to innerText, but includes hidden elements.

document.getElementById("demo").innerText = "Hello!";
document.getElementById("demo").innerHTML = "<b>Bold Text</
b>";

How to modify attributes in JavaScript?

Method Description
Changes or adds an
setAttribute() attribute
getAttribute() Gets an attribute's value
removeAttribute(
Removes an attribute
)

let img = document.querySelector("img");


img.setAttribute("src", "new-image.jpg");
console.log(img.getAttribute("src"));
img.removeAttribute("alt");

What is an object in JavaScript?

• 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

How do you create objects in JavaScript?

• Using Object Literals (Most common)


• Using new Object()
• Using Constructor Functions
• Using ES6 Classes
Example:

// Object Literal
let car = { brand: "Toyota", model: "Camry" };

// Using `new Object()`


let obj = new Object();
obj.name = "Alice";

// 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");

How do you access and modify object properties?

• Dot Notation: obj.property


• Bracket Notation: obj["property"]
Example:

let person = { name: "John", age: 30 };

// Accessing
console.log(person.name); // John
console.log(person["age"]); // 30
// Modifying
person.age = 35;
person["name"] = "Alice";

How do you loop through an object’s properties?

• Using for...in
• Using Object.keys()
• Using Object.entries()
Example:

let user = { name: "Alice", age: 25 };

// 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));

What is object destructuring in JavaScript?

• Extracting properties from objects into variables.


Example:

let person = { name: "Alice", age: 25 };


const { name, age } = person;
console.log(name, age); // Alice 25

What is object spread/rest operator (...)?

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 }

function print({ name, ...rest }) {


console.log(rest);
}
print({ name: "Alice", age: 25, city: "NY" }); // { age: 25,
city: "NY" }

JavaScript Fetch API


Q1: What is the Fetch API in JavaScript?

• 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));

Q2: What are the differences between fetch() and XMLHttpRequest?

Feature fetch() XMLHttpRequest


API Type Modern Promise-based API Old callback-based API
Return Type Returns a Promise Uses event listeners
Error Only rejects on network Rejects on network + HTTP
Handling failure errors

Q3: How do you send a POST request using Fetch?

• 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));

Q4: How to handle errors in Fetch?

• 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);
}

// Nested Callbacks (Callback Hell)


step1(() => {
step2(() => {
step3();
});
});

Q6: How to avoid Callback Hell?

• Use Promises or Async/Await instead of deeply nested callbacks.

3. Promises in JavaScript
Q7: What is a Promise in JavaScript?

• A Promise represents a value that will be available in the future.


• It can be in one of three states:
◦ pending → Initial state.
◦ fulfilled → Operation completed successfully.
◦ rejected → Operation failed.
Example:

let myPromise = new Promise((resolve, reject) => {


let success = true;
setTimeout(() => {
if (success) resolve("Task Completed!");
else reject("Task Failed!");
}, 2000);
});

myPromise
.then(result => console.log(result))
.catch(error => console.error(error));

Q8: How to convert Callback Hell into Promises?

Instead of nested callbacks, chain .then() calls.

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));

What is async and await in JavaScript?

• 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.

async function fetchData() {


let response = await fetch("https://
jsonplaceholder.typicode.com/posts/1");
let data = await response.json();
console.log(data);
}
fetchData();

Q2: What is the difference between async/await and Promises?

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));

async function fetchPost() {


try {
let response = await fetch("https://
jsonplaceholder.typicode.com/posts/1");
let data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
fetchPost();

2. Using async and await


Q3: How do you declare an async function?

• An async function is declared using the async keyword before function.

async function myFunction() {


return "Hello World";
}
myFunction().then(console.log); // Output: Hello World

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.

async function getData() {


return fetch("https://jsonplaceholder.typicode.com/posts/
1");
}

console.log(getData()); // Output: Promise { <pending> }

Q5: How does await work with multiple asynchronous calls?

• It executes each await one after another.

async function fetchMultiple() {


let user = await fetch("https://
jsonplaceholder.typicode.com/users/1").then(res =>
res.json());
let posts = await fetch("https://
jsonplaceholder.typicode.com/posts?userId=1").then(res =>
res.json());
console.log(user, posts);
}
fetchMultiple();

3. Handling Errors in async/await


Q6: How do you handle errors in async/await?

• Use try...catch to handle errors.

async function fetchData() {


try {
let response = await fetch("invalid-url");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}
fetchData();

You might also like