JavaScript Flashcards

1
Q

What is ternary operator in JavaScript?

A

The ternary operator is a conditional operator that takes three operands. It is frequently used as a shortcut for the if statement.

console.log(condition ? true : false);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is callback hell in JavaScript?

A

Callback hell, often referred to as Pyramid of Doom, describes a situation in JavaScript where multiple nested callbacks become difficult to manage, leading to unreadable and unmaintainable code. It often arises when performing multiple asynchronous operations that depend on the completion of previous operations. The code starts to take on a pyramidal shape due to the nesting.

Example of callback hell

callAsync1(function () {
  callAsync2(function () {
    callAsync3(function () {
      callAsync4(function () {
        callAsync5(function () {
          // ...
        });
      });
    });
  });
});

Strategies to avoid callback hell
Developers can address or avoid callback hell by using strategies like modularizing the code into named functions, using asynchronous control flow libraries, or leveraging modern JavaScript features like Promises and async/await to write more linear, readable asynchronous code.

Promise chaining

callAsync1()
  .then(() => callAsync2())
  .then(() => callAsync3())
  .then(() => callAsync4())
  .then(() => callAsync5())
  .catch((err) => console.error(err));

Async/await

async function asyncCall() {
  try {
    await callAsync1();
    await callAsync2();
    await callAsync3();
    await callAsync4();
    await callAsync5();
  } catch (err) {
    console.error(err);
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the difference between Map and WeakMap in JavaScript?

A

The Map object holds key-value pairs and remembers the original insertion order of the keys. Whereas, the WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. You can use any data type as a key or value in a Map whereas in WeakMap you can only use objects as keys. The WeakMap is not iterable whereas Map is. In WeakMap it holds the weak reference to the original object which means if there are no other references to an object stored in the WeakMap, those objects can be garbage collected.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Switch case statement in JavaScript?

A

The switch statement evaluates an expression, matching the expression’s value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.

const fruit = 'Papayas';

switch (fruit) {
  case 'Oranges':
    console.log('Oranges are $0.59 a pound.');
    break;
  case 'Mangoes':
  case 'Papayas':
    console.log('Mangoes and papayas are $2.79 a pound.');
    break;
  default:
    console.log(`Sorry, we are out of ${fruit}.`);
}

// Mangoes and papayas are $2.79 a pound.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to debug JavaScript code?

A

Debugging JavaScript code can be achieved through various methods and tools. Here’s a basic guide:

Console Logging:
You can use console.log(), console.warn(), console.error(), etc., to print values, variables, or messages to the browser’s developer console.
console.log('Value of x:', x);

Browser Developer Tools:
Most modern browsers come equipped with developer tools. You can access these tools by pressing F12 or right-clicking on the web page and selecting Inspect or Inspect Element.

Sources Tab: Allows you to see the loaded scripts, set breakpoints, and step through the code.
Console Tab: Displays console outputs and allows for interactive JavaScript execution.
Network Tab: Helps in checking network requests and responses.

Setting Breakpoints:
In the Sources tab of the browser’s developer tools, you can click on a line number to set a breakpoint. The code execution will pause at this line, allowing you to inspect variables, the call stack, and continue step-by-step.

Debugger Statement:
Inserting the debugger; statement in your code will act as a breakpoint when the browser developer tools are open. Execution will pause at the debugger; line.

function myFunction() {
  debugger; // Execution will pause here when dev tools are open
  // ... rest of the code
}

Call Stack and Scope:
In the developer tools, when paused on a breakpoint or debugger; statement, you can inspect the call stack to see the sequence of function calls. The Scope panel will show you the values of local and global variables.

Remember, debugging is an iterative process. It often involves setting breakpoints, checking variables, adjusting code, and re-running to ensure correctness.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is Inheritance in JavaScript?

A

Inheritance is a way to create a new Class from an existing Class. The new Class inherits all the properties and methods from the existing Class. The new Class is called the child Class, and the existing Class is called the parent Class.

Example

class Roadmap {
  constructor(name, description, slug) {
    this.name = name;
    this.description = description;
    this.slug = slug;
  }

  getRoadmapUrl() {
    console.log(`https://roadmap.sh/${this.slug}`);
  }
}

class JavaScript extends Roadmap {
  constructor(name, description, slug) {
    super(name, description, slug);
  }

  greet() {
    console.log(`${this.name} - ${this.description}`);
  }
}

const js = new JavaScript(
  'JavaScript Roadmap',
  'Learn JavaScript',
  'javascript'
);

js.getRoadmapUrl(); // https://roadmap.sh/javascript
js.greet(); // JavaScript Roadmap - Learn JavaScript

In the above example, the JavaScript class inherits the getRoadmapUrl() method from the Roadmap class. This is because the JavaScript class extends the Roadmap class using the extends keyword. In the JavaScript class, the getRoadmapUrl() method is not found, so JavaScript looks up the prototype chain and finds the getRoadmapUrl() method in the Roadmap class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to implement your own Custom Event in JavaScript?

A

You can use the CustomEvent constructor to create a custom event. The CustomEvent constructor accepts two arguments: the event name and an optional object that specifies the event options. And you can use the dispatchEvent method to dispatch the custom event on the target element/document.

Creating Custom Events

const event = new CustomEvent('roadmap-updated', {
  detail: { name: 'JavaScript' },
});
element.dispatchEvent(event);

Listening for Custom Events
You can listen for custom events using the addEventListener method. The addEventListener method accepts the event name and a callback function that is called when the event is dispatched.

element.addEventListener('roadmap-updated', (event) => {
  console.log(event.detail); // { name: 'JavaScript' }
});

Removing Event Listeners
You can remove event listeners using the removeEventListener method. The removeEventListener method accepts the event name and the callback function that was used to add the event listener.

function handleEvent(event) {
  console.log(event.detail); // { name: 'JavaScript' }
}
element.addEventListener('roadmap-updated', handleEvent);
element.removeEventListener('roadmap-updated', handleEvent);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Explain alert(), prompt(), and confirm() methods in JavaScript?

A

Let’s see how we can use the alert, prompt and confirm functions to interact with the user.

alert()
The alert() method displays an alert box with a specified message and an OK button.
alert(‘Hello World!’);

prompt()
The prompt() method displays a dialog box that prompts the visitor for input. A prompt box is often used if you want the user to input a value before entering a page. The prompt() method returns the input value if the user clicks OK. If the user clicks Cancel, the method returns null.

const name = prompt('What is your name?');
console.log(name);

confirm()
The confirm() method displays a dialog box with a specified message, along with an OK and a Cancel button. This is often used to confirm or verify something from the user.

const result = confirm('Are you sure?');
console.log(result); // true/false
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is JavaScript?

A

JavaScript (often abbreviated as JS) is a high-level, versatile, and widely-used programming language primarily known for its role in web development. It enables interactive and dynamic behavior on websites.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the difference between var, let, and const in JavaScript?

A

In JavaScript, var is function-scoped and was traditionally used to declare variables. let and const are block-scoped. The key difference between let and const is that let allows for reassignment while const creates a read-only reference.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is Map in JavaScript?

A

Map is another data structure in JavaScript which is similar to Object but the key can be of any type. It is a collection of elements where each element is stored as a Key, value pair. It is also known as a Hash table or a dictionary.

The key can be of any type but the value can be of any type. The key is unique and immutable, whereas the value can be mutable or immutable.

const roadmap = new Map();
roadmap.set(‘name’, ‘JavaScript’);
roadmap.set(‘type’, ‘dynamic’);
roadmap.set(‘year’, 1995);

console.log(roadmap.get(‘name’)); // JavaScript

roadmap.delete(‘year’);
console.log(roadmap.has(‘year’)); // false
console.log(roadmap.size); // 2

roadmap.clear();
console.log(roadmap.size); // 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How you can find unique values in an array?

A

There are serveral ways to find unique values in an array. Here are some of them:

Using Set

const roadmaps = ['JavaScript', 'React', 'Node.js', 'Node.js', 'JavaScript'];
const uniqueRoadmaps = [...new Set(roadmaps)];
console.log(uniqueRoadmaps); // ['JavaScript', 'React', 'Node.js']

Using filter()

const roadmaps = ['JavaScript', 'React', 'Node.js', 'Node.js', 'JavaScript'];
const uniqueRoadmaps = roadmaps.filter(
  (roadmap, index) => roadmaps.indexOf(roadmap) === index
);
console.log(uniqueRoadmaps); // ['JavaScript', 'React', 'Node.js']

Using reduce()

const roadmaps = ['JavaScript', 'React', 'Node.js', 'Node.js', 'JavaScript'];
const uniqueRoadmaps = roadmaps.reduce((unique, roadmap) => {
  return unique.includes(roadmap) ? unique : [...unique, roadmap];
}, []);
console.log(uniqueRoadmaps); // ['JavaScript', 'React', 'Node.js']

Using forEach()

const roadmaps = ['JavaScript', 'React', 'Node.js', 'Node.js', 'JavaScript'];
const uniqueRoadmaps = [];
roadmaps.forEach((roadmap) => {
  if (!uniqueRoadmaps.includes(roadmap)) {
    uniqueRoadmaps.push(roadmap);
  }
});
console.log(uniqueRoadmaps); // ['JavaScript', 'React', 'Node.js']

Using for…of

const roadmaps = ['JavaScript', 'React', 'Node.js', 'Node.js', 'JavaScript'];
const uniqueRoadmaps = [];
for (const roadmap of roadmaps) {
  if (!uniqueRoadmaps.includes(roadmap)) {
    uniqueRoadmaps.push(roadmap);
  }
}
console.log(uniqueRoadmaps); // ['JavaScript', 'React', 'Node.js']
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the difference between null and undefined?

A

The null is an assignment value. It can be assigned to a variable as a representation of no value. But the undefined is a primitive value that represents the absence of a value, or a variable that has not been assigned a value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the purpose of the async/await in JavaScript?

A

The async/await, introduced in ES2017, provides a more readable and cleaner way to handle asynchronous operations compared to callbacks and promises. An async function always returns a promise, and within such a function, you can use await to pause execution until a promise settles.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the spread operator in JavaScript?

A

The spread operator in JavaScript is represented by three dots (…). It allows the elements of an array or properties of an object to be expanded or “spread” into individual elements or properties. This can be useful in various contexts, such as when passing elements as function arguments, cloning arrays and objects, or merging arrays and objects.

const roadmaps = [‘JavaScript’, ‘React’, ‘Node.js’];
const bestPractices = [‘AWS’, ‘API Security’];

const resources = […roadmaps, …bestPractices];
console.log(resources); // [‘JavaScript’, ‘React’, ‘Node.js’, ‘AWS’, ‘API Security’]
const roadmap = {
name: ‘JavaScript’,
type: ‘dynamic’,
};

const roadmapClone = { …roadmap }; // shallow copy
console.log(roadmapClone); // { name: ‘JavaScript’, type: ‘dynamic’ }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is Type Casting?

A

Type conversion (or typecasting) means transfer of data from one data type to another. Implicit conversion happens when the compiler (for compiled languages) or runtime (for script languages like JavaScript) automatically converts data types.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How to use reduce() method?

A

You can use the reduce() method to reduce an array to a single value. The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

Syntax
array.reduce((accumulator, currentValue) => {
// …
}, initialValue);
Example
You can use the reduce() method to sum all the numbers in an array.

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

const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);

console.log(numbers); // [1, 2, 3, 4, 5, 6]
console.log(sum); // 21

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is Set in JavaScript?

A

Set is another data structure in JavaScript which is similar to Array but the values are unique. It is a collection of elements where each element is stored as a value without any keys.

const roadmap = new Set();
roadmap.add(‘JavaScript’);
roadmap.add(‘JavaScript’);

roadmap.add(‘dynamic’);
roadmap.add(1995);

console.log(roadmap.size); // 3, because the value ‘JavaScript’ is already present in the set
console.log(roadmap.has(‘JavaScript’)); // true

roadmap.delete(‘JavaScript’);
console.log(roadmap.has(‘JavaScript’)); // false
console.log(roadmap.size); // 2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Difference between Promise.all() and Promise.allSettled()?

A

The core difference between Promise.all() and Promise.allSettled() is that Promise.all() rejects immediately if any of the promises reject whereas Promise.allSettled() waits for all of the promises to settle (either resolve or reject) and then returns the result.

Initialize
const promise1 = Promise.resolve(‘Promise 1 resolved’);
const promise2 = Promise.reject(‘Promise 2 rejected’);
Using Promise.all()
Promise.all([promise1, promise2])
.then((values) => {
console.log(values);
})
.catch((error) => {
console.log(‘An error occurred in Promise.all():’, error);
});

// Output:
// An error occurred in Promise.all(): Promise 2 rejected
In the above code, the Promise.all() rejects immediately when any of the promise2 rejects.

Using Promise.allSettled()
Promise.allSettled([promise1, promise2]).then((results) => {
results.forEach((result, index) => {
if (result.status === ‘fulfilled’) {
console.log(
Promise ${index + 1} was fulfilled with value:,
result.value
);
} else {
console.log(
Promise ${index + 1} was rejected with reason:,
result.reason
);
}
});
});

// Output:
// Promise 1 was fulfilled with value: Promise 1 resolved
// Promise 2 was rejected with reason: Promise 2 rejected
In the above code, the Promise.allSettled() waits for all of the promises to settle (either resolve or reject) and then returns the result.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Difference between Promise.all() and Promise.allSettled()?

A

The core difference between Promise.all() and Promise.allSettled() is that Promise.all() rejects immediately if any of the promises reject whereas Promise.allSettled() waits for all of the promises to settle (either resolve or reject) and then returns the result.

Initialize
const promise1 = Promise.resolve(‘Promise 1 resolved’);
const promise2 = Promise.reject(‘Promise 2 rejected’);
Using Promise.all()
Promise.all([promise1, promise2])
.then((values) => {
console.log(values);
})
.catch((error) => {
console.log(‘An error occurred in Promise.all():’, error);
});

// Output:
// An error occurred in Promise.all(): Promise 2 rejected
In the above code, the Promise.all() rejects immediately when any of the promise2 rejects.

Using Promise.allSettled()
Promise.allSettled([promise1, promise2]).then((results) => {
results.forEach((result, index) => {
if (result.status === ‘fulfilled’) {
console.log(
Promise ${index + 1} was fulfilled with value:,
result.value
);
} else {
console.log(
Promise ${index + 1} was rejected with reason:,
result.reason
);
}
});
});

// Output:
// Promise 1 was fulfilled with value: Promise 1 resolved
// Promise 2 was rejected with reason: Promise 2 rejected
In the above code, the Promise.allSettled() waits for all of the promises to settle (either resolve or reject) and then returns the result.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is a JavaScript promise?

A

A Promise in JavaScript represents a value that may not be available yet but will be at some point. Promises provide a way to handle asynchronous operations, offering methods like .then() and .catch() to register callbacks for success and failure.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How to use filter() method?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What are Heap and Stack in JavaScript?

A

The Heap and Stack in JavaScript Engine are two different data structures that store data in different ways.

Stack
The Stack is a small, organized region of memory. It is where primitive values, function calls, and local variables are stored. It follows a “Last In, First Out” (LIFO) order, meaning that the last item added to the stack is the first one to be removed. Each function invocation creates a new stack frame, which contains the function’s local variables, return address, and other contextual data.

Heap
The Heap is a large, mostly unstructured region of memory. It is where objects, arrays, and functions are stored. Variables from the Stack (e.g., in functions) point to locations in the Heap for these dynamically allocated structures.

When you declare a primitive type (like a number or boolean), it’s usually managed in the stack. But when you create an object, array, or function, it’s stored in the heap, and the stack will hold a reference to that location in the heap.

For example:

const name = ‘JavaScript’; // Stored on the stack
const roadmap = { name: ‘JS’ }; // roadmap reference on the stack, actual object { name: ‘JS’ } in the heap
In the code above, the primitive value JavaScript for variable name is directly stored on the stack. For the object assigned to roadmap, its actual data resides in the heap, and the reference to this data (a memory address pointer) is held on the stack.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What are Heap and Stack in JavaScript?

A

The Heap and Stack in JavaScript Engine are two different data structures that store data in different ways.

Stack
The Stack is a small, organized region of memory. It is where primitive values, function calls, and local variables are stored. It follows a “Last In, First Out” (LIFO) order, meaning that the last item added to the stack is the first one to be removed. Each function invocation creates a new stack frame, which contains the function’s local variables, return address, and other contextual data.

Heap
The Heap is a large, mostly unstructured region of memory. It is where objects, arrays, and functions are stored. Variables from the Stack (e.g., in functions) point to locations in the Heap for these dynamically allocated structures.

When you declare a primitive type (like a number or boolean), it’s usually managed in the stack. But when you create an object, array, or function, it’s stored in the heap, and the stack will hold a reference to that location in the heap.

For example:

const name = ‘JavaScript’; // Stored on the stack
const roadmap = { name: ‘JS’ }; // roadmap reference on the stack, actual object { name: ‘JS’ } in the heap
In the code above, the primitive value JavaScript for variable name is directly stored on the stack. For the object assigned to roadmap, its actual data resides in the heap, and the reference to this data (a memory address pointer) is held on the stack.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is Prototype Chain in JavaScript?

A

The prototype chain in JavaScript refers to the chain of objects linked by their prototypes. When a property or method is accessed on an object, JavaScript first checks the object itself. If it doesn’t find it there, it looks up the property or method in the object’s prototype. This process continues, moving up the chain from one prototype to the next, until the property or method is found or the end of the chain is reached (typically the prototype of the base object, which is null). The prototype chain is fundamental to JavaScript’s prototypal inheritance model, allowing objects to inherit properties and methods from other objects.

Example
const roadmap = {
getRoadmapUrl() {
console.log(https://roadmap.sh/${this.slug});
},
};

const javascript = {
name: ‘JavaScript Roadmap’,
description: ‘Learn JavaScript’,
slug: ‘javascript’,
greet() {
console.log(${this.name} - ${this.description});
},
};

Object.setPrototypeOf(javascript, roadmap); // or javascript.__proto__ = roadmap;

javascript.getRoadmapUrl(); // https://roadmap.sh/javascript
javascript.greet(); // JavaScript Roadmap - Learn JavaScript
In the above example, the javascript object inherits the getRoadmapUrl() method from the roadmap object. This is because the javascript object’s prototype is set to the roadmap object using the Object.setPrototypeOf() method. In the javascript object, the getRoadmapUrl() method is not found, so JavaScript looks up the prototype chain and finds the getRoadmapUrl() method in the roadmap object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

How to run a piece of code only once after a specific time?

A

To run a piece of code after a certain time, you can use setTimeout function in JavaScript. It accepts a function and a time interval in milliseconds. It returns a unique id which you can use to clear the timeout using clearTimeout function.

const timeoutId = setTimeout(() => {
console.log(‘Hello World’);
}, 1000);

// Output:
// Hello World
In the above code, the setTimeout function runs the callback function after 1000 milliseconds (1 second) and prints Hello World to the console. It returns a unique id which you can use to clear the timeout using clearTimeout function.

clearTimeout(timeoutId);

27
Q

What is Nullish Coalescing Operator?

A

The Nullish Coalescing Operator (??) returns the right operand if the left one is null or undefined, otherwise, it returns the left operand. It’s useful for setting default values without considering falsy values like 0 or ‘’ as absent.

console.log(null ?? ‘hello’); // hello
console.log(undefined ?? ‘hello’); // hello
console.log(‘’ ?? ‘hello’); // ‘’
console.log(0 ?? ‘hello’); // 0

28
Q

Is JavaScript a compiled or interpreted language?

A

JavaScript is an interpreted language. This means that the JavaScript code is not compiled before it is executed. Instead, the JavaScript engine interprets the code at runtime.

29
Q

How to accept variable number of arguments in a JavaScript function?

A

In JavaScript, you can accept a variable number of arguments in a function using the arguments object or the rest parameter (…).

Using the arguments object:
The arguments is an array-like object that holds all of the passed arguments. They are only available inside the function body.

function displayArgs() {
for (let i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
displayArgs(1, 2, 3, 4); // Outputs: 1, 2, 3, 4
Using the rest parameter:
The rest parameter allows you to represent an indefinite number of arguments as an array.

function displayArgs(…args) {
args.forEach((arg) => console.log(arg));
}
displayArgs(1, 2, 3, 4); // Outputs: 1, 2, 3, 4
The rest parameter (…args in the example) is generally more modern and flexible, and it provides an actual array, unlike the array-like arguments object.

30
Q

How to run a piece of code after a specific time interval?

A

ou can run some codes on interval using setInterval function in JavaScript. It accepts a function and a time interval in milliseconds. It returns a unique id which you can use to clear the interval using clearInterval function.

const intervalId = setInterval(() => {
console.log(‘Hello World’);
}, 1000);

// Output:
// Hello World
// Hello World
In the above code, the setInterval function runs the callback function every 1000 milliseconds (1 second) and prints Hello World to the console. It returns a unique id which you can use to clear the interval using clearInterval function.

clearInterval(intervalId);

31
Q

How to use finally block in Promise?

A

The finally block will be executed when the promise is resolved or rejected.

promise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error.message);
})
.finally(() => {
console.log(‘Finally Promise has settled’);
});

32
Q

What are Labelled Statements in JavaScript?

A

JavaScript label statements are used to prefix a label to an identifier. It can be used with break and continue statement to control the flow more precisely.

loop1: for (let i = 0; i < 5; i++) {
if (i === 1) {
continue loop1; // skips the rest of the code in the loop1
}
console.log(i: ${i});
}
// Output:
// i: 0
// i: 2
// i: 3
// i: 4

33
Q

What is Event Loop in JavaScript?

A

The Event loop is one the most important aspect to understand in JavaScript. It is the mechanism that allows JavaScript to perform non-blocking operations. It is the reason why we can use asynchronous code in JavaScript. The Event loop is a loop that constantly checks if there are any tasks that need to be executed. If there are, it will execute them. If there are no tasks to execute, it will wait for new tasks to arrive.

34
Q

What is the difference between map() and forEach() methods?

A

The map() method creates a new array with the results of calling a provided function on every element in the calling array. Whereas, the forEach() method executes a provided function once for each array element.

35
Q

What is the difference between == and ===?

A

The == equality operator converts the operands if they are not of the same type, then applies strict comparison. The === strict equality operator only considers values equal that have the same type.

console.log(1 == ‘1’); // true
console.log(1 === ‘1’); // false
console.log(1 === 1); // true

36
Q

What are the Logical Operators in JavaScript?

A

There are four logical operators in JavaScript: || (OR), && (AND), ! (NOT), and ?? (Nullish Coalescing). They can be used with boolean values, or with non-boolean values.

OR (||)
The OR operator (||) returns the first truthy value, or the last value if none are truthy.

console.log(‘hello’ || 0); // hello
console.log(false || ‘hello’); // hello
console.log(‘hello’ || ‘world’); // hello
AND (&&)
The AND operator (&&) aka logical conjunction returns the first falsy value, or the last value if none are falsy.

console.log(‘hello’ && 0); // 0
console.log(false && ‘hello’); // false
console.log(‘hello’ && ‘world’); // world
NOT (!)
It simply inverts the boolean value of its operand.

console.log(!true); // false
console.log(!false); // true
console.log(!’hello’); // false
console.log(!0); // true
Nullish Coalescing (??)
The Nullish Coalescing Operator (??) returns the right operand if the left one is null or undefined, otherwise, it returns the left operand. It’s useful for setting default values without considering falsy values like 0 or ‘’ as absent.

console.log(null ?? ‘hello’); // hello
console.log(undefined ?? ‘hello’); // hello
console.log(‘’ ?? ‘hello’); // ‘’
console.log(0 ?? ‘hello’); // 0

37
Q

Garbage collection in JavaScript?

A

The JavaScript engine uses automatic garbage collection. JavaScript automatically manages memory by freeing up space used by objects no longer needed. This algorithm is called Mark and Sweep, which is performed periodically by the JavaScript engine.

38
Q

What are the different ways to declare a variable in JavaScript?

A

There are three ways to declare a variable in JavaScript var, let, and const.

39
Q

How to make an Object immutable in JavaScript?

A

To make an object immutable, you can use Object.freeze() method. It prevents the modification of existing property values and prevents the addition of new properties.

const roadmap = {
name: ‘JavaScript’,
};

Object.freeze(roadmap);

roadmap.name = ‘JavaScript Roadmap’; // throws an error in strict mode
console.log(roadmap.name); // JavaScript

40
Q

Does Arrow functions have their own this?

A

No, arrow functions do not have their own this. Instead, they inherit the this of the enclosing lexical scope.

41
Q

What is Hoisting in JavaScript?

A

oisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. This means that no matter where the functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local. Note that hoisting only moves the declaration, not the initialization.

console.log(x === undefined); // true
var x = 3;
console.log(x); // 3
The above code snippet can be visualized in the following way:

var x;
console.log(x === undefined); // true
x = 3;
console.log(x); // 3

42
Q

Is it possible to run JavaScript outside the browser?

A

Yes, it is possible to run JavaScript outside the browser. There are several ways to run JavaScript outside the browser. You can use Node.js, Deno, Bun, or any other JavaScript runtime environment.

43
Q

What are Scopes in JavaScript?

A

A scope is a set of variables, objects, and functions that you have access to. There are three types of scopes in JavaScript. Which are Global Scope, Function Scope (Local Scope), and Block Scope.

44
Q

How to define multiline strings in JavaScript?

A

In order to define multiline strings in JavaScript, you need to use template literals. Template literals are enclosed by the backtick ( ) character instead of double or single quotes. Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}).

