mirror of
https://github.com/kamranahmedse/developer-roadmap.git
synced 2026-03-13 02:01:57 +08:00
Compare commits
32 Commits
feat/quest
...
chore/java
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eaf5aee2f5 | ||
|
|
aee10fac37 | ||
|
|
c70ee5c5f3 | ||
|
|
b39de5f670 | ||
|
|
802b84ad79 | ||
|
|
ff000c87ed | ||
|
|
1604cb9d8c | ||
|
|
3fab75d44c | ||
|
|
7fb089259d | ||
|
|
6713b059e1 | ||
|
|
e9651c6afe | ||
|
|
96fe0a5439 | ||
|
|
0393a658a7 | ||
|
|
4d0143f137 | ||
|
|
66eff7af70 | ||
|
|
0331e1f782 | ||
|
|
0318fe48e3 | ||
|
|
00ba8a73c1 | ||
|
|
81a9baedd0 | ||
|
|
50e26e4fe2 | ||
|
|
56473b129c | ||
|
|
1dd53d8994 | ||
|
|
1b639c433c | ||
|
|
041facdc61 | ||
|
|
e4d770e256 | ||
|
|
81bbb42e34 | ||
|
|
b92ae9b836 | ||
|
|
83df0da6b4 | ||
|
|
a58b78bfe9 | ||
|
|
2fa41f583e | ||
|
|
80819f8914 | ||
|
|
edcf0e683d |
@@ -2,6 +2,7 @@ import { Fragment, useEffect, useRef, useState } from 'react';
|
||||
import { useKeydown } from '../../hooks/use-keydown';
|
||||
import { useOutsideClick } from '../../hooks/use-outside-click';
|
||||
import BestPracticesIcon from '../../icons/best-practices.svg';
|
||||
import ClipboardIcon from '../../icons/clipboard.svg';
|
||||
import GuideIcon from '../../icons/guide.svg';
|
||||
import HomeIcon from '../../icons/home.svg';
|
||||
import RoadmapIcon from '../../icons/roadmap.svg';
|
||||
@@ -53,6 +54,13 @@ const defaultPages: PageType[] = [
|
||||
group: 'Pages',
|
||||
icon: BestPracticesIcon.src,
|
||||
},
|
||||
{
|
||||
id: 'questions',
|
||||
url: '/questions',
|
||||
title: 'Questions',
|
||||
group: 'Pages',
|
||||
icon: ClipboardIcon.src,
|
||||
},
|
||||
{
|
||||
id: 'guides',
|
||||
url: '/guides',
|
||||
|
||||
@@ -24,10 +24,10 @@ import AccountDropdown from './AccountDropdown.astro';
|
||||
>
|
||||
</li>
|
||||
<li class='hidden lg:inline'>
|
||||
<a href='/guides' class='text-gray-400 hover:text-white'>Guides</a>
|
||||
<a href='/questions' class='text-gray-400 hover:text-white'>Questions</a>
|
||||
</li>
|
||||
<li class='hidden lg:inline'>
|
||||
<a href='/videos' class='text-gray-400 hover:text-white'>Videos</a>
|
||||
<a href='/guides' class='text-gray-400 hover:text-white'>Guides</a>
|
||||
</li>
|
||||
<li>
|
||||
<kbd
|
||||
|
||||
@@ -19,6 +19,8 @@ function bindEvents() {
|
||||
...target.closest('button')?.dataset,
|
||||
};
|
||||
|
||||
const accountDropdown = document.querySelector('[data-account-dropdown]');
|
||||
|
||||
// If the user clicks on the logout button, remove the token cookie
|
||||
if (dataset.logoutButton !== undefined) {
|
||||
e.preventDefault();
|
||||
@@ -27,6 +29,12 @@ function bindEvents() {
|
||||
document.querySelector('[data-mobile-nav]')?.classList.remove('hidden');
|
||||
} else if (dataset.closeMobileNav !== undefined) {
|
||||
document.querySelector('[data-mobile-nav]')?.classList.add('hidden');
|
||||
} else if (
|
||||
accountDropdown &&
|
||||
!target?.closest('[data-account-dropdown]') &&
|
||||
!accountDropdown.classList.contains('hidden')
|
||||
) {
|
||||
accountDropdown.classList.add('hidden');
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -94,7 +94,7 @@ export function QuestionCard(props: QuestionCardProps) {
|
||||
>
|
||||
{!question.isLongAnswer && (
|
||||
<div
|
||||
className={`mx-auto flex max-w-[600px] flex-grow flex-col items-center justify-center py-0 px-5 text-center text-base leading-normal sm:text-xl`}
|
||||
className={`mx-auto flex max-w-[600px] flex-grow flex-col items-center justify-center py-0 px-5 text-center text-base [&>p]:leading-relaxed sm:text-xl`}
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: markdownToHtml(question.answer, false),
|
||||
}}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
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`.
|
||||
|
||||
```js
|
||||
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.
|
||||
|
||||
```js
|
||||
const result = confirm('Are you sure?');
|
||||
console.log(result); // true/false
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
You can add a new element to the DOM using the `appendChild` or `insertBefore` method.
|
||||
|
||||
## appendChild
|
||||
|
||||
The `appendChild` method adds a new element as the last child of the specified parent element.
|
||||
|
||||
```js
|
||||
const roadmapWrapper = document.querySelector('.roadmap-wrapper');
|
||||
|
||||
const roadmap = document.createElement('div');
|
||||
roadmap.id = 'javascript-roadmap';
|
||||
|
||||
roadmapWrapper.appendChild(roadmapTitle);
|
||||
```
|
||||
|
||||
In the example above, the `roadmap` element is added as the last child of the `roadmapWrapper` element.
|
||||
|
||||
## insertBefore
|
||||
|
||||
The `insertBefore` method adds a new element before the specified child element.
|
||||
|
||||
```js
|
||||
const roadmapWrapper = document.querySelector('.roadmap-wrapper');
|
||||
|
||||
const roadmap = document.createElement('div');
|
||||
roadmap.id = 'javascript-roadmap';
|
||||
|
||||
const roadmapTitle = document.querySelector('#roadmap-title');
|
||||
roadmapWrapper.insertBefore(roadmap, roadmapTitle);
|
||||
```
|
||||
|
||||
In the example above, the `roadmap` element is added before the `roadmapTitle` element.
|
||||
27
src/data/question-groups/javascript/content/async-vs-sync.md
Normal file
27
src/data/question-groups/javascript/content/async-vs-sync.md
Normal file
@@ -0,0 +1,27 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
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.
|
||||
|
||||
```js
|
||||
console.log('Before');
|
||||
|
||||
for (let i = 0; i < 1000000000; i++) {}
|
||||
|
||||
console.log('After');
|
||||
```
|
||||
@@ -0,0 +1,28 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
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
|
||||
```
|
||||
|
||||
```js
|
||||
for (let i = 0; i < 5; i++) {
|
||||
if (i === 1) {
|
||||
break; // stops the loop
|
||||
}
|
||||
console.log(`i: ${i}`);
|
||||
}
|
||||
|
||||
// Output:
|
||||
// i: 0
|
||||
```
|
||||
48
src/data/question-groups/javascript/content/callback-hell.md
Normal file
48
src/data/question-groups/javascript/content/callback-hell.md
Normal file
@@ -0,0 +1,48 @@
|
||||
**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
|
||||
|
||||
```js
|
||||
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
|
||||
|
||||
```js
|
||||
callAsync1()
|
||||
.then(() => callAsync2())
|
||||
.then(() => callAsync3())
|
||||
.then(() => callAsync4())
|
||||
.then(() => callAsync5())
|
||||
.catch((err) => console.error(err));
|
||||
```
|
||||
|
||||
### Async/await
|
||||
|
||||
```js
|
||||
async function asyncCall() {
|
||||
try {
|
||||
await callAsync1();
|
||||
await callAsync2();
|
||||
await callAsync3();
|
||||
await callAsync4();
|
||||
await callAsync5();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
```
|
||||
18
src/data/question-groups/javascript/content/closure.md
Normal file
18
src/data/question-groups/javascript/content/closure.md
Normal file
@@ -0,0 +1,18 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
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.
|
||||
@@ -0,0 +1,8 @@
|
||||
The Comma Operator `,` evaluates each of its operands (from left to right) and returns the value of the last operand.
|
||||
|
||||
```js
|
||||
let x = 1;
|
||||
x = (x++, x);
|
||||
|
||||
console.log(x); // 2
|
||||
```
|
||||
@@ -0,0 +1,9 @@
|
||||
To create a new DOM element, you can use the `document.createElement` method. It accepts a tag name as an argument and returns a new element with the specified tag name. You can set attributes to the element.
|
||||
|
||||
```js
|
||||
const div = document.createElement('div');
|
||||
|
||||
div.id = 'roadmap-wrapper';
|
||||
div.setAttribute('data-id', 'javascript');
|
||||
console.log(div); // <div id="roadmap-wrapper" data-id="javascript"></div>
|
||||
```
|
||||
33
src/data/question-groups/javascript/content/custom-event.md
Normal file
33
src/data/question-groups/javascript/content/custom-event.md
Normal file
@@ -0,0 +1,33 @@
|
||||
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
|
||||
|
||||
```js
|
||||
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.
|
||||
|
||||
```js
|
||||
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.
|
||||
|
||||
```js
|
||||
function handleEvent(event) {
|
||||
console.log(event.detail); // { name: 'JavaScript' }
|
||||
}
|
||||
|
||||
element.addEventListener('roadmap-updated', handleEvent);
|
||||
element.removeEventListener('roadmap-updated', handleEvent);
|
||||
```
|
||||
@@ -0,0 +1,38 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
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.
|
||||
|
||||
```js
|
||||
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.
|
||||
@@ -0,0 +1,25 @@
|
||||
The main difference between `defer` and `async` is the order of execution.
|
||||
|
||||
## Defer attribute
|
||||
|
||||
A `<script>` 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.
|
||||
|
||||
```html
|
||||
<script defer src="script1.js"></script>
|
||||
<script defer src="script2.js"></script>
|
||||
```
|
||||
|
||||
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 `<script>` 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.
|
||||
|
||||
```html
|
||||
<script async src="script1.js"></script>
|
||||
<script async src="script2.js"></script>
|
||||
```
|
||||
|
||||
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](https://roadmap.sh/guides/avoid-render-blocking-javascript-with-async-defer) from us that explains the difference between `defer` and `async` in a visual way.
|
||||
14
src/data/question-groups/javascript/content/do-while-loop.md
Normal file
14
src/data/question-groups/javascript/content/do-while-loop.md
Normal file
@@ -0,0 +1,14 @@
|
||||
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`.
|
||||
|
||||
```js
|
||||
let i = 0;
|
||||
|
||||
do {
|
||||
console.log(i);
|
||||
i++;
|
||||
} while (i < 3);
|
||||
|
||||
// 0
|
||||
// 1
|
||||
// 2
|
||||
```
|
||||
@@ -0,0 +1,7 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
console.log(1 == '1'); // true
|
||||
console.log(1 === '1'); // false
|
||||
console.log(1 === 1); // true
|
||||
```
|
||||
@@ -0,0 +1,24 @@
|
||||
In order to handle errors in async/await, we can use the `try/catch` statement.
|
||||
|
||||
## Rejecting a promise
|
||||
|
||||
```js
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
reject(new Error('Something went wrong'));
|
||||
});
|
||||
```
|
||||
|
||||
## Try/catch statement
|
||||
|
||||
```js
|
||||
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.
|
||||
@@ -0,0 +1,38 @@
|
||||
In order to handle errors in promises, we can use the `catch` method or the second argument of the `then` method.
|
||||
|
||||
## Rejecting a promise
|
||||
|
||||
```js
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
reject(new Error('Something went wrong'));
|
||||
});
|
||||
```
|
||||
|
||||
## Catch method
|
||||
|
||||
In this method, we can pass a `callback` function that will be called when the promise is `rejected`.
|
||||
|
||||
```js
|
||||
promise
|
||||
.then((result) => {
|
||||
console.log(result);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error.message);
|
||||
});
|
||||
```
|
||||
|
||||
## Second argument of the then method
|
||||
|
||||
In this method, we can pass two `callback` functions as arguments. The first one will be called when the promise is `resolved` and the second one will be called when the promise is `rejected`.
|
||||
|
||||
```js
|
||||
promise.then(
|
||||
(result) => {
|
||||
console.log(result);
|
||||
},
|
||||
(error) => {
|
||||
console.log(error.message);
|
||||
}
|
||||
);
|
||||
```
|
||||
@@ -0,0 +1,19 @@
|
||||
Event bubbling is a concept in the Document Object Model (DOM) that describes the way in which events propagate or "bubble up" through the hierarchy of nested elements in the DOM.
|
||||
|
||||
When an event, such as a mouse click, occurs on a DOM element, the event will be handled by the element first, then its parent element, and so on, until the event reaches the root element. This behavior is called event bubbling.
|
||||
|
||||
```js
|
||||
const parent = document.querySelector('.parent');
|
||||
const child = document.querySelector('.child');
|
||||
|
||||
// Scenario of clicking on the child element
|
||||
parent.addEventListener('click', () => {
|
||||
console.log('Handled Last');
|
||||
});
|
||||
|
||||
child.addEventListener('click', () => {
|
||||
console.log('Handled First');
|
||||
});
|
||||
```
|
||||
|
||||
In the above example, when you click on the `child` element, the event will be handled by the `child` element first, then its parent element, and so on, to the root element unless you stop the propagation (`event.stopPropagation()`) of the event.
|
||||
26
src/data/question-groups/javascript/content/event-loop.md
Normal file
26
src/data/question-groups/javascript/content/event-loop.md
Normal file
@@ -0,0 +1,26 @@
|
||||
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:
|
||||
|
||||
1. Executes tasks from the Call Stack.
|
||||
2. For an asynchronous task, such as a timer, it runs in the background. JavaScript proceeds to the next task without waiting.
|
||||
3. When the asynchronous task concludes, its callback function is added to the Callback Queue.
|
||||
4. 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.
|
||||
|
||||
```js
|
||||
setTimeout(() => console.log('Hello from the timer'), 0);
|
||||
console.log('Hello from the main code');
|
||||
```
|
||||
|
||||
1. `setTimeout` is processed, and because it's asynchronous, its callback is placed in the Callback Queue.
|
||||
2. The next line, `console.log("Hello from the main code")`, is logged immediately.
|
||||
3. 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.
|
||||
4. The result is "Hello from the main code" being logged before "Hello from the timer".
|
||||
@@ -0,0 +1,19 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
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.
|
||||
12
src/data/question-groups/javascript/content/filter-method.md
Normal file
12
src/data/question-groups/javascript/content/filter-method.md
Normal file
@@ -0,0 +1,12 @@
|
||||
You can use the `filter()` method to filter an array based on a condition. The `filter()` method creates a new array with all elements that pass the test implemented by the provided function.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5, 6];
|
||||
|
||||
const evenNumbers = numbers.filter((number) => {
|
||||
return number % 2 === 0;
|
||||
});
|
||||
|
||||
console.log(numbers); // [1, 2, 3, 4, 5, 6]
|
||||
console.log(evenNumbers); // [2, 4, 6]
|
||||
```
|
||||
@@ -0,0 +1,14 @@
|
||||
The `finally` block will be executed when the promise is `resolved` or `rejected`.
|
||||
|
||||
```js
|
||||
promise
|
||||
.then((result) => {
|
||||
console.log(result);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error.message);
|
||||
})
|
||||
.finally(() => {
|
||||
console.log('Finally Promise has settled');
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,55 @@
|
||||
There are serveral ways to find unique values in an array. Here are some of them:
|
||||
|
||||
## Using `Set`
|
||||
|
||||
```js
|
||||
const roadmaps = ['JavaScript', 'React', 'Node.js', 'Node.js', 'JavaScript'];
|
||||
const uniqueRoadmaps = [...new Set(roadmaps)];
|
||||
console.log(uniqueRoadmaps); // ['JavaScript', 'React', 'Node.js']
|
||||
```
|
||||
|
||||
## Using `filter()`
|
||||
|
||||
```js
|
||||
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()`
|
||||
|
||||
```js
|
||||
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()`
|
||||
|
||||
```js
|
||||
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`
|
||||
|
||||
```js
|
||||
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']
|
||||
```
|
||||
@@ -0,0 +1,9 @@
|
||||
No, the `forEach()` method does not return a new array. It simply calls a provided function on each element in the array.
|
||||
|
||||
```js
|
||||
const roadmaps = ['JavaScript', 'React', 'Node.js'];
|
||||
|
||||
roadmaps.forEach((roadmap) => {
|
||||
console.log(roadmap);
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,20 @@
|
||||
The Head 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:
|
||||
|
||||
```js
|
||||
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.
|
||||
16
src/data/question-groups/javascript/content/hoisting.md
Normal file
16
src/data/question-groups/javascript/content/hoisting.md
Normal file
@@ -0,0 +1,16 @@
|
||||
Hoisting 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.
|
||||
|
||||
```js
|
||||
console.log(x === undefined); // true
|
||||
var x = 3;
|
||||
console.log(x); // 3
|
||||
```
|
||||
|
||||
The above code snippet can be visualized in the following way:
|
||||
|
||||
```js
|
||||
var x;
|
||||
console.log(x === undefined); // true
|
||||
x = 3;
|
||||
console.log(x); // 3
|
||||
```
|
||||
18
src/data/question-groups/javascript/content/iife.md
Normal file
18
src/data/question-groups/javascript/content/iife.md
Normal file
@@ -0,0 +1,18 @@
|
||||
The IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.
|
||||
|
||||
```js
|
||||
(function () {
|
||||
console.log('Hello Roadmap!');
|
||||
})();
|
||||
```
|
||||
|
||||
The IIFE is frequently used to create a new scope to avoid variable hoisting from within blocks.
|
||||
|
||||
```js
|
||||
(function () {
|
||||
var roadmap = 'JavaScript';
|
||||
console.log(roadmap);
|
||||
})();
|
||||
|
||||
console.log(roadmap); // ReferenceError: name is not defined
|
||||
```
|
||||
@@ -0,0 +1,12 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
const roadmap = {
|
||||
name: 'JavaScript',
|
||||
};
|
||||
|
||||
Object.freeze(roadmap);
|
||||
|
||||
roadmap.name = 'JavaScript Roadmap'; // throws an error in strict mode
|
||||
console.log(roadmap.name); // JavaScript
|
||||
```
|
||||
@@ -0,0 +1,21 @@
|
||||
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:
|
||||
|
||||
```js
|
||||
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:
|
||||
|
||||
```js
|
||||
let x = 1;
|
||||
console.log(x++); // 1
|
||||
console.log(x); // 2
|
||||
```
|
||||
21
src/data/question-groups/javascript/content/infinite-loop.md
Normal file
21
src/data/question-groups/javascript/content/infinite-loop.md
Normal file
@@ -0,0 +1,21 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
while (true) {
|
||||
// do something
|
||||
}
|
||||
```
|
||||
|
||||
## For loop
|
||||
|
||||
To create an infinite loop with the `for` loop, we can use the `true` keyword as the condition.
|
||||
|
||||
```js
|
||||
for (let i = 0; true; i++) {
|
||||
// do something
|
||||
}
|
||||
```
|
||||
38
src/data/question-groups/javascript/content/inheritance.md
Normal file
38
src/data/question-groups/javascript/content/inheritance.md
Normal file
@@ -0,0 +1,38 @@
|
||||
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
|
||||
|
||||
```js
|
||||
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.
|
||||
@@ -0,0 +1,15 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
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
|
||||
```
|
||||
@@ -0,0 +1,43 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
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.
|
||||
|
||||
```js
|
||||
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.
|
||||
|
||||
```js
|
||||
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.
|
||||
|
||||
```js
|
||||
console.log(null ?? 'hello'); // hello
|
||||
console.log(undefined ?? 'hello'); // hello
|
||||
console.log('' ?? 'hello'); // ''
|
||||
console.log(0 ?? 'hello'); // 0
|
||||
```
|
||||
12
src/data/question-groups/javascript/content/map-method.md
Normal file
12
src/data/question-groups/javascript/content/map-method.md
Normal file
@@ -0,0 +1,12 @@
|
||||
No, the `map()` method does not mutate the original array. It returns a new array with the results of calling a provided function on every element in the calling array.
|
||||
|
||||
```js
|
||||
const roadmaps = ['JavaScript', 'React', 'Node.js'];
|
||||
|
||||
const renamedRoadmaps = roadmaps.map((roadmap) => {
|
||||
return `${roadmap} Roadmap`;
|
||||
});
|
||||
|
||||
console.log(roadmaps); // ['JavaScript', 'React', 'Node.js']
|
||||
console.log(renamedRoadmaps); // ['JavaScript Roadmap', 'React Roadmap', 'Node.js Roadmap']
|
||||
```
|
||||
19
src/data/question-groups/javascript/content/map.md
Normal file
19
src/data/question-groups/javascript/content/map.md
Normal file
@@ -0,0 +1,19 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
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
|
||||
```
|
||||
@@ -0,0 +1,8 @@
|
||||
You can use `getBoundingClientRect` method to get the dimensions of an element.
|
||||
|
||||
```js
|
||||
const roadmapWrapper = document.querySelector('.roadmap-wrapper');
|
||||
const dimensions = roadmapWrapper.getBoundingClientRect();
|
||||
|
||||
console.log(dimensions); // DOMRect { x: 8, y: 8, width: 784, height: 784, top: 8, right: 792, bottom: 792, left: 8 }
|
||||
```
|
||||
25
src/data/question-groups/javascript/content/merge-arrays.md
Normal file
25
src/data/question-groups/javascript/content/merge-arrays.md
Normal file
@@ -0,0 +1,25 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
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.
|
||||
|
||||
```js
|
||||
const arr1 = [1, 2, 3];
|
||||
const arr2 = [4, 5, 6];
|
||||
|
||||
const arr3 = [...arr1, ...arr2];
|
||||
console.log(arr3); // [1, 2, 3, 4, 5, 6]
|
||||
```
|
||||
@@ -0,0 +1,8 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
console.log(null ?? 'hello'); // hello
|
||||
console.log(undefined ?? 'hello'); // hello
|
||||
console.log('' ?? 'hello'); // ''
|
||||
console.log(0 ?? 'hello'); // 0
|
||||
```
|
||||
@@ -0,0 +1,9 @@
|
||||
In order to parse JSON, you can use the `JSON.parse()` method. It parses a JSON string and returns the JavaScript equivalent.
|
||||
|
||||
```js
|
||||
const json = '{"name":"JavaScript","year":1995}';
|
||||
const roadmap = JSON.parse(json);
|
||||
|
||||
console.log(roadmap.name); // JavaScript
|
||||
console.log(roadmap.year); // 1995
|
||||
```
|
||||
@@ -0,0 +1,10 @@
|
||||
The `event.preventDefault()` method is used to prevent the default action of an event. For example, when you click on a link, the default action is to navigate to the link's URL. But, if you want to prevent the navigation, you can use `event.preventDefault()` method.
|
||||
|
||||
```js
|
||||
const link = document.querySelector('a');
|
||||
|
||||
link.addEventListener('click', (event) => {
|
||||
event.preventDefault();
|
||||
console.log('Clicked on link!');
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,51 @@
|
||||
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
|
||||
|
||||
```js
|
||||
const promise1 = Promise.resolve('Promise 1 resolved');
|
||||
const promise2 = Promise.reject('Promise 2 rejected');
|
||||
```
|
||||
|
||||
## Using `Promise.all()`
|
||||
|
||||
```js
|
||||
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()`
|
||||
|
||||
```js
|
||||
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.
|
||||
@@ -0,0 +1,27 @@
|
||||
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
|
||||
|
||||
```js
|
||||
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.
|
||||
@@ -0,0 +1,18 @@
|
||||
For selecting elements in the DOM, the `querySelector` and `querySelectorAll` methods are the most commonly used. They are both methods of the `document` object, and they both accept a CSS selector as an argument.
|
||||
|
||||
## querySelector
|
||||
|
||||
The `querySelector` method returns the first element that matches the specified selector. If no matches are found, it returns `null`.
|
||||
|
||||
```js
|
||||
const roadmapWrapper = document.querySelector('.roadmap-wrapper');
|
||||
const roadmapTitle = document.querySelector('#roadmap-title');
|
||||
```
|
||||
|
||||
## querySelectorAll
|
||||
|
||||
The `querySelectorAll` method returns a `NodeList` of all elements that match the specified selector. If no matches are found, it returns an empty `NodeList`.
|
||||
|
||||
```js
|
||||
const roadmapItems = document.querySelectorAll('.roadmap-item');
|
||||
```
|
||||
24
src/data/question-groups/javascript/content/reduce-method.md
Normal file
24
src/data/question-groups/javascript/content/reduce-method.md
Normal file
@@ -0,0 +1,24 @@
|
||||
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
|
||||
|
||||
```js
|
||||
array.reduce((accumulator, currentValue) => {
|
||||
// ...
|
||||
}, initialValue);
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
You can use the `reduce()` method to sum all the numbers in an array.
|
||||
|
||||
```js
|
||||
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
|
||||
```
|
||||
@@ -0,0 +1,9 @@
|
||||
To remove a DOM element, you can use the `remove` or `removeChild` method of the `Node` interface.
|
||||
|
||||
```js
|
||||
const roadmapWrapper = document.querySelector('.roadmap-wrapper');
|
||||
const roadmapTitle = document.querySelector('#roadmap-title');
|
||||
|
||||
roadmapWrapper.removeChild(roadmapTitle);
|
||||
roadmapWrapper.remove();
|
||||
```
|
||||
@@ -0,0 +1,5 @@
|
||||
In order to scroll to the top of the page, we can use the `scrollTo` method.
|
||||
|
||||
```js
|
||||
window.scrollTo(0, 0);
|
||||
```
|
||||
17
src/data/question-groups/javascript/content/set-interval.md
Normal file
17
src/data/question-groups/javascript/content/set-interval.md
Normal file
@@ -0,0 +1,17 @@
|
||||
You 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.
|
||||
|
||||
```js
|
||||
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.
|
||||
|
||||
```js
|
||||
clearInterval(intervalId);
|
||||
```
|
||||
16
src/data/question-groups/javascript/content/set-timeout.md
Normal file
16
src/data/question-groups/javascript/content/set-timeout.md
Normal file
@@ -0,0 +1,16 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
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.
|
||||
|
||||
```js
|
||||
clearTimeout(timeoutId);
|
||||
```
|
||||
17
src/data/question-groups/javascript/content/set.md
Normal file
17
src/data/question-groups/javascript/content/set.md
Normal file
@@ -0,0 +1,17 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
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
|
||||
```
|
||||
@@ -0,0 +1,19 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
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']
|
||||
```
|
||||
|
||||
```js
|
||||
const roadmap = {
|
||||
name: 'JavaScript',
|
||||
type: 'dynamic',
|
||||
};
|
||||
|
||||
const roadmapClone = { ...roadmap }; // shallow copy
|
||||
console.log(roadmapClone); // { name: 'JavaScript', type: 'dynamic' }
|
||||
```
|
||||
19
src/data/question-groups/javascript/content/switch-case.md
Normal file
19
src/data/question-groups/javascript/content/switch-case.md
Normal file
@@ -0,0 +1,19 @@
|
||||
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 `case`s that follow the matching `case`.
|
||||
|
||||
```js
|
||||
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.
|
||||
```
|
||||
@@ -0,0 +1,5 @@
|
||||
The ternary operator is a conditional operator that takes three operands. It is frequently used as a shortcut for the `if` statement.
|
||||
|
||||
```js
|
||||
console.log(condition ? true : false);
|
||||
```
|
||||
@@ -0,0 +1,27 @@
|
||||
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.
|
||||
|
||||
```js
|
||||
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.
|
||||
|
||||
```js
|
||||
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.
|
||||
396
src/data/question-groups/javascript/javascript.md
Normal file
396
src/data/question-groups/javascript/javascript.md
Normal file
@@ -0,0 +1,396 @@
|
||||
---
|
||||
order: 1
|
||||
briefTitle: 'JavaScript'
|
||||
briefDescription: 'Test, rate and improve your JavaScript knowledge with these questions.'
|
||||
title: 'JavaScript Questions'
|
||||
description: 'Test, rate and improve your JavaScript knowledge with these questions.'
|
||||
isNew: true
|
||||
seo:
|
||||
title: 'JavaScript Questions'
|
||||
description: 'Curated list of JavaScript questions to test, rate and improve your knowledge. Questions are based on real world experience and knowledge.'
|
||||
keywords:
|
||||
- 'javascript quiz'
|
||||
- 'javascript questions'
|
||||
- 'javascript interview questions'
|
||||
- 'javascript interview'
|
||||
- 'javascript test'
|
||||
sitemap:
|
||||
priority: 1
|
||||
changefreq: 'monthly'
|
||||
questions:
|
||||
- question: What is JavaScript?
|
||||
answer: 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.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: What is the difference between `var`, `let`, and `const` in JavaScript?
|
||||
answer: 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.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: What is the difference between `null` and `undefined`?
|
||||
answer: 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.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: What is the difference between `==` and `===`?
|
||||
answer: equality-operator.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: What are the different ways to declare a variable in JavaScript?
|
||||
answer: There are three ways to declare a variable in JavaScript `var`, `let`, and `const`.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: What are Scopes in JavaScript?
|
||||
answer: 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.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: What is ternary operator in JavaScript?
|
||||
answer: ternary-operator.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: How to implement your own Custom Event in JavaScript?
|
||||
answer: custom-event.md
|
||||
topics:
|
||||
- 'Event'
|
||||
- 'Advanced'
|
||||
- question: What is a closure in JavaScript?
|
||||
answer: closure.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Advanced'
|
||||
- question: Does Arrow functions have their own `this`?
|
||||
answer: No, arrow functions do not have their own `this`. Instead, they inherit the `this` of the enclosing lexical scope.
|
||||
topics:
|
||||
- 'Function'
|
||||
- 'Intermediate'
|
||||
- question: Does `map()` method mutate the original array?
|
||||
answer: map-method.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: Does `forEach()` method return a new array?
|
||||
answer: for-each-method.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: How to use `filter()` method?
|
||||
answer: filter-method.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: What is the difference between `map()` and `forEach()` methods?
|
||||
answer: 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.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: How to use `reduce()` method?
|
||||
answer: reduce-method.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: What is the difference between `map()` and `reduce()` methods?
|
||||
answer: 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.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: What is Prototype Chain in JavaScript?
|
||||
answer: prototype-chain.md
|
||||
topics:
|
||||
- 'OOP'
|
||||
- 'Advanced'
|
||||
- question: What is IIFE in JavaScript?
|
||||
answer: iife.md
|
||||
topics:
|
||||
- 'Function'
|
||||
- 'Advanced'
|
||||
- question: What is Inheritance in JavaScript?
|
||||
answer: inheritance.md
|
||||
topics:
|
||||
- 'OOP'
|
||||
- 'Advanced'
|
||||
- question: What is Map in JavaScript?
|
||||
answer: map.md
|
||||
topics:
|
||||
- 'Date Type'
|
||||
- 'Beginner'
|
||||
- question: What is Set in JavaScript?
|
||||
answer: set.md
|
||||
topics:
|
||||
- 'Data Type'
|
||||
- 'Beginner'
|
||||
- question: How you can find unique values in an array?
|
||||
answer: find-unique-array-values.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: What is a JavaScript promise?
|
||||
answer: 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.
|
||||
topics:
|
||||
- 'Promise'
|
||||
- 'Advanced'
|
||||
- question: What is the purpose of the `async/await` in JavaScript?
|
||||
answer: 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.
|
||||
topics:
|
||||
- 'Promise'
|
||||
- 'Advanced'
|
||||
- question: What is callback hell in JavaScript?
|
||||
answer: callback-hell.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Advanced'
|
||||
- question: How to enable strict mode in JavaScript?
|
||||
answer: To enable strict mode in JavaScript, you need to add the following line at the top of the file or function `'use strict';`.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: Explain `alert()`, `prompt()`, and `confirm()` methods in JavaScript?
|
||||
answer: alert-prompt-confirm.md
|
||||
topics:
|
||||
- 'Event'
|
||||
- 'Intermediate'
|
||||
- question: How to handle event bubbling in JavaScript?
|
||||
answer: event-bubbling.md
|
||||
topics:
|
||||
- 'Event'
|
||||
- 'Beginner'
|
||||
- question: What is Event Capturing in JavaScript?
|
||||
answer: Event capturing is the first phase of event propagation. In this phase, the event is captured by the outermost element and propagated to the inner elements. It is also known as trickling. It is the opposite of event bubbling.
|
||||
topics:
|
||||
- 'Event'
|
||||
- 'Beginner'
|
||||
- question: What is the spread operator in JavaScript?
|
||||
answer: spread-operator.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: Is Java and JavaScript the same?
|
||||
answer: No, Java and JavaScript are distinct languages. Their similarity in name is coincidental, much like `car` and `carpet`. Java is often used for backend and mobile apps, while JavaScript powers web interactivity and backend.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: What is `preventDefault()` method in JavaScript?
|
||||
answer: prevent-default.md
|
||||
topics:
|
||||
- 'Event'
|
||||
- 'Intermediate'
|
||||
- question: What is Hoisting in JavaScript?
|
||||
answer: hoisting.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: What is DOM?
|
||||
answer: The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects.
|
||||
topics:
|
||||
- 'DOM'
|
||||
- 'Beginner'
|
||||
- question: Difference between `Promise.all()` and `Promise.allSettled()`?
|
||||
answer: promise-all-vs-all-settled.md
|
||||
topics:
|
||||
- 'Promise'
|
||||
- 'Advanced'
|
||||
- question: What is the difference between `Map` and `WeakMap` in JavaScript?
|
||||
answer: 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.
|
||||
topics:
|
||||
- 'Data Type'
|
||||
- 'Advanced'
|
||||
- question: Garbage collection in JavaScript?
|
||||
answer: 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.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Advanced'
|
||||
- question: How to make an Object immutable in JavaScript?
|
||||
answer: immutable-object.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Advanced'
|
||||
- question: What is Type Casting?
|
||||
answer: 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.
|
||||
topics:
|
||||
- 'Data Type'
|
||||
- 'Intermediate'
|
||||
- question: What are Explicit binding in JavaScript?
|
||||
answer: explicit-binding.md
|
||||
topics:
|
||||
- 'Function'
|
||||
- 'Advanced'
|
||||
- question: How to run a piece of code after a specific time interval?
|
||||
answer: set-interval.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: How to run a piece of code only once after a specific time?
|
||||
answer: set-timeout.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: What are Labelled Statements in JavaScript?
|
||||
answer: labelled-statements.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: Difference between `defer` and `async` attributes in JavaScript?
|
||||
answer: defer-vs-async.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: What is Increment operator in JavaScript?
|
||||
answer: increment-operator.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: How to accept variable number of arguments in a JavaScript function?
|
||||
answer: variable-number-of-arguments.md
|
||||
topics:
|
||||
- 'Function'
|
||||
- 'Intermediate'
|
||||
- question: How to define multiline strings in JavaScript?
|
||||
answer: 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}` ```).
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: Uses of `break` and `continue` statements in JavaScript?
|
||||
answer: break-and-continue.md
|
||||
topics:
|
||||
- 'Loop'
|
||||
- 'Beginner'
|
||||
- question: How to parse JSON in JavaScript?
|
||||
answer: parse-json.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: How to debug JavaScript code?
|
||||
answer: debug-javascript.md
|
||||
topics:
|
||||
- 'Debug'
|
||||
- 'Beginner'
|
||||
- question: How to handle error in Promise?
|
||||
answer: error-in-promise.md
|
||||
topics:
|
||||
- 'Promise'
|
||||
- 'Advanced'
|
||||
- question: How to handle error in async/await?
|
||||
answer: error-in-async-await.md
|
||||
topics:
|
||||
- 'Promise'
|
||||
- 'Advanced'
|
||||
- question: How to use `finally` block in Promise?
|
||||
answer: finally-block-in-promise.md
|
||||
topics:
|
||||
- 'Promise'
|
||||
- 'Advanced'
|
||||
- question: Asynchronous vs Synchronous code?
|
||||
answer: async-vs-sync.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: What is Event Loop in JavaScript?
|
||||
answer: 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.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Advanced'
|
||||
- question: How does Event Loop work in JavaScript?
|
||||
answer: event-loop.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Advanced'
|
||||
- question: Is it possible to run JavaScript outside the browser?
|
||||
answer: 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.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: Is it possible to run 2 lines of code at the same time in JavaScript?
|
||||
answer: 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.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: Is JavaScript a compiled or interpreted language?
|
||||
answer: 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.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: Are references copied in JavaScript?
|
||||
answer: 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.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: What are Heap and Stack in JavaScript?
|
||||
answer: heap-and-stack.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Advanced'
|
||||
- question: What is Comma Operator in JavaScript?
|
||||
answer: comma-operator.md
|
||||
topics:
|
||||
- 'Operator'
|
||||
- 'Intermediate'
|
||||
- question: What is Nullish Coalescing Operator?
|
||||
answer: nullish-coalescing-operator.md
|
||||
topics:
|
||||
- 'Operator'
|
||||
- 'Beginner'
|
||||
- question: What are the Logical Operators in JavaScript?
|
||||
answer: logical-operators.md
|
||||
topics:
|
||||
- 'Operator'
|
||||
- 'Beginner'
|
||||
- question: How to create Infinite Loop in JavaScript?
|
||||
answer: infinite-loop.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: How to use `do...while` loop in JavaScript?
|
||||
answer: do-while-loop.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: Switch case statement in JavaScript?
|
||||
answer: switch-case.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: How to select DOM elements using `querySelector()` and `querySelectorAll()`?
|
||||
answer: query-selector.md
|
||||
topics:
|
||||
- 'DOM'
|
||||
- 'Beginner'
|
||||
- question: How to create a new Element in DOM?
|
||||
answer: create-element.md
|
||||
topics:
|
||||
- 'DOM'
|
||||
- 'Beginner'
|
||||
- question: Difference between `appendChild()` and `insertBefore()`?
|
||||
answer: append-child-vs-insert-before.md
|
||||
topics:
|
||||
- 'DOM'
|
||||
- 'Beginner'
|
||||
- question: How to remove an Element from DOM?
|
||||
answer: remove-element.md
|
||||
topics:
|
||||
- 'DOM'
|
||||
- 'Beginner'
|
||||
- question: How to scroll to the top of the page using JavaScript?
|
||||
answer: scroll-to-top.md
|
||||
topics:
|
||||
- 'DOM'
|
||||
- 'Beginner'
|
||||
- question: How to measure dimensions of an Element?
|
||||
answer: measure-dimensions.md
|
||||
topics:
|
||||
- 'DOM'
|
||||
- 'Beginner'
|
||||
- question: Can you merge multiple arrays in JavaScript?
|
||||
answer: merge-arrays.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: How to get viewport dimensions in JavaScript?
|
||||
answer: You can use `window.innerWidth` and `window.innerHeight` to get the viewport dimensions.
|
||||
topics:
|
||||
- 'DOM'
|
||||
- 'Beginner'
|
||||
---
|
||||
@@ -0,0 +1,32 @@
|
||||
In React functional components, lifecycle-like behaviors are achieved using hooks:
|
||||
|
||||
## Mounting and Unmounting
|
||||
|
||||
Utilizing the useEffect hook with an empty dependency array ([]) ensures the hook runs after the component mounts to the DOM.
|
||||
|
||||
```js
|
||||
useEffect(() => {
|
||||
// do something after component mounts
|
||||
return () => {
|
||||
// do something before component unmounts
|
||||
};
|
||||
}, []);
|
||||
```
|
||||
|
||||
The cleanup function returned within the useEffect callback offers a mechanism for handling tasks when the component is about to **unmount**.
|
||||
|
||||
## Updates
|
||||
|
||||
The useEffect hook, when invoked without a dependency array or with specific dependencies, executes after every render or when specified prop/state changes are detected.
|
||||
|
||||
```js
|
||||
useEffect(() => {
|
||||
// do something after every render
|
||||
});
|
||||
```
|
||||
|
||||
```js
|
||||
useEffect(() => {
|
||||
// do something after specific prop/state changes
|
||||
}, [state1, state2]);
|
||||
```
|
||||
51
src/data/question-groups/react/content/custom-hook.md
Normal file
51
src/data/question-groups/react/content/custom-hook.md
Normal file
@@ -0,0 +1,51 @@
|
||||
**Custom hooks** are a mechanism for code reuse in React and allow you to extract component logic into reusable functions. Custom hooks can be used to share logic between components or to abstract away complex logic to make components more readable.
|
||||
|
||||
Let's look at an example of a custom hook that return network status information:
|
||||
|
||||
## Creating a Custom hook
|
||||
|
||||
Custom hooks are named with the prefix `use` and can call other hooks if needed. They can also accept arguments and return values.
|
||||
|
||||
```js
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
function useNetworkStatus() {
|
||||
const [isOnline, setIsOnline] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
function handleOnline() {
|
||||
setIsOnline(true);
|
||||
}
|
||||
|
||||
function handleOffline() {
|
||||
setIsOnline(false);
|
||||
}
|
||||
|
||||
window.addEventListener('online', handleOnline);
|
||||
window.addEventListener('offline', handleOffline);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('online', handleOnline);
|
||||
window.removeEventListener('offline', handleOffline);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return isOnline;
|
||||
}
|
||||
```
|
||||
|
||||
The custom hook above uses the `useState` and `useEffect` hooks to track the network status of the browser. It returns a boolean value that indicates whether the browser is online or offline.
|
||||
|
||||
## Using a Custom hook
|
||||
|
||||
```js
|
||||
function NetworkStatus() {
|
||||
const isOnline = useNetworkStatus();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p>You are {isOnline ? 'online' : 'offline'}.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
37
src/data/question-groups/react/content/error-boundaries.md
Normal file
37
src/data/question-groups/react/content/error-boundaries.md
Normal file
@@ -0,0 +1,37 @@
|
||||
Error boundaries are special React components that catch JavaScript errors during rendering, in lifecycle methods, and during the constructor of whole tree below them. They are used to handle errors gracefully by displaying a fallback UI and preventing the entire application from crashing due to unhandled errors.
|
||||
|
||||
You can use [react-error-boundary](https://npm.im/react-error-boundary) package to create error boundaries in your application. It provides a `ErrorBoundary` component that you can wrap around any component that might throw an error. The `ErrorBoundary` component takes a `FallbackComponent` prop that is used to render a fallback UI when an error occurs.
|
||||
|
||||
## Capturing Errors
|
||||
|
||||
```js
|
||||
import { ErrorBoundary } from 'react-error-boundary';
|
||||
import { FetchData } from './FetchData';
|
||||
|
||||
function ErrorFallback({ error, resetErrorBoundary }) {
|
||||
return (
|
||||
<div role="alert">
|
||||
<p>Something went wrong:</p>
|
||||
<pre>{error.message}</pre>
|
||||
<button onClick={resetErrorBoundary}>Try again</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<ErrorBoundary FallbackComponent={ErrorFallback}>
|
||||
<FetchData />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
This `FetchData` component will throw an error when it is rendered, and the `ErrorBoundary` component will catch the error and display the `ErrorFallback` component.
|
||||
|
||||
```js
|
||||
export function FetchData() {
|
||||
throw new Error('Error fetching data');
|
||||
return <p>This will never render</p>;
|
||||
}
|
||||
```
|
||||
9
src/data/question-groups/react/content/flush-sync.md
Normal file
9
src/data/question-groups/react/content/flush-sync.md
Normal file
@@ -0,0 +1,9 @@
|
||||
The `flushSync` function in React is used to flush updates synchronously. It schedules updates to be performed inside a high-priority task, ensuring that the updates are executed immediately and synchronously before returning control to the caller.
|
||||
|
||||
```js
|
||||
import { flushSync } from 'react-dom';
|
||||
|
||||
flushSync(callback);
|
||||
```
|
||||
|
||||
This is useful in situations where you need the DOM to be updated immediately, such as for measurements or to ensure synchronous rendering. However, excessive use of `flushSync` can lead to degraded performance, so it should be used judiciously.
|
||||
@@ -0,0 +1,33 @@
|
||||
There are many reasons why an app might be slow. It could be due to a slow network, a slow backend, or a slow client. It could also be due to a memory leak, unnecessary re-renders, or large bundle sizes.
|
||||
|
||||
Here are some tips to help you investigate and fix performance issues:
|
||||
|
||||
## Use the React DevTools Profiler
|
||||
|
||||
The React DevTools Profiler helps you visualize how components render and identify costly renderings. It can also help you identify unnecessary re-renders.
|
||||
|
||||
## Check for Unnecessary Renders
|
||||
|
||||
Ensure that components don't render more often than needed. Be clear about the `useEffect` dependencies and avoid creating new objects or arrays every render, as these can trigger unnecessary child component renders. Tools like [why-did-you-render](https://npm.im/@welldone-software/why-did-you-render) can help spot unnecessary re-renders.
|
||||
|
||||
## Analyze Bundle Size
|
||||
|
||||
Use your production build to analyze your bundle size. Tools like [webpack-bundle-analyzer](https://npm.im/webpack-bundle-analyzer) or [source-map-explorer](https://npm.im/source-map-explorer) can help you see if large libraries or unused code is slowing down the initial load.
|
||||
|
||||
## Optimize Images & Assets
|
||||
|
||||
Ensure images are appropriately sized and use modern formats. Also, consider using CDNs for assets that don't change often.
|
||||
|
||||
## Lazy Load Components
|
||||
|
||||
Use `lazy()` and dynamic imports to split your bundle and load components only when they're needed. This can help reduce the initial load time.
|
||||
|
||||
## Check Network Requests
|
||||
|
||||
Slow API calls or fetching large amounts of data can affect performance. Optimize your backend, paginate data, or cache results. You can also use tools like [@tanstack/react-query](https://npm.im/@tanstack/react-query) or [swr](https://npm.im/swr) to help manage data fetching and caching.
|
||||
|
||||
## Use Production Build for Testing
|
||||
|
||||
Ensure you're testing the performance on a production build, as development builds are often slower due to extra checks and logs.
|
||||
|
||||
Regularly profiling and monitoring your app can help you spot and fix performance issues before they become significant problems. You can use tools like [Lighthouse](https://developers.google.com/web/tools/lighthouse) or [Calibre](https://calibreapp.com) to monitor your app's performance over time.
|
||||
39
src/data/question-groups/react/content/lazy-loading.md
Normal file
39
src/data/question-groups/react/content/lazy-loading.md
Normal file
@@ -0,0 +1,39 @@
|
||||
You can use React's `lazy()` function in conjunction with dynamic `import()` to lazily load a component. This is often combined with `Suspense` to display fallback content while the component is being loaded.
|
||||
|
||||
```js
|
||||
// The component has to be exported as a default export
|
||||
export default function RoadmapRender() {
|
||||
return <h1>This is a lazily-loaded component!</h1>;
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
import { lazy, Suspense } from 'react';
|
||||
|
||||
const LazyRoadmapRender = lazy(() => delay(import('./RoadmapRender')));
|
||||
|
||||
export function App() {
|
||||
const [showRoadmapRender, setShowRoadmapRender] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => setShowRoadmapRender(true)}>
|
||||
Show RoadmapRender
|
||||
</button>
|
||||
{showRoadmapRender && (
|
||||
<Suspense fallback={<div>Loading...</div>}>
|
||||
<LazyRoadmapRender />
|
||||
</Suspense>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// Helper function to simulate a 2 seconds delay
|
||||
function delay(promise) {
|
||||
return new Promise((resolve) => setTimeout(resolve, 2000)).then(
|
||||
() => promise
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `RoadmapRender` component is lazily loaded and rendered inside the `Suspense` component. While the component is being loaded, the `Suspense` component will display the fallback content.
|
||||
@@ -2,7 +2,7 @@ Pure components re-render only when the props passed to the component changes. F
|
||||
|
||||
To create a pure component, you can use the `memo` function from React. It is a higher order component which takes a component as an argument and returns a new component. The new component renders only if the props change.
|
||||
|
||||
```jsx
|
||||
```javascript
|
||||
import React, { memo } from 'react';
|
||||
|
||||
const ChildComponent = ({ name }) => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
By default, each component’s DOM nodes are private. However, sometimes it’s useful to expose a DOM node to the parent—for example, to allow focusing it. To opt in, wrap your component definition into `forwardRef()`:
|
||||
|
||||
```jsx
|
||||
```javascript
|
||||
import { forwardRef } from 'react';
|
||||
|
||||
const MyInput = forwardRef(function MyInput(props, ref) {
|
||||
@@ -16,7 +16,7 @@ const MyInput = forwardRef(function MyInput(props, ref) {
|
||||
|
||||
You will receive a `ref` as the second argument after props. Pass it to the DOM node that you want to expose:
|
||||
|
||||
```jsx
|
||||
```javascript
|
||||
import { forwardRef } from 'react';
|
||||
|
||||
const MyInput = forwardRef(function MyInput(props, ref) {
|
||||
@@ -32,7 +32,7 @@ const MyInput = forwardRef(function MyInput(props, ref) {
|
||||
|
||||
This lets the parent Form component access their `<input>` DOM node exposed by `MyInput`:
|
||||
|
||||
```jsx
|
||||
```javascript
|
||||
function Form() {
|
||||
const ref = useRef(null);
|
||||
|
||||
|
||||
17
src/data/question-groups/react/content/render-list.md
Normal file
17
src/data/question-groups/react/content/render-list.md
Normal file
@@ -0,0 +1,17 @@
|
||||
In React, you can render a list by using the JavaScript `map` function to iterate over an array of items and return a JSX element for each item. It's important to provide a unique `key` prop to each element in the list for React's diffing algorithm to function efficiently during re-renders. Here's a basic example:
|
||||
|
||||
```javascript
|
||||
const items = ['Apple', 'Banana', 'Cherry'];
|
||||
|
||||
function FruitList() {
|
||||
return (
|
||||
<ul>
|
||||
{items.map((fruit, index) => (
|
||||
<li key={index}>{fruit}</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
> Note: While using the index as a key can work in some cases, it's generally not recommended for dynamic lists where items can be added, removed, or reordered.
|
||||
19
src/data/question-groups/react/content/strict-mode.md
Normal file
19
src/data/question-groups/react/content/strict-mode.md
Normal file
@@ -0,0 +1,19 @@
|
||||
Strict Mode is a tool in React for highlighting potential problems in an application. By wrapping a component tree with `StrictMode`, React will activate additional checks and warnings for its descendants. This doesn't affect the production build but provides insights during development.
|
||||
|
||||
```js
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
|
||||
const root = createRoot(document.getElementById('root'));
|
||||
root.render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>
|
||||
);
|
||||
```
|
||||
|
||||
In Strict Mode, React does a few extra things during development:
|
||||
|
||||
1. It renders components twice to catch bugs caused by impure rendering.
|
||||
2. It runs side-effects (like data fetching) twice to find mistakes in them caused by missing effect cleanup.
|
||||
3. It checks if deprecated APIs are used, and logs a warning message to the console if so.
|
||||
23
src/data/question-groups/react/content/suspense.md
Normal file
23
src/data/question-groups/react/content/suspense.md
Normal file
@@ -0,0 +1,23 @@
|
||||
Suspense is a component in React that lets you specify the fallback content to display while waiting for a component to load. It is used in conjunction with `lazy()` to lazily load components.
|
||||
|
||||
```js
|
||||
import { lazy, Suspense } from 'react';
|
||||
|
||||
const LazyRoadmapRender = lazy(() => import('./RoadmapRender'));
|
||||
|
||||
export function App() {
|
||||
const [show, setShow] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => setShow(true)}>Show</button>
|
||||
{show && (
|
||||
<Suspense fallback={<div>Loading...</div>}>
|
||||
<LazyRoadmapRender />
|
||||
</Suspense>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Until the `RoadmapRender` component is loaded, the `Suspense` component will display the `Loading...` fallback content.
|
||||
@@ -2,7 +2,7 @@ React differs from HTML in that it uses a synthetic event system instead of dire
|
||||
|
||||
The events such as `onClick`, `onSubmit`, `onFocus`, etc. are all camel-cased to be consistent with the naming convention in JavaScript. React event handlers are written inside curly braces:
|
||||
|
||||
```jsx
|
||||
```javascript
|
||||
function activateLasers(e) {
|
||||
e.preventDefault();
|
||||
console.log('The button was clicked.');
|
||||
|
||||
67
src/data/question-groups/react/content/use-transition.md
Normal file
67
src/data/question-groups/react/content/use-transition.md
Normal file
@@ -0,0 +1,67 @@
|
||||
`useTransition` hook allows you to mark certain updates as **transitions** so they can be deprioritized, allowing other, more urgent updates to be processed first. This ensures that the UI remains responsive during updates that might take some time.
|
||||
|
||||
```js
|
||||
import { useTransition, useState } from 'react';
|
||||
import { Posts } from './Posts';
|
||||
import { Home } from './Home';
|
||||
import { Contact } from './Contact';
|
||||
|
||||
export function App() {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [page, setPage] = useState('home');
|
||||
|
||||
function changePage(newPage: string) {
|
||||
startTransition(() => {
|
||||
setPage(newPage);
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => changePage('home')}>Home</button>
|
||||
<button onClick={() => changePage('posts')}>Posts</button>
|
||||
<button onClick={() => changePage('contact')}>Contact</button>
|
||||
<hr />
|
||||
{isPending && <div>Loading...</div>}
|
||||
{page === 'home' && <Home />}
|
||||
{page === 'posts' && <Posts />}
|
||||
{page === 'contact' && <Contact />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
export function Home() {
|
||||
return <div>Home</div>;
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
export function Contact() {
|
||||
return <div>Contact</div>;
|
||||
}
|
||||
```
|
||||
|
||||
Posts component is artificially delayed by 500ms to emulate extremely slow code.
|
||||
|
||||
```js
|
||||
export function Posts() {
|
||||
const items = [];
|
||||
for (let i = 0; i < 500; i++) {
|
||||
items.push(<SlowPost key={i} />);
|
||||
}
|
||||
return <ul>{items}</ul>;
|
||||
}
|
||||
|
||||
function SlowPost() {
|
||||
const startTime = performance.now();
|
||||
while (performance.now() - startTime < 1) {
|
||||
// Do nothing for 1 ms per item to emulate extremely slow code
|
||||
}
|
||||
|
||||
return <li>Post</li>;
|
||||
}
|
||||
```
|
||||
|
||||
Now when you click on the `Posts` button, you'll notice that the UI remains responsive and you can still switch to other pages while the posts are loading. Try removing the `startTransition` wrapper around `setPage` in `changePage` to see the difference.
|
||||
5
src/data/question-groups/react/content/virtual-dom.md
Normal file
5
src/data/question-groups/react/content/virtual-dom.md
Normal file
@@ -0,0 +1,5 @@
|
||||
Virtual DOM works in this steps:
|
||||
|
||||
1. Whenever any underlying data changes, new virtual DOM representation will be created.
|
||||
2. Then the difference between the previous DOM representation and the new one is calculated.
|
||||
3. Once the calculations are done, the real DOM will be updated with only the things that have actually changed.
|
||||
@@ -169,22 +169,140 @@ questions:
|
||||
- 'Performance'
|
||||
- 'Intermediate'
|
||||
- question: Explain the concept of error boundaries in React.
|
||||
answer: |
|
||||
Error boundaries are special React components that catch JavaScript errors during rendering, in lifecycle methods, and during the constructor of whole tree below them. They are used to handle errors gracefully by displaying a fallback UI and preventing the entire application from crashing due to unhandled errors.
|
||||
answer: error-boundaries.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Advanced'
|
||||
- question: What are fragments in React?
|
||||
answer: |
|
||||
React doesn't allow returning multiple elements from a component. You can use fragments to return multiple elements.
|
||||
|
||||
|
||||
Fragments in React allow for a group of elements to be returned from a component's render method without adding an extra node to the DOM. They are useful when you want to return multiple elements without wrapping them in a parent container.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: What is `createPortal`?
|
||||
- question: What are portals in React?
|
||||
answer: create-portal.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: What is Concurrent React (Concurrent Mode)?
|
||||
answer: |
|
||||
Concurrent React, previously referred to as Concurrent Mode, is a set of new features in React that allows React to interrupt the rendering process to consider more urgent tasks, making it possible for React to be more responsive to user input and produce smoother user experiences. It lets React keep the UI responsive while rendering large component trees by splitting the rendering work into smaller chunks and spreading it over multiple frames.
|
||||
topics:
|
||||
- 'Performance'
|
||||
- 'Intermediate'
|
||||
- question: What is the `useTransition` hook?
|
||||
answer: use-transition.md
|
||||
topics:
|
||||
- 'Performance'
|
||||
- 'Advanced'
|
||||
- question: What is the purpose of `flushSync` in React?
|
||||
answer: flush-sync.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Advanced'
|
||||
- question: How to render React components as static HTML string?
|
||||
answer: |
|
||||
The `renderToString` function in React is part of the `react-dom/server` package and is used to render React components on the server-side to a static HTML string. It is commonly used for server-side rendering (SSR) in React.
|
||||
topics:
|
||||
- 'SSR'
|
||||
- 'Intermediate'
|
||||
- question: What are Server Components in React?
|
||||
answer: |
|
||||
Server Components in allow developers to write components that render on the server instead of the client. Unlike traditional components, Server Components do not have a client-side runtime, meaning they result in a smaller bundle size and faster loads. They can seamlessly integrate with client components and can fetch data directly from the backend without the need for an API layer. This enables developers to build rich, interactive apps with less client-side code, improving performance and developer experience.
|
||||
topics:
|
||||
- 'SSR'
|
||||
- 'Intermediate'
|
||||
- question: How to lazy load components in React?
|
||||
answer: lazy-loading.md
|
||||
topics:
|
||||
- 'Performance'
|
||||
- 'Intermediate'
|
||||
- question: What is `Suspense` in React?
|
||||
answer: suspense.md
|
||||
topics:
|
||||
- 'UX'
|
||||
- 'Intermediate'
|
||||
- question: How React Virtual DOM works?
|
||||
answer: virtual-dom.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: How do Server Components differ from Client Components?
|
||||
answer: Server Components are rendered on the server and do not require client-side JavaScript for rendering. While Server Components and Client components can coexist in the same app, Server Components can import and render Client components.
|
||||
topics:
|
||||
- 'SSR'
|
||||
- 'Beginner'
|
||||
- question: How do React Server Components handle data fetching?
|
||||
answer: Server Components can directly access backend resources, databases, or filesystems to fetch data during rendering, eliminating the need for a separate API layer for data fetching.
|
||||
topics:
|
||||
- 'SSR'
|
||||
- 'Beginner'
|
||||
- question: What's the component's lifecycle in React?
|
||||
answer: component-lifecycle.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: How to write a comment in React?
|
||||
answer: |
|
||||
You can write a comment in JSX by wrapping it in curly braces and using JavaScript's multi-line comment syntax.
|
||||
```js
|
||||
{/* This is a comment */}
|
||||
```
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: What is the difference between stateful and stateless components?
|
||||
answer: |
|
||||
The main difference between stateful and stateless components is one has state and the other doesn't. Stateful components keep track of changes to their state and re-render themselves when the state changes. Stateless components, on the other hand, render whatever is passed to them via `props` or always render the same thing.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: Why you shouldn't use `index` as a key in React lists and iterators?
|
||||
answer: Using `index` as a key can negatively impact performance and may cause issues with the component state. When the list items change due to additions, deletions, or reordering, using indexes can lead to unnecessary re-renders or even incorrect UI updates. React uses keys to identify elements in the list, and if the key is just an index, it might reuse component instances and state inappropriately. Especially in cases where the list is dynamic or items can be reordered, it's recommended to use unique and stable identifiers as keys to ensure consistent behavior.
|
||||
topics:
|
||||
- 'Performance'
|
||||
- 'Beginner'
|
||||
- question: What is the naming convention for React components?
|
||||
answer: In React, the naming convention for components is to use PascalCase, meaning the first letter of each word in the component's name should be capitalized. For example, `UserProfile`, `SidebarItem`, or `NavigationMenu`. This convention differentiates custom React components from regular HTML tags in JSX, as React treats elements starting with a lowercase letter as DOM tags and those starting with a capital letter as custom components.
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: How to render a list in React?
|
||||
answer: render-list.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Beginner'
|
||||
- question: What are `use client` and `use server` directives?
|
||||
answer: The `use client` directive marks source files whose components are intended to execute only on the client. Conversely, `use server` marks server-side functions that can be invoked from client-side code.
|
||||
topics:
|
||||
- 'SSR'
|
||||
- 'Intermediate'
|
||||
- question: Can you use hooks in Server Components?
|
||||
answer: No, hooks are not supported in Server Components. Hooks are a client-side feature and are not supported in Server Components. However, you can use hooks in client components and import them into Server Components.
|
||||
topics:
|
||||
- 'SSR'
|
||||
- 'Intermediate'
|
||||
- question: How to create a Custom hook in React?
|
||||
answer: custom-hook.md
|
||||
topics:
|
||||
- 'Core'
|
||||
- 'Intermediate'
|
||||
- question: What is Hydration in React?
|
||||
answer: |
|
||||
Hydration is the process of using client-side JavaScript to add interactivity to the markup generated by the server. When you use server-side rendering, the server returns a static HTML representation of the component tree. Once this reaches the browser, in order to make it interactive, React "hydrates" the static content, turning it into a fully interactive application.
|
||||
topics:
|
||||
- 'SSR'
|
||||
- 'Intermediate'
|
||||
- question: What is Strict Mode in React and why is it useful?
|
||||
answer: strict-mode.md
|
||||
topics:
|
||||
- 'Debugging'
|
||||
- 'Intermediate'
|
||||
- question: How do you investigate a slow React app and identify performance bottlenecks?
|
||||
answer: investigate-slow-app.md
|
||||
topics:
|
||||
- 'Performance'
|
||||
- 'Intermediate'
|
||||
---
|
||||
|
||||
9
src/icons/clipboard.svg
Normal file
9
src/icons/clipboard.svg
Normal file
@@ -0,0 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||
stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-clipboard-list">
|
||||
<rect width="8" height="4" x="8" y="2" rx="1" ry="1"/>
|
||||
<path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/>
|
||||
<path d="M12 11h4"/>
|
||||
<path d="M12 16h4"/>
|
||||
<path d="M8 11h.01"/>
|
||||
<path d="M8 16h.01"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 482 B |
@@ -60,15 +60,15 @@ const videos = await getAllVideos();
|
||||
}))}
|
||||
/>
|
||||
|
||||
<!--<FeaturedItems-->
|
||||
<!-- heading='Questions'-->
|
||||
<!-- allowBookmark={false}-->
|
||||
<!-- featuredItems={questionGroups.map((questionGroup) => ({-->
|
||||
<!-- text: questionGroup.frontmatter.briefTitle,-->
|
||||
<!-- url: `/questions/${questionGroup.id}`,-->
|
||||
<!-- isNew: questionGroup.frontmatter.isNew,-->
|
||||
<!-- }))}-->
|
||||
<!--/>-->
|
||||
<FeaturedItems
|
||||
heading='Questions'
|
||||
allowBookmark={false}
|
||||
featuredItems={questionGroups.map((questionGroup) => ({
|
||||
text: questionGroup.frontmatter.briefTitle,
|
||||
url: `/questions/${questionGroup.id}`,
|
||||
isNew: questionGroup.frontmatter.isNew,
|
||||
}))}
|
||||
/>
|
||||
|
||||
<div class='grid grid-cols-1 gap-7 bg-gray-50 py-7 sm:gap-16 sm:py-16'>
|
||||
<FeaturedGuides heading='Guides' guides={guides.slice(0, 7)} />
|
||||
|
||||
@@ -2,10 +2,12 @@ import { getAllBestPractices } from '../lib/best-pratice';
|
||||
import { getAllGuides } from '../lib/guide';
|
||||
import { getRoadmapsByTag } from '../lib/roadmap';
|
||||
import { getAllVideos } from '../lib/video';
|
||||
import {getAllQuestionGroups} from "../lib/question-group";
|
||||
|
||||
export async function GET() {
|
||||
const guides = await getAllGuides();
|
||||
const videos = await getAllVideos();
|
||||
const questionGroups = await getAllQuestionGroups();
|
||||
const roadmaps = await getRoadmapsByTag('roadmap');
|
||||
const bestPractices = await getAllBestPractices();
|
||||
|
||||
@@ -26,6 +28,12 @@ export async function GET() {
|
||||
title: bestPractice.frontmatter.briefTitle,
|
||||
group: 'Best Practices',
|
||||
})),
|
||||
...questionGroups.map((questionGroup) => ({
|
||||
id: questionGroup.id,
|
||||
url: `/questions/${questionGroup.id}`,
|
||||
title: questionGroup.frontmatter.briefTitle,
|
||||
group: 'Questions',
|
||||
})),
|
||||
...guides.map((guide) => ({
|
||||
id: guide.id,
|
||||
url: `/guides/${guide.id}`,
|
||||
|
||||
@@ -35,10 +35,9 @@ const { frontmatter } = questionGroup;
|
||||
description={frontmatter.seo.description}
|
||||
keywords={frontmatter.seo.keywords}
|
||||
permalink={`/questions/${questionGroup.id}`}
|
||||
noIndex={true}
|
||||
>
|
||||
<div class='flex bg-gray-50 pb-14 pt-4 sm:pb-16 sm:pt-8'>
|
||||
<div class='container !max-w-[700px]'>
|
||||
<div class='container !max-w-[740px]'>
|
||||
<div class='mb-3 sm:mb-5 mt-2 text-left sm:text-center sm:mt-8'>
|
||||
<div class='mb-2 md:mb-6'>
|
||||
<a
|
||||
|
||||
@@ -11,7 +11,6 @@ const questionGroups = await getAllQuestionGroups();
|
||||
title='Questions'
|
||||
description={'Step by step guides and paths to learn different tools or technologies'}
|
||||
permalink={'/roadmaps'}
|
||||
noIndex={true}
|
||||
>
|
||||
<SimplePageHeader
|
||||
title='Questions'
|
||||
|
||||
Reference in New Issue
Block a user