JavaScript NodeJS MongoDB Guide
JavaScript NodeJS MongoDB Guide
1. JavaScript Basics
Example:
```javascript
console.log('Adult');
} else {
console.log('Minor');
console.log(i);
function greet(name) {
console.log(greet(name));
```
Sample Question:
- Write a function that takes an array of numbers and returns the sum of all even numbers.
2. Iterators and Generators
Iterator Example:
```javascript
function makeIterator(arr) {
let index = 0;
return {
next: () => {
return index < arr.length ? { value: arr[index++], done: false } : { done: true };
};
```
Generator Example:
```javascript
function* numberGenerator() {
yield 1;
yield 2;
yield 3;
```
Sample Question:
- Create a generator function that generates an infinite sequence of numbers, starting from 1.
3. Promises
Example:
```javascript
function getData() {
});
```
Sample Question:
- Write a function that returns a promise that resolves with "Success" after 2 seconds.
Example:
```javascript
try {
console.log(data);
} catch (error) {
console.error('Error:', error);
fetchData();
```
Sample Question:
- Write an async function to fetch user data from a given URL and return the user's name.
Example:
```javascript
```
Sample Question:
- Given an array of numbers, use `map` to double each number, then use `filter` to keep only even
numbers, and finally use `reduce` to get the sum of the remaining numbers.
6. Functions
Example:
```javascript
function multiply(a, b) {
return a * b;
console.log(multiply(3, 4)); // 12
console.log(add(3, 4)); // 7
```
Sample Question:
- Write a function that takes a list of numbers and returns an array with each number squared.
7. Arrays
Example:
```javascript
fruits.push("date");
console.log(firstFruit); // "apple"
```
Sample Question:
- Write a function that takes an array and a value, then removes all instances of that value from the
array.
8. Destructuring
Example:
```javascript
console.log(name); // Alice
console.log(age); // 25
console.log(first, second); // 1 2
```
Sample Question:
- Given an object with properties `name`, `age`, and `country`, destructure these properties into
individual variables.
9. JSON
Example:
```javascript
console.log(jsObject);
const jsonString = JSON.stringify(jsObject);
console.log(jsonString);
```
Sample Question:
- Convert a JavaScript object with properties `title`, `author`, and `year` into JSON format.
```javascript
res.end('Hello, World!');
});
server.listen(3000, () => {
});
```
Sample Question:
- Write a Node.js application that serves an HTML file when a user visits `http://localhost:3000`.
```bash
```
```javascript
await client.connect();
const db = client.db(dbName);
console.log(person);
main().catch(console.error);
```
Sample Question:
- Write a Node.js script to insert a new document, find it by a specific field, update one of its fields,