45
Q

Difference between defer and async attributes in JavaScript?

A

https://roadmap.sh/guides/avoid-render-blocking-javascript-with-async-defer.png

The main difference between defer and async is the order of execution.

Defer attribute
A

 element with a defer attribute, it will continue to load the HTML page and render it while the script is being downloaded. The script is executed after the HTML page has been completely parsed. defer scripts maintain their order in the document.


In the example above, script1.js will be executed before script2.js. The browser will download both scripts in parallel, but script1.js will be executed after the HTML page has been parsed and script2.js will be executed after script1.js has been executed.

Async attribute
On the other hand, A

 element with an async attribute, it will pause the HTML parser and execute the script immediately after it has been downloaded. The HTML parsing will resume after the script has been executed.


In the example above, the browser will download both scripts in parallel, and execute them as soon as they are downloaded. The order of execution is not guaranteed.

To know more you can check this diagram from us that explains the difference between defer and async in a visual way.

46
Q

What is IIFE in JavaScript?

A

The IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

(function () {
console.log(‘Hello Roadmap!’);
})();
The IIFE is frequently used to create a new scope to avoid variable hoisting from within blocks.

(function () {
var roadmap = ‘JavaScript’;
console.log(roadmap);
})();

console.log(roadmap); // ReferenceError: name is not defined

