JavaScript & Node.
js Basics with MongoDB - Guide
1. JavaScript Basics
Example:
```javascript
let name = 'Alice';
const age = 25;
if (age >= 18) {
console.log('Adult');
} else {
console.log('Minor');
for (let i = 0; i < 5; i++) {
console.log(i);
function greet(name) {
return `Hello, ${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;
const gen = numberGenerator();
console.log(gen.next()); // { value: 1, done: false }
```
Sample Question:
- Create a generator function that generates an infinite sequence of numbers, starting from 1.
3. Promises
Example:
```javascript
function getData() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Data received"), 1000);
});
getData().then(result => console.log(result)).catch(error => console.error(error));
```
Sample Question:
- Write a function that returns a promise that resolves with "Success" after 2 seconds.
4. Asynchronous Programming (Async/Await)
Example:
```javascript
async function fetchData() {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
let data = await response.json();
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.
5. Map, Filter, and Reduce
Example:
```javascript
let numbers = [1, 2, 3, 4, 5];
let squares = numbers.map(num => num * num);
let evenNumbers = numbers.filter(num => num % 2 === 0);
let sum = numbers.reduce((acc, num) => acc + num, 0);
```
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;
const add = (a, b) => 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
let fruits = ["apple", "banana", "cherry"];
fruits.push("date");
let firstFruit = fruits.shift();
console.log(fruits); // ["banana", "cherry", "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
const person = { name: 'Alice', age: 25 };
const { name, age } = person;
console.log(name); // Alice
console.log(age); // 25
const numbers = [1, 2, 3];
const [first, second] = numbers;
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
const jsonData = '{"name": "Alice", "age": 25}';
const jsObject = JSON.parse(jsonData);
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.
10. Node.js Application
Example: Simple HTTP Server
```javascript
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
```
Sample Question:
- Write a Node.js application that serves an HTML file when a user visits `http://localhost:3000`.
11. MongoDB CRUD Operations
Setting up MongoDB in Node.js:
1. Install `mongodb` package:
```bash
npm install mongodb
```
Basic CRUD operations using MongoDB:
```javascript
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
const dbName = 'myDatabase';
async function main() {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('myCollection');
await collection.insertOne({ name: 'Alice', age: 25 });
const person = await collection.findOne({ name: 'Alice' });
console.log(person);
await collection.updateOne({ name: 'Alice' }, { $set: { age: 26 } });
await collection.deleteOne({ name: 'Alice' });
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,
and then delete it.