0% found this document useful (0 votes)
3 views

ChatGPT (1)

The document provides complex and advanced Core JavaScript questions and answers, covering topics such as the event loop, closures, the 'this' keyword, and Promises. It includes real code examples to illustrate concepts like async/await, the differences between null and undefined, and the use of keywords like yield, super, import, and export. The content aims to deepen understanding of JavaScript's asynchronous programming, scoping, and object-oriented features.

Uploaded by

kecadilo
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)
3 views

ChatGPT (1)

The document provides complex and advanced Core JavaScript questions and answers, covering topics such as the event loop, closures, the 'this' keyword, and Promises. It includes real code examples to illustrate concepts like async/await, the differences between null and undefined, and the use of keywords like yield, super, import, and export. The content aims to deepen understanding of JavaScript's asynchronous programming, scoping, and object-oriented features.

Uploaded by

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

ChatGPT

Complex and advance Core JavaScript questions and their


answers with real code examples.

Here are some complex and advanced Core JavaScript questions along with real code
examples and answers:

1. What is the event loop in JavaScript and how does it work?


The event loop is a fundamental concept in JavaScript's concurrency model. JavaScript is
single-threaded, which means it can execute only one operation at a time. However,
JavaScript uses the event loop to handle asynchronous code execution.

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 synchronous console.log('Start') and console.log('End') are executed first.

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.

2. What are closures in JavaScript and how do they work?


A closure is a function that retains access to its lexical scope (the environment in which it was
defined) even after the outer function has returned.

Example:

javascript

function outerFunction() {
let counter = 0;

return function innerFunction() {


counter++;
console.log(counter);
};
}

const counterFunc = outerFunction();


counterFunc(); // 1
counterFunc(); // 2
counterFunc(); // 3

Explanation:

innerFunction is a closure because it has access to counter (from outerFunction ),


even though outerFunction has already finished execution.

Every time counterFunc() is called, it increments and logs the counter , showing how
closures retain the state from the outer function.

3. What is the difference between null and undefined in JavaScript?


null is an assignment value. It's an object representing the intentional absence of any
object value.

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

console.log(a === b); // false

4. What is the this keyword in JavaScript and how does it work in


different contexts?
The value of this in JavaScript depends on how a function is called:

1. In Global Context: this refers to the global object ( window in browsers).

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

5. What is the difference between == and === in JavaScript?


== is the loose equality operator. It compares values for equality, but it performs type
coercion, meaning it converts the operands to the same type before comparison.

=== is the strict equality operator. It compares both the value and type without
performing type coercion.

Example:

javascript

console.log(5 == '5'); // true (type coercion)


console.log(5 === '5'); // false (different types)

let a = null;
let b;
console.log(a == b); // true
console.log(a === b); // false

6. What are Promises and how do they work in JavaScript?


A Promise is an object representing the eventual completion or failure of an asynchronous
operation. A promise can be in one of three states:

Pending: The initial state, neither fulfilled nor rejected.

Fulfilled: The operation completed successfully.

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!"
});

7. What are async and await in JavaScript?


async and await are used for handling asynchronous operations in a more readable way
than using Promises directly.

async is used to declare a function as asynchronous.

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

8. What is the difference between var , let , and const ?


var is function-scoped or globally-scoped and can be re-declared and updated.

let is block-scoped, can be updated but not re-declared in the same scope.

const is block-scoped and cannot be updated or re-declared. However, if the value is an


object, the properties of the object can still be modified.

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

9. What is the bind , call , and apply methods in JavaScript?


These are methods used to control the this keyword.

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

const person = { message: "Hello" };

greet.call(person, 'Alice'); // Hello, Alice


greet.apply(person, ['Bob']); // Hello, Bob

const greetBound = greet.bind(person);


greetBound('Charlie'); // Hello, Charlie

These questions explore advanced topics in JavaScript, including asynchronous


programming, scoping, object-oriented concepts, and handling the JavaScript environment
effectively.

Export to Google Doc Copy with formatting Select for Multi-select


Export to Google Doc Copy with formatting Select for Multi-select

What is yield and all those complex and unknown keywords


in JavaScript? Give questions and their answers with real
code examples.

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.