47
Q

Are references copied in JavaScript?

A

No, references are not copied in JavaScript. When you assign an object to a variable, the variable will contain a reference to the object. If you assign the variable to another variable, the second variable will also contain a reference to the object. If you change the object using one of the variables, the change will be visible using the other variable.

48
Q

What is a closure in JavaScript?

A

A closure is a function that has access to its outer function scope even after the outer function has returned. This means a closure can remember and access variables and arguments of its outer function even after the function has finished.

function outer() {
const name = ‘Roadmap’;

function inner() {
console.log(name);
}

return inner;
}

const closure = outer();
closure(); // Roadmap
In the above example, the inner function has access to the name variable of the outer function even after the outer function has returned. Therefore, the inner function forms a closure.

49
Q

What are Explicit binding in JavaScript?

A

Explicit binding is a way to explicitly state what the this keyword is going to be bound to using call, apply or bind methods of a function.

const roadmap = {
name: ‘JavaScript’,
};

function printName() {
console.log(this.name);
}

printName.call(roadmap); // JavaScript
printName.apply(roadmap); // JavaScript

const printRoadmapName = printName.bind(roadmap);
printRoadmapName(); // JavaScript
In the above example, the this keyword inside the printName() function is explicitly bound to the roadmap object using call, apply or bind methods.

