JavaScript Flashcards
What is ternary operator
in JavaScript?
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);
What is callback hell in JavaScript?
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); } }
What is the difference between Map
and WeakMap
in JavaScript?
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.
Switch case statement in JavaScript?
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 to debug JavaScript code?
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.
What is Inheritance in JavaScript?
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 to implement your own Custom Event in JavaScript?
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);
Explain alert()
, prompt()
, and confirm()
methods in JavaScript?
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
What is JavaScript?
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.
What is the difference between var
, let
, and const
in JavaScript?
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.
What is Map in JavaScript?
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 you can find unique values in an array?
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']
What is the difference between null
and undefined
?
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.
What is the purpose of the async/await
in JavaScript?
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.
What is the spread operator in JavaScript?
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’ }
What is Type Casting?
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 to use reduce()
method?
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
What is Set in JavaScript?
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
Difference between Promise.all()
and Promise.allSettled()
?
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.
Difference between Promise.all()
and Promise.allSettled()
?
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.
What is a JavaScript promise?
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 to use filter()
method?
What are Heap and Stack in JavaScript?
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.
What are Heap and Stack in JavaScript?
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.
What is Prototype Chain in JavaScript?
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.