1. What is the yield keyword in JavaScript?

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

const generator = myGenerator();

console.log(generator.next()); // { value: 1, done: false }


console.log(generator.next()); // { value: 2, done: false }
console.log(generator.next()); // { value: 3, done: false }
console.log(generator.next()); // { value: undefined, done: true }

Explanation:

A generator function is defined with function* .

The yield pauses the function and returns the value.

next() is used to resume the generator function and obtain the next value.

2. What is the super keyword in JavaScript?


The super keyword is used in classes that are subclasses. It refers to the parent class and
can be used to call parent class methods or access parent class properties.

Example:

javascript

8/15
class Animal {
constructor(name) {
this.name = name;
}

speak() {
console.log(`${this.name} makes a sound.`);
}
}

class Dog extends Animal {


constructor(name, breed) {
super(name); // Calling the parent class constructor
this.breed = breed;
}

speak() {
super.speak(); // Calling the parent class method
console.log(`${this.name} barks.`);
}
}

const dog = new Dog('Buddy', 'Golden Retriever');


dog.speak();

Output:

css

Buddy makes a sound.


Buddy barks.

Explanation:

super(name) calls the constructor of the Animal class.

super.speak() calls the speak() method of the parent class Animal .

3. What is the import and export syntax in JavaScript?

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.

Example (exporting a function):

file1.js:

javascript

export function greet(name) {


return `Hello, ${name}!`;
}

file2.js:

javascript

import { greet } from './file1.js';

console.log(greet('Alice')); // Hello, Alice!

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.

4. What is the async and await keyword in JavaScript?


The async and await keywords are used to work with Promises in a more readable
manner. async is used to declare a function that returns a Promise, and await is used to
pause the execution of the code until the Promise resolves.

Example:

javascript

10/15
function fetchData() {
return new Promise(resolve => {
setTimeout(() => resolve("Data fetched!"), 1000);
});
}

async function getData() {


const data = await fetchData();
console.log(data); // "Data fetched!"
}

getData();

Explanation:

The function getData is declared async so it returns a promise.

await fetchData() pauses execution until the fetchData promise resolves.

5. What is the new keyword in JavaScript?


The new keyword is used to create an instance of an object from a constructor function or
a class. It also sets up the correct context ( this ) inside the constructor and returns the
object instance.

Example:

javascript

function Person(name, age) {


this.name = name;
this.age = age;
}

const person1 = new Person('Alice', 30);


console.log(person1); // Person { name: 'Alice', age: 30 }

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.

6. What is the with keyword in JavaScript?


The with keyword extends the scope chain for a block of code, allowing direct access to the
properties of an object without needing to reference the object itself. However, the use of
with is discouraged in modern JavaScript due to potential ambiguities.

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 .

7. What is the delete keyword in JavaScript?


The delete keyword is used to remove a property from an object. It can also be used to
delete elements from an array, but the array will still have the same length (it will leave a
hole ).

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.

8. What is the typeof operator in JavaScript?


The typeof operator is used to determine the data type of a given variable or value. It
returns a string indicating the type of the operand.

Example:

javascript

console.log(typeof 42); // number


console.log(typeof 'hello'); // string
console.log(typeof true); // boolean
console.log(typeof {}); // object
console.log(typeof null); // object (this is a known quirk)

Explanation:

typeof returns the type of a variable.

A known quirk is that typeof null returns "object" even though null is not an
object.

9. What is the instanceof operator in JavaScript?

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

const person1 = new Person('Alice');

console.log(person1 instanceof Person); // true


console.log(person1 instanceof Object); // true

Explanation:

person1 instanceof Person checks if person1 is an instance of the Person class.

10. What is the const keyword in JavaScript?


The const keyword is used to declare a variable that cannot be reassigned. However, if the
variable is an object or array, the contents (i.e., properties or elements) can still be modified.

Example:

javascript

const person = { name: 'Alice', age: 30 };


person.age = 31; // Valid: modifying an object
console.log(person); // { name: 'Alice', age: 31 }

person = {}; // Error: Assignment to constant variable

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.

Export to Google Doc Copy with formatting Select for Multi-select


Export to Google Doc Copy with formatting Select for Multi-select

15/15

You might also like