ChatGPT (1)
ChatGPT (1)
Here are some complex and advanced Core JavaScript questions along with real code
examples and answers:
When you run an asynchronous operation (like a setTimeout , HTTP request, or Promise ),
the event loop puts the callback function in a queue. The event loop checks if the call stack is
empty, and if so, it pushes the callback from the queue to the call stack.
Example:
javascript
console.log('Start');
setTimeout(() => {
console.log('Inside setTimeout');
}, 0);
Promise.resolve().then(() => {
console.log('Inside Promise');
});
console.log('End');
Output:
javascript
Start
End
Inside Promise
Inside setTimeout
1/15
Explanation:
The setTimeout with 0ms delay is added to the queue but waits for the call stack to
clear before being executed.
The promise’s .then() is executed after the synchronous code but before the
setTimeout callback, because promises are processed before events in the event loop.
Example:
javascript
function outerFunction() {
let counter = 0;
Explanation:
Every time counterFunc() is called, it increments and logs the counter , showing how
closures retain the state from the outer function.
2/15
undefined is a type and value assigned by JavaScript to variables that have been
declared but not assigned a value.
Example:
javascript
let a;
console.log(a); // undefined
let b = null;
console.log(b); // null
2. In an Object Method: this refers to the object the method is called on.
3. In a Constructor Function: this refers to the instance of the object being created.
4. In Arrow Functions: Arrow functions do not have their own this ; they inherit it from
the surrounding context.
Example:
javascript
// Global Context
console.log(this); // window object (in browsers)
// Object Method
const person = {
name: 'Alice',
greet() {
console.log(this.name);
}
};
person.greet(); // Alice
3/15
// Constructor Function
function Person(name) {
this.name = name;
}
const personInstance = new Person('Bob');
console.log(personInstance.name); // Bob
// Arrow Function
const obj = {
name: 'Charlie',
greet: () => {
console.log(this.name);
}
};
obj.greet(); // undefined (because arrow function doesn't bind `this`)
=== is the strict equality operator. It compares both the value and type without
performing type coercion.
Example:
javascript
let a = null;
let b;
console.log(a == b); // true
console.log(a === b); // false
4/15
Rejected: The operation failed.
Example:
javascript
function fetchData() {
return new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Data fetched successfully!");
} else {
reject("Data fetching failed!");
}
});
}
fetchData()
.then((data) => {
console.log(data); // "Data fetched successfully!"
})
.catch((error) => {
console.error(error); // "Data fetching failed!"
});
await is used inside an async function to wait for a Promise to resolve or reject.
Example:
javascript
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Data fetched!"), 1000);
});
}
5/15
async function getData() {
const result = await fetchData();
console.log(result); // "Data fetched!"
}
getData();
let is block-scoped, can be updated but not re-declared in the same scope.
Example:
javascript
var x = 10;
if (true) {
var x = 20; // Same variable, re-declared
}
console.log(x); // 20
let y = 10;
if (true) {
let y = 20; // Block-scoped, different variable
}
console.log(y); // 10
const z = 10;
// z = 20; // Error: Assignment to constant variable
console.log(z); // 10
call() : Calls a function with a specified this value and arguments provided
individually.
6/15
apply() : Calls a function with a specified this value and arguments provided as an
array.
bind() : Returns a new function with a specified this value and optional arguments,
but it does not call the function immediately.
Example:
javascript
function greet(name) {
console.log(`${this.message}, ${name}`);
}
In JavaScript, there are several advanced and complex keywords that are important to
understand for mastering the language. Below are some of these keywords along with
detailed questions, answers, and real code examples to help you grasp their usage.
7/15
The yield keyword is used in generator functions. It allows a function to pause its
execution and return an intermediate result, which can be resumed later. When the
generator function is resumed, the state is preserved, and the next value is returned.
Generators are functions that can be paused and resumed, enabling you to control the
flow of asynchronous code in a synchronous-like manner.
Example:
javascript
function* myGenerator() {
yield 1;
yield 2;
yield 3;
}
Explanation:
next() is used to resume the generator function and obtain the next value.
Example:
javascript
8/15
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
speak() {
super.speak(); // Calling the parent class method
console.log(`${this.name} barks.`);
}
}
Output:
css
Explanation:
9/15
The import and export keywords are used in modules to allow JavaScript code to be
divided into separate files for better organization and reusability. export is used to make
parts of a module available for other files, and import is used to load those parts into
another module.
file1.js:
javascript
file2.js:
javascript
Explanation:
export makes the greet function available for import in other files.
import { greet } from './file1.js' allows the greet function to be used in the
current file.
Example:
javascript
10/15
function fetchData() {
return new Promise(resolve => {
setTimeout(() => resolve("Data fetched!"), 1000);
});
}
getData();
Explanation:
Example:
javascript
Explanation:
11/15
new Person() creates a new instance of Person , and it automatically calls the
constructor function Person .
this refers to the newly created object inside the constructor function.
Example:
javascript
const person = {
name: 'Alice',
age: 30
};
with (person) {
console.log(name); // Alice
console.log(age); // 30
}
Explanation:
The with keyword allows access to the properties of the person object directly without
needing to use person.name or person.age .
Example:
12/15
javascript
const person = {
name: 'Alice',
age: 30
};
delete person.age;
console.log(person); // { name: 'Alice' }
Explanation:
The delete keyword removes the age property from the person object.
Example:
javascript
Explanation:
A known quirk is that typeof null returns "object" even though null is not an
object.
13/15
The instanceof operator checks if an object is an instance of a particular class or
constructor function.
Example:
javascript
class Person {
constructor(name) {
this.name = name;
}
}
Explanation:
Example:
javascript
Explanation:
The object person itself cannot be reassigned, but its properties can be modified.
14/15
Conclusion
These keywords— yield , super , import , export , async , await , new , delete , typeof ,
instanceof , and const —are some of the more advanced concepts in JavaScript. They help
you manage data, control flow, and work with objects in sophisticated ways, allowing for
more flexible and efficient coding.
15/15