1. What is JavaScript?
JavaScript is a lightweight, interpreted programming language primarily used to create
interactive web pages. It is a core technology of the web, alongside HTML and CSS.
2. What are the different data types in JavaScript?
JavaScript has the following data types:
1. Primitive types:
○ String
○ Number
○ BigInt
○ Boolean
○ Undefined
○ Null
○ Symbol
2. Non-Primitive (Reference) types:
○ Objects (including Arrays, Functions, etc.)
3. What is the difference between null and undefined?
● null: Represents an intentional absence of value. It must be assigned.
● undefined: Represents a variable that has been declared but not assigned a value.
4. What are closures in JavaScript?
A closure is a function that has access to its own scope, the scope of the outer function, and the
global scope even after the outer function has executed.
Example:
javascript
Copy code
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
[Link](`Outer Variable: ${outerVariable}`);
[Link](`Inner Variable: ${innerVariable}`);
};
}
const newFunc = outerFunction("outside");
newFunc("inside");
5. What is the difference between var, let, and const?
1. var:
○ Function-scoped.
○ Can be redeclared and updated.
2. let:
○ Block-scoped.
○ Cannot be redeclared but can be updated.
3. const:
○ Block-scoped.
○ Cannot be redeclared or updated.
6. What is the difference between == and ===?
● ==: Compares values for equality after type coercion.
● ===: Compares values for equality without type coercion (strict equality).
Example:
javascript
Copy code
[Link](5 == '5'); // true (type coercion)
[Link](5 === '5'); // false (strict comparison)
7. What is event bubbling and capturing in JavaScript?
● Event Bubbling: The event is first captured and handled by the innermost element and
then propagated to outer elements.
● Event Capturing: The event is captured by the outermost element and propagated to
the innermost element.
8. What is the difference between call(), apply(), and bind()?
● call(): Invokes a function with a specified this value and arguments provided one by
one.
● apply(): Invokes a function with a specified this value and arguments provided as an
array.
● bind(): Returns a new function with a specified this value and arguments.
Example:
javascript
Copy code
const obj = { value: 10 };
function add(a, b) {
return [Link] + a + b;
}
[Link]([Link](obj, 5, 5)); // 20
[Link]([Link](obj, [5, 5])); // 20
const boundAdd = [Link](obj);
[Link](boundAdd(5, 5)); // 20
9. What is the use of Promise in JavaScript?
A Promise represents the result of an asynchronous operation. It can be in one of three states:
● Pending
● Fulfilled
● Rejected
Example:
javascript
Copy code
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Success"), 1000);
});
[Link]((value) => [Link](value)).catch((err) =>
[Link](err));
10. What are JavaScript arrow functions?
Arrow functions are a shorter syntax for writing functions. They do not have their own this
context.
Example:
javascript
Copy code
const add = (a, b) => a + b;
[Link](add(5, 3)); // 8
11. What is the difference between synchronous and asynchronous
programming?
● Synchronous: Code executes line-by-line, and each operation must complete before
the next begins.
● Asynchronous: Code does not wait for an operation to complete and moves on to the
next.
12. What is the this keyword?
The this keyword refers to the object it belongs to, depending on the context in which it is
called.
Example:
javascript
Copy code
const obj = {
value: 10,
getValue() {
return [Link];
}
};
[Link]([Link]()); // 10
13. What are JavaScript promises?
Promises are a way to handle asynchronous operations in JavaScript by chaining .then() and
.catch() methods.
14. What is the difference between map(), filter(), and reduce()?
● map(): Transforms each element of an array and returns a new array.
● filter(): Filters elements of an array based on a condition and returns a new array.
● reduce(): Reduces the array to a single value using a callback function.
Example:
javascript
Copy code
const numbers = [1, 2, 3, 4];
[Link]([Link](x => x * 2)); // [2, 4, 6, 8]
[Link]([Link](x => x % 2 === 0)); // [2, 4]
[Link]([Link]((sum, x) => sum + x, 0)); // 10
15. What are JavaScript modules?
Modules allow you to break your code into reusable pieces.
Example:
javascript
Copy code
// [Link]
export const greet = () => [Link]("Hello");
// [Link]
import { greet } from './[Link]';
greet(); // Hello
16. Explain async and await.
async and await allow you to write asynchronous code that looks synchronous. They work
with Promises.
Example:
javascript
Copy code
const fetchData = async () => {
try {
const data = await fetch("[Link]
[Link](data);
} catch (error) {
[Link](error);
}
};
fetchData();
17. What is the difference between forEach() and map()?
● forEach(): Iterates over an array but does not return a new array.
● map(): Iterates over an array and returns a new array based on the transformation.
Understanding async and await in JavaScript
async and await are modern JavaScript features introduced in ES2017 (ES8) that simplify
working with asynchronous code. They allow you to write asynchronous code in a way that
looks and behaves like synchronous code, making it easier to read and debug.
What is async?
The async keyword is used to declare a function as asynchronous. When a function is marked
as async:
1. It automatically returns a Promise.
2. The value returned by the function is wrapped in a Promise.
Example:
javascript
Copy code
async function greet() {
return "Hello, World!";
}
greet().then((message) => [Link](message)); // Output: Hello,
World!
Here, greet() returns a Promise that resolves to "Hello, World!".
What is await?
The await keyword can only be used inside async functions. It pauses the execution of the
async function until the Promise it is awaiting resolves or rejects:
● If the Promise resolves, await returns the resolved value.
● If the Promise rejects, await throws the error.
Example:
javascript
Copy code
async function fetchData() {
const response = await
fetch("[Link]
const data = await [Link]();
[Link](data);
}
fetchData();
In this example:
1. fetch("...") returns a Promise.
2. The await keyword pauses execution until the Promise resolves.
3. Once resolved, the result is stored in response.
Key Features of async/await
Error Handling: Errors in async/await can be handled using try...catch.
javascript
Copy code
async function fetchData() {
try {
const response = await fetch("[Link]
const data = await [Link]();
[Link](data);
} catch (error) {
[Link]("Error fetching data:", error);
}
}
fetchData();
1.
Sequential Execution: await ensures that asynchronous operations occur sequentially.
javascript
Copy code
async function sequentialExecution() {
const first = await [Link](1);
[Link](first); // 1
const second = await [Link](2);
[Link](second); // 2
}
sequentialExecution();
2.
Parallel Execution: If operations can run in parallel, use [Link] for better performance.
javascript
Copy code
async function parallelExecution() {
const [first, second] = await [Link]([
[Link](1),
[Link](2),
]);
[Link](first, second); // 1 2
}
parallelExecution();
3.
Benefits of Using async/await
● Improved Readability: Simplifies complex Promise chains (.then()/.catch()).
● Error Handling: Easily manage errors with try...catch.
● Debugging: Debugging is easier since the code looks synchronous.
Common Use Cases
Fetching data from APIs:
javascript
Copy code
async function getUser() {
const response = await fetch("[Link]
const user = await [Link]();
[Link](user);
}
1.
Waiting for multiple asynchronous tasks:
javascript
Copy code
async function getData() {
const [posts, comments] = await [Link]([
fetch("[Link]
fetch("[Link]
]);
[Link](await [Link](), await [Link]());
}
2.
By using async and await, asynchronous code becomes more intuitive and less error-prone. It
eliminates the "callback hell" that arises from deeply nested callbacks, providing a cleaner and
more maintainable structure.
Promises in JavaScript: Examples and Explanation
A Promise in JavaScript represents the eventual completion or failure of an asynchronous
operation. It allows you to handle asynchronous tasks such as fetching data, interacting with
APIs, or performing file operations without getting into callback hell.
Basic Syntax of a Promise
javascript
Copy code
const promise = new Promise((resolve, reject) => {
// Perform some asynchronous task
if (/* task succeeds */) {
resolve("Task succeeded!");
} else {
reject("Task failed!");
});
● resolve: Called when the operation succeeds.
● reject: Called when the operation fails.
You handle the result using .then() for success and .catch() for failure.
Examples of Promises
1. Creating and Using a Promise
javascript
Copy code
const fetchData = new Promise((resolve, reject) => {
const success = true; // Simulate success or failure
if (success) {
resolve("Data fetched successfully!");
} else {
reject("Failed to fetch data.");
});
fetchData
.then((message) => {
[Link](message); // Output: "Data fetched successfully!"
})
.catch((error) => {
[Link](error); // If failed: "Failed to fetch data."
});
2. Simulating an Asynchronous Task
javascript
Copy code
const delayedTask = (time) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(`Task completed after ${time} ms`);
}, time);
});
};
delayedTask(2000).then((message) => [Link](message));
// Output after 2 seconds: "Task completed after 2000 ms"
3. Chaining Promises
You can chain multiple .then() calls to execute tasks sequentially.
javascript
Copy code
const step1 = () => [Link]("Step 1 completed");
const step2 = () => [Link]("Step 2 completed");
const step3 = () => [Link]("Step 3 completed");
step1()
.then((message) => {
[Link](message);
return step2();
})
.then((message) => {
[Link](message);
return step3();
})
.then((message) => {
[Link](message);
})
.catch((error) => {
[Link](error);
});
Output:
vbnet
Copy code
Step 1 completed
Step 2 completed
Step 3 completed
4. Handling Errors with .catch()
javascript
Copy code
const fetchData = new Promise((resolve, reject) => {
const success = false; // Simulate failure
if (success) {
resolve("Data fetched successfully!");
} else {
reject("Error: Unable to fetch data.");
});
fetchData
.then((message) => [Link](message))
.catch((error) => [Link](error));
// Output: "Error: Unable to fetch data."
5. Using [Link] for Concurrent Promises
[Link] runs multiple promises in parallel and resolves when all promises are resolved.
It rejects if any one of the promises fails.
javascript
Copy code
const promise1 = [Link]("Promise 1 resolved");
const promise2 = [Link]("Promise 2 resolved");
const promise3 = [Link]("Promise 3 resolved");
[Link]([promise1, promise2, promise3])
.then((messages) => {
[Link](messages); // Output: ["Promise 1 resolved", "Promise
2 resolved", "Promise 3 resolved"]
})
.catch((error) => {
[Link](error);
});
6. Using [Link]
[Link] resolves or rejects as soon as the first promise resolves or rejects.
javascript
Copy code
const promise1 = new Promise((resolve) => setTimeout(resolve, 100,
"First"));
const promise2 = new Promise((resolve) => setTimeout(resolve, 200,
"Second"));
[Link]([promise1, promise2])
.then((message) => {
[Link](message); // Output: "First"
});
7. Nested Promises
javascript
Copy code
const fetchData = () => {
return new Promise((resolve) => {
setTimeout(() => resolve("Data fetched"), 1000);
});
};
const processData = (data) => {
return new Promise((resolve) => {
setTimeout(() => resolve(`${data} processed`), 1000);
});
};
fetchData()
.then((data) => {
[Link](data); // "Data fetched"
return processData(data);
})
.then((processedData) => {
[Link](processedData); // "Data fetched processed"
});
Benefits of Promises
1. Avoids deeply nested callbacks (callback hell).
2. Easier error handling using .catch().
3. Enables better composition with [Link] and [Link].
Common Use Cases
Fetching data from APIs:
javascript
Copy code
fetch("[Link]
.then((response) => [Link]())
.then((data) => [Link](data))
.catch((error) => [Link](error));
●
● File reading and writing operations.
● Performing background tasks like image processing.
Promises make asynchronous JavaScript code more manageable and readable, laying the
foundation for modern techniques like async/await.