50
Q

What is the difference between map() and reduce() methods?

A

The map() method creates a new array with the results of calling a provided function on every element in the calling array. Whereas, the reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

51
Q

Is it possible to run 2 lines of code at the same time in JavaScript?

A

No, it is not possible to run 2 lines of code at the same time in JavaScript. JavaScript is a single-threaded language, which means that it can only execute one line of code at a time. However, it is possible to run 2 lines of code at the same time using asynchronous code.

52
Q

How to use do...while loop in JavaScript?

A

The do…while statement creates a loop that executes a block of code once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

let i = 0;

do {
console.log(i);
i++;
} while (i < 3);

// 0
// 1
// 2

53
Q

Uses of break and continue statements in JavaScript?

A

You can use break and continue in loops to alter the flow of the loop. break will stop the loop from continuing, and continue will skip the current iteration and continue the loop.

for (let i = 0; i < 5; i++) {
if (i === 1) {
continue; // skips the rest of the code in the loop
}
console.log(i: ${i});
}

// Output:
// i: 0
// i: 2
// i: 3
// i: 4
for (let i = 0; i < 5; i++) {
if (i === 1) {
break; // stops the loop
}
console.log(i: ${i});
}

// Output:
// i: 0

54
Q

Can you merge multiple arrays in JavaScript?

A

Yes, you can merge multiple arrays into one array using the concat() method, or the spread operator ….

concat()
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const arr3 = arr1.concat(arr2);
console.log(arr3); // [1, 2, 3, 4, 5, 6]
Spread operator
The spread operator … is used to expand an iterable object into the list of arguments.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const arr3 = […arr1, …arr2];
console.log(arr3); // [1, 2, 3, 4, 5, 6]

55
Q

How to handle error in async/await?

A

In order to handle errors in async/await, we can use the try/catch statement.

Rejecting a promise
const promise = new Promise((resolve, reject) => {
reject(new Error(‘Something went wrong’));
});
Try/catch statement
async function main() {
try {
const result = await promise;
console.log(result);
} catch (error) {
console.log(error.message);
}
}
The catch block will be executed when the promise is rejected or when an error is thrown inside the try block.

56
Q

How to create Infinite Loop in JavaScript?

A

You can use the while or for loop to create an infinite loop.

While loop
To create an infinite loop with the while loop, we can use the true keyword as the condition.

while (true) {
// do something
}
For loop
To create an infinite loop with the for loop, we can use the true keyword as the condition.

for (let i = 0; true; i++) {
// do something
}

57
Q

How does Event Loop work in JavaScript?

A

The Event loop has two main components: the Call stack and the Callback queue.

Call Stack
The Call stack is a data structure that stores the tasks that need to be executed. It is a LIFO (Last In, First Out) data structure, which means that the last task that was added to the Call stack will be the first one to be executed.

Callback Queue
The Callback queue is a data structure that stores the tasks that have been completed and are ready to be executed. It is a FIFO (First In, First Out) data structure, which means that the first task that was added to the Callback queue will be the first one to be executed.

Event Loop’s Workflow:
Executes tasks from the Call Stack.
For an asynchronous task, such as a timer, it runs in the background. JavaScript proceeds to the next task without waiting.
When the asynchronous task concludes, its callback function is added to the Callback Queue.
If the Call Stack is empty and there are tasks in the Callback Queue, the Event Loop transfers the first task from the Queue to the Call Stack for execution.
setTimeout(() => console.log(‘Hello from the timer’), 0);
console.log(‘Hello from the main code’);
setTimeout is processed, and because it’s asynchronous, its callback is placed in the Callback Queue.
The next line, console.log(“Hello from the main code”), is logged immediately.
Although the timer duration is 0 milliseconds, its callback has to wait until the Call Stack is empty. After the main code logs, the callback is moved from the Callback Queue to the Call Stack and executed.
The result is “Hello from the main code” being logged before “Hello from the timer”.

58
Q

What is Increment operator in JavaScript?

A

As the name says, the increment operator increases the value of a variable by 1. There are two types of increment operators: pre-increment and post-increment.

Pre-increment
The pre-increment operator increases the value of a variable by 1 and then returns the value. For example:

let x = 1;
console.log(++x); // 2
console.log(x); // 2
Post-increment
The post-increment operator returns the value of a variable and then increases the value by 1. For example:

let x = 1;
console.log(x++); // 1
console.log(x); // 2

59
Q

What is Comma Operator in JavaScript?

A

The Comma Operator , evaluates each of its operands (from left to right) and returns the value of the last operand.

let x = 1;
x = (x++, x);

console.log(x); // 2

60
Q

Asynchronous vs Synchronous code?

A

The difference between Asynchronous and Synchronous code is that Asynchronous code does not block the execution of the program while Synchronous code does.

Asynchronous code
Asynchronous code is executed in the background and it does not block the execution of the program. It is usually used to perform tasks that take a long time to complete, such as network requests.

console.log(‘Before’);

setTimeout(() => {
console.log(‘Hello’);
}, 1000);

console.log(‘After’);
Synchronous code
Synchronous code is executed in sequence and it blocks the execution of the program until it is completed. If a task takes a long time to complete, everything else waits.

console.log(‘Before’);

for (let i = 0; i < 1000000000; i++) {}

console.log(‘After’);

61
Q

How to parse JSON in JavaScript?

A

In order to parse JSON, you can use the JSON.parse() method. It parses a JSON string and returns the JavaScript equivalent.

const json = ‘{“name”:”JavaScript”,”year”:1995}’;
const roadmap = JSON.parse(json);

console.log(roadmap.name); // JavaScript
console.log(roadmap.year); // 1995

62
Q

Proxy

A
63
Q

Reflect

A