let score = 100 + 3;
let highScore = 100 / 2;
let age = 20;
score + age;
let greeting = 'Hello World, Welcome to RST Forum.';
greeting.toLowerCase().indexOf('hello');
// let cart = 10;
// let message = 'You have ' + cart + ' items in your cart.';
// let username = 'john123';
// let hello = `Hello There,
// This is a multi-line
// string.`;
// let message2 = `Hello $${username.toUpperCase()}, You have ${
// (cart * 2) / 2
// } items in your cart`;
// console.log(message2);
// console.log(hello);
// let highScore = null;
// let score;
// console.log(highScore);
// console.log(score);
// 'hello world'[100];
// console.log(Math.PI);
// Math.floor(Math.random() * 10) + 1;
// let age = 85;
// if (age > 21) {
// console.log('Welcome');
// }
// let num = 97;
// if (num % 2 === 0) {
// console.log('This number is EVEN.');
// } else {
// console.log('This number is ODD');
// }
// let age = 22;
// if (age >= 65) {
// console.log('Drinks are free.');
// } else if (age >= 21) {
// console.log('You are allowed to enter and drink.');
// } else if (age >= 18) {
// console.log('You are allowed to enter but you cannot drink.');
// } else {
// console.log('Access denied.');
// }
// let age = 65;
// if (age > 18) {
// console.log('Entry Granted!');
// } else if (age >= 21) {
// console.log('Drinks Allowed');
// } else if (age >= 65) {
// console.log('Drinks FREE!');
// }
// if (age > 18) {
// if (age >= 65) {
// console.log('Drinks are free');
// } else if (age >= 21) {
// console.log('Drinks allowed');
// } else {
// console.log('You can enter');
// }
// } else {
// console.log('You cannot enter');
// }
// let password = 'hello world@123';
// if (password.length >= 6) {
// if (password.indexOf(' ') !== -1) {
// console.log('Password cannot include spaces');
// } else {
// console.log('Valid Password');
// }
// } else {
// console.log('Invalid password. Min 6 chars required.');
// }
// let username = 'john123';
// if (username) {
// console.log('Access granted');
// } else {
// console.log('Access denined');
// }
let age = 22;
if (age >= 65) {
console.log('Drinks are free.');
} else if (age >= 21) {
console.log('You are allowed to enter and drink.');
} else if (age >= 18) {
console.log('You are allowed to enter but you cannot drink.');
} else {
console.log('Access denied.');
}
if (age >= 18 && age < 21) {
onsole.log('You are allowed to enter but you cannot drink.');
} else if (age >= 21 && age < 65) {
console.log('You are allowed to enter and drink.');
} else if (age > 65) {
console.log('Drinks are free.');
} else {
console.log('Access denied.');
}
// if (day === 1) {
// console.log('Monday');
// } else if (day === 2) {
// console.log('Tuesday');
// } else if (day === 3) {
// console.log('Tuesday');
// }
// let day = 10;
// switch (day) {
// case 1:
// console.log('Mon');
// break;
// case 2:
// console.log('Tue');
// break;
// case 3:
// console.log('Wed');
// break;
// case 4:
// console.log('Thu');
// break;
// case 5:
// console.log('Fri');
// break;
// case 6:
// console.log('Sat');
// break;
// case 7:
// console.log('Sun');
// break;
// default:
// console.log('Invalid day no.');
// }
// let num = 12;
// if (num === 13) {
// console.log('Lucky');
// } else if (num === 17) {
// console.log('Even luckier');
// } else {
// console.log('Unlucky');
// }
// num === 13
// ? console.log('Lucky')
// : num === 17
// ? console.log('Even luckier')
// : console.log('Unlucky');
let status = 'offline';
let color = status === 'offline' ? 'red' : 'green';
console.log(color);
// const product1 = ['Apple', 'iPhone', 100000, 100, 'Some description'];
// const product2 = ['Nord X', 'One Plus', 60000, 3000, 'Some description again'];
// const product3 = ['Apple', 'iPhone', 100, 100000, 'Some description'];
// const products = [product1, product2];
// console.log(products);
// product1[0];
// const product4 = {
// name: 'iPhone',
// price: 100000,
// brand: 'Apple',
// inStock: 100,
// description: 'Some description',
// 'hello world': 'Good',
// 1000: 'xxxxxxx',
// };
// console.log(product1[0]);
// console.log(product4.name);
// console.log(product4['hello world']);
// console.log(product4[1000]);
// const nums = ['John', 'Jack', 'Jane', 'James'];
const nums2 = {
0: 'John',
1: 'Jack',
2: 'Jane',
3: 'James',
'-1': 'sadsad',
length: 4,
};
console.log(nums2['0']);
// let name = 'John Doe';
// let age = 20;
// let names = ['John Doe', 'Jane Doe', 'Jack Doe'];
// // let product = ['iPhone', 'Apple', 100000, 25];
// // console.log(product[0]);
// // console.log(product[2]);
// // let product = {
// // price: 100000,
// // brand: 'Apple',
// // name: 'iPhone',
// // inStock: 25,
// // };
// // product.description = 'Some information about...';
// // product.name = 'iPhone 13';
// // product['price'] = 10000;
// // console.log(product);
// // console.log(product.name);
// // console.log(product.price);
// const playlist = [
// {
// name: 'Some song #1',
// artist: ['Artist #1', 'Artist #2'],
// trackTime: 3.12,
// metadata: {
// label: 'T-series',
// id: 213213213,
// },
// },
// {
// name: 'Some song #1',
// artist: ['Artist #1', 'Artist #2'],
// trackTime: 3.12,
// metadata: {
// label: 'T-series',
// id: 213213213,
// },
// },
// {
// name: 'Some song #1',
// artist: ['Artist #1', 'Artist #2'],
// trackTime: 3.12,
// metadata: {
// label: 'T-series',
// id: 213213213,
// },
// },
// {
// name: 'Some song #1',
// artist: ['Artist #1', 'Artist #2'],
// trackTime: 3.12,
// metadata: {
// label: 'T-series',
// id: 213213213,
// },
// },
// ];
// // JSON
// // console.log(playlist[0].name);
// console.log(playlist[0].artist[0].toUpperCase());
// for (let i = 0; i < 10; i++) {
// console.log(`${i} - Hello World`);
// }
// for (let i = 100; i > 0; i += 10) {
// console.log(`${i} - Hello World`);
// }
// const nums = [12, 34, 56, 34, 78, 54, 23, 12];
// for (let i = 0; i < nums.length; i++) {
// console.log(nums[i]);
// }
// const movies = [
// { movieName: 'Inception', rating: 3.8 },
// { movieName: 'Avengers', rating: 3.4 },
// { movieName: 'Iron Man', rating: 2.9 },
// ];
// for (let i = 0; i < movies.length; i++) {
// let movie = movies[i];
// console.log(`${movie.movieName} has a rating of ${movie.rating}`);
// }
// const word = 'Hello World';
// let reveredWord = '';
// for (let i = word.length - 1; i >= 0; i--) {
// // console.log(word[i]);
// reveredWord += word[i];
// }
// console.log(reveredWord);
// for (let i = 1; i <= 5; i++) {
// console.log(i + ' OUTER');
// for (let j = 1; j <= 3; j++) {
// console.log(' ' + j + ' INNER');
// }
// }
// const gameBoard = [
// [4, 64, 8, 4],
// [128, 32, 4, 16],
// [16, 4, 4, 32],
// [2, 16, 16, 2],
// ];
// for (let i = 0; i < gameBoard.length; i++) {
// for (let j = 0; j < gameBoard[i].length; j++) {
// console.log(gameBoard[i][j]);
// }
// }
// const gameBoard = [
// [
// [4, 64, 8, 4],
// [4, 64, 8, 4],
// [4, 64, 8, 4],
// [4, 64, 8, 4],
// ],
// [
// [4, 64, 8, 4],
// [4, 64, 8, 4],
// [4, 64, 8, 4],
// [4, 64, 8, 4],
// ],
// [
// [4, 64, 8, 4],
// [4, 64, 8, 4],
// [4, 64, 8, 4],
// [4, 64, 8, 4],
// ],
// [
// [4, 64, 8, 4],
// [4, 64, 8, 4],
// [4, 64, 8, 4],
// [4, 64, 8, 4],
// ],
// ];
// for (let i = 0; i < 10; i++) {
// console.log(i);
// }
// console.log(i);
// let j = 0;
// while (j < 10) {
// console.log(j);
// j++;
// }
// let randomNumber = Math.floor(Math.random() * 100) + 1;
// let guess = Math.floor(Math.random() * 100) + 1;
// while (guess !== randomNumber) {
// console.log(`Random Num: ${randomNumber} | Guess: ${guess}`);
// guess = Math.floor(Math.random() * 100) + 1;
// }
// console.log(`Random Num: ${randomNumber} | Guess: ${guess}`);
// let str = 'abcdefghijklmnopqrstuvwxyz1234567890';
// let randomNum = Math.floor(Math.random() * str.length - 1);
// console.log(str[randomNum]);
let randomNumber = Math.floor(Math.random() * 100000) + 1;
let guess = Math.floor(Math.random() * 100000) + 1;
while (true) {
if (guess === randomNumber) {
console.log("Awesome you've guessed it.");
break;
}
console.log(`Random Num: ${randomNumber} | Guess: ${guess}`);
guess = Math.floor(Math.random() * 100000) + 1;
}
console.log(`Random Num: ${randomNumber} | Guess: ${guess}`);
let num = 10;
let x = 5;
15;
let result = 20;
undefined;
// let highScoreOfPlayerOne = 10;
// let player1Score = 10;
// let GST_RATE = 18;
// let $highScore = 10;
// let _highScore = 10;
// let high_score = 10;
// let if = 10
// let num1 = 1;
// let num2 = '1';
// let result = num1 + num2;
// console.log(result);
let greeting = 'Hello World, Welcome to RST Forum.';
console.log(greeting.toUpperCase());
console.log(greeting.toLowerCase());
// Ctrl + `
// ls
// const arr = ['john', 'jane', 'jack', 'james', 'jim'];
// for (let i = 0; i < arr.length; i++) {
// console.log(arr[i]);
// }
// let c = 0;
// while (c < arr.length) {
// console.log(arr[c]);
// c++;
// }
const arr = ['john', 'jane', 'jack', 'james', 'jim'];
// for (let name of arr) {
// console.log(name);
// }
// let total = 0;
// for (let num of [1, [1, 2, 3, 4], 3, 4, 5, 6, 7]) {
// if (typeof num === 'number') {
// total += num;
// } else if (typeof num === 'object') {
// let localTotal = 0;
// for
// }
// }
// console.log(total);
// for (let char of 'Hello World') {
// console.log(char.toUpperCase());
// }
// const matrix = [
// [1, 4, 7],
// [9, 7, 2],
// [9, 4, 6],
// ];
// let total = 0;
// for (let row of matrix) {
// for (let item of row) {
// total += item;
// }
// }
// console.log(total);
// const cats = ['fashion', 'mobiles', 'books'];
// const prods = ['tshirt', 'samsung', '1984'];
// for (let i = 0; i <= cats.length; i++) {
// console.log(cats[i], prods[i]);
// }
// const productPrices = {
// Apple: 80000,
// OnePlus: 50000,
// Samsung: 90000,
// };
// for (let product of Object.keys(productPrices)) {
// console.log(`${product} - ${productPrices[product]}`);
// }
// for (let product in productPrices) {
// console.log(productPrices[product]);
// }
// function sayHello() {
// console.log('Hello World');
// console.log('Hello Universe');
// }
// for (let i = 0; i < 50; i++) {
// sayHello();
// sayHello();
// }
function rollDie() {
let roll = Math.floor(Math.random() * 6) + 1;
console.log(`Rolled: ${roll}`);
}
// for (let i = 0; i < 3; i++) {
// rollDie();
// }
// function throwDice() {
// rollDie();
// rollDie();
// rollDie();
// }
// throwDice();
// function sayHello(name) {
// console.log(`Hello ${name}`);
// }
// sayHello('John');
// sayHello('Jane');
// sayHello('Jack');
// function throwDice(times) {
// for (let i = 0; i < times; i++) {
// rollDie();
// }
// }
// throwDice(10);
// function printMessage(message, name) {
// console.log(`${message} ${name}`);
// }
// printMessage();
function add(num1, num2) {
// console.log(num1 + num2);
return num1 + num2;
}
// let result = add();
// console.log(result);
// console.log(add('a', 'b'));
// console.log(result);
// console.log(add(10, 40));
// add(10, 5);
function isNumber(val) {
if (typeof val !== 'number') {
return false;
// console.log('Hello World');
// console.log('Hello World');
// console.log('Hello World');
// console.log('Hello World');
} else {
return true;
}
}
console.log(isNumber('hello'));
// let fullName = 'Jack Doe';
// function sayHello() {
// let fullName = 'Jane Smith';
// console.log(fullName);
// }
// sayHello();
// console.log(fullName);
// if (true) {
// // let first_name = 'John';
// // const last_name = 'Doe';
// // console.log(first_name + ' ' + last_name);
// var fullName = 'John Doe';
// console.log(fullName);
// }
// console.log(first_name, last_name);
// if (true) {
// var fullName = 'John Doe';
// console.log(fullName);
// }
// console.log(fullName);
// for (var i = 0; i < 10; i++) {
// console.log(i);
// }
// console.log(i);
// let movie = 'Inception';
// function outer() {
// // let movie = 'Avengers';
// function inner() {
// let movie = 'John Wick';
// let ratings = `${movie} has a rating of 4.2`;
// console.log(ratings);
// }
// console.log(rating);
// inner();
// }
// outer();
// let score = 100;
// function sayHello() {
// console.log('Hello World');
// }
// function square(num) {
// return num * num;
// }
// console.log(square(10));
// const square = function (num) {
// return num * num;
// };
// console.log(square(10));
// const arr = [
// 10,
// true,
// function () {
// return "I'm inside an array";
// },
// ];
// console.log(arr[0]);
// console.log(arr[1]);
// console.log(arr[2]());
// const math = {
// pi: 3.1415,
// add: function (a, b) {
// return a + b;
// },
// sub: function (a, b) {
// return a - b;
// },
// mul: function (a, b) {
// return a * b;
// },
// };
// console.log(math.pi);
// console.log(math.add(10, 5));
// function hello() {
// // console.log('Hello World');
// return 'Hello World';
// }
// const world = hello;
// // const hello2 = hello;
// // console.log(hello2());
// console.log(world());
// function mul() {
// }
// function mul(a, b) {
// return a * b;
// }
// const operations = {
// add: function (a, b) {
// return a + b;
// },
// sub: function (a, b) {
// return a - b;
// },
// mul: mul,
// };
// console.log(operations.add(10, 2));
// console.log(operations.mul(10, 2));
// console.log(operations.sub(10, 2));
// function add(x, y) {
// return x + y;
// }
// const sub = function (x, y) {
// return x - y;
// };
// const mul = function (x, y) {
// return x * y;
// };
// function div(x, y) {
// return x / y;
// }
// const operations = [add, sub, mul, div];
// console.log(operations[0](10, 2));
function math(a, b, fn) {
return fn(a, b);
}
// function sub(a, b) {
// return a - b;
// }
console.log(
math(10, 5, function (a, b) {
return a - b;
})
);
// const add = function (a, b) {
// return a + b;
// };
// // add(10, 5);
// function math(a, b, fn) {
// return fn(a, b);
// }
// // console.log(
// // math(10, 5, function (a, b) {
// // return a + b;
// // })
// // );
// console.log(math(10, 12, add));
// function multipleGreets(fn) {
// fn();
// fn();
// fn();
// }
// function sayHello() {
// console.log('Hello World!');
// }
// function sayGoodbye() {
// console.log('Bye World!');
// }
// multipleGreets(sayHello);
// multipleGreets(sayGoodbye);
// function repeat(func, num) {
// for (let i = 0; i < num; i++) {
// func();
// }
// }
// function sayHello() {
// console.log('Hello World!');
// }
// function sayGoodbye() {
// console.log('Bye World!');
// }
// repeat(sayHello, 10);
// repeat(sayGoodbye, 5);
// function randomPick(f1, f2) {
// let randNum = Math.random();
// if (randNum < 0.5) {
// f1();
// } else {
// f2();
// }
// }
// randomPick(sayHello, sayGoodbye);
// function raiseBy(num) {
// return function (x) {
// return x ** num;
// };
// }
// const square = raiseBy(2);
// const cube = raiseBy(3);
// console.log(square(5));
// console.log(cube(5));
// function isBetween(x, y) {
// return function (num) {
// return num >= x && num <= y;
// };
// }
// const isUnderage = isBetween(1, 18);
// const isAllowed = isBetween(18, 21);
// const isLegal = isBetween(24, 65);
// const freeDrinks = isBetween(65, 100);
// console.log(freeDrinks(90));
// function logHello() {
// console.log('Hello after 2 seconds');
// }
// setTimeout(logHello, 2000);
// logHello();
// setTimeout(function () {
// console.log('Hello World');
// }, 2000);
// function greet() {
// console.log('Hello World');
// }
// greet();
// console.log(fullName);
// var fullName = 'John Doe';
// console.log(fullName);
// console.log(fullName);
// let fullName = 'Jane Doe';
// const nums = [9, 2, 4, 6, 2, 3, 7, 6];
// for (let num of nums) {
// console.log(num);
// }
// for (let i = 0; i < nums.length; i++) {
// console.log(i, nums[i]);
// }
// const nums = [9, 2, 4, 6, 2, 3, 7, 6];
// nums.forEach(function (n) {
// console.log(n);
// });
// nums.forEach();
// const names = ['john', 'jane', 'jack', 'james'];
// names.forEach(function (name, i) {
// console.log(i, name.toUpperCase());
// });
// nums.forEach(function (n, i) {
// if (n % 2 === 0) {
// console.log(n, i);
// }
// });
// for (let num of nums) {
// if (num % 2 === 0) {
// console.log(num);
// }
// }
// const movies = [
// {
// title: 'Avengers',
// rating: 4.1,
// },
// {
// title: 'Dr. Strange',
// rating: 3.9,
// },
// {
// title: 'Tenet',
// rating: 4.3,
// },
// {
// title: 'Joker',
// rating: 4.7,
// },
// ];
// movies.forEach(function (movie) {
// console.log(`${movie.title.toUpperCase()} has a rating of ${movie.rating}`);
// });
// // Using for..of loop
// for (let movie of movies) {
// console.log(movie.title.toUpperCase())
// }
// // if we want the index no.
// // second arg is the index value
// movies.forEach(function (movie, idx) {
// console.log(idx, movie.title)
// })
// const names = ['john', 'jack', 'jane', 'james'];
// // const newNames = names.map(function (name, idx) {
// // return `${idx} - ${name.toUpperCase()}`;
// // });
// const uppercasedNames = names.map(name => name.toUpperCase())
// console.log(uppercasedNames)
// console.log(newNames);
// const nums = [2, 3, 4, 7, 6, 8, 13, 10, 19, 12, 14, 22, 21, 16];
// const doubles = nums.map(function (num) {
// return num * 2;
// });
// const doubles = nums.map(num => num * 2);
// console.log(doubles);
// const numDetails = nums.map(function (num) {
// return {
// number: num,
// isEven: num % 2 === 0,
// };
// });
// console.log(numDetails);
// const square = function (num) {
// return num ** 2;
// };
// const square = (num) => {
// return num ** 2;
// };
// const square = num => {
// return num ** 2;
// }
// const square = num => num ** 2;
// console.log(square(5));
// const greet = () => {
// console.log('Hello World')
// }
// greet();
// const greet = name => {
// console.log(`Hello, ${name}`)
// }
// const greet = (name, message) => {
// console.log(`${message}, ${name}`)
// }
// greet("John", "Hi");
// const nums = [1,2,3,4,5,6]
// // using regular function expressions
// const doubles1 = nums.map(function (n) {
// return n * 2
// })
// // using arrow functions
// const doubles2 = nums.map(n => {
// return n * 2
// })
// // using arrow function's one-liner implicit return
// const doubles3 = nums.map(n => n * 2)
// const parityList = nums.map(n => n % 2 === 0 ? 'Even' : 'Odd')
// console.log(parityList)
let movies = ['The Terminator', 'The Avengers', 'Jurassic Park', 'Titanic'];
// let movie1 = movies.find((movie) => movie === 'The Avengers');
let movie1 = movies.find((movie) => movie.includes('e'));
console.log(movie1);
// const books = [
// {
// title: 'The Shining',
// author: 'Stephen King',
// rating: 4.1,
// },
// {
// title: 'Sacred Games',
// author: 'Vikram Chandra',
// rating: 4.5,
// },
// {
// title: '1984',
// author: 'George Orwell',
// rating: 4.9,
// },
// {
// title: 'The Alchemist',
// author: 'Paulo Coelho',
// rating: 3.5,
// },
// {
// title: 'The Great Gatsby',
// author: 'F. Scott Fitzgerald',
// rating: 3.8,
// },
// ];
// // const result = books.find(function (movie) {
// // return movie.rating < 4;
// // });
// const result = books.filter((movie) => movie.rating < 4);
// console.log(result);
// const nums = [9, 8, 3, 4, 6, 12, 17, 23, 0];
// const odds = nums.filter((num) => num % 2 !== 0);
// console.log(odds);
// const bigNums = nums.filter((n) => n > 10);
// console.log(bigNums);
// const books = [
// {
// title: 'The Shining',
// author: 'Stephen King',
// rating: 4.1,
// },
// {
// title: 'Sacred Games',
// author: 'Vikram Chandra',
// rating: 4.5,
// },
// {
// title: '1984',
// author: 'George Orwell',
// rating: 4.9,
// },
// {
// title: 'The Alchemist',
// author: 'Paulo Coelho',
// rating: 3.5,
// },
// {
// title: 'The Great Gatsby',
// author: 'F. Scott Fitzgerald',
// rating: 3.8,
// },
// ];
// const goodBook = books.filter((b) => b.rating >= 4.3);
// const georgeBooks = books.filter((b) => b.author.includes('George'));
// const lowRated = books.filter((book) => {
// return book.rating < 4;
// });
// let query = 'the';
// const filteredBooks = books.filter((book) => {
// return book.title.toLowerCase().includes(query.toLowerCase());
// });
// console.log(goodBook);
// console.log(georgeBooks);
// console.log(lowRated);
// console.log(filteredBooks);
// const names = ['jack', 'james', 'john', 'jane', 'josh', 'brad'];
// const result = names.every((name) => name[0] !== 'j');
// console.log(result);
// const books = [
// {
// title: 'The Shining',
// author: 'Stephen King',
// rating: 4.1,
// },
// {
// title: 'Sacred Games',
// author: 'Vikram Chandra',
// rating: 4.5,
// },
// {
// title: '1984',
// author: 'George Orwell',
// rating: 4.9,
// },
// {
// title: 'The Alchemist',
// author: 'Paulo Coelho',
// rating: 4.1,
// },
// {
// title: 'The Great Gatsby',
// author: 'F. Scott Fitzgerald',
// rating: 4.0,
// },
// ];
// const bestBooks = books.every((book) => book.rating >= 4);
// const notAuthor = books.every(
// (book) => book.author.toLowerCase() !== 'chetan bhagat'
// );
// console.log(bestBooks);
// console.log(notAuthor);
// const names = ['jack', 'james', 'john', 'jane', 'josh', 'brad'];
// console.log(names.some((name) => name[0] === 'x'));
// const names = ['walter', 'john', 'alan', 'bob', 'harry'];
// names.sort();
// console.log(names);
// const prices = [500.4, 211, 23, 5, 4, 22.2, -23.2, 9233];
// prices.sort((a, b) => a + b);
// console.log(prices);
// console.log(books.sort((a, b) => a.rating - b.rating));
// const nums = [1, 2, 3, 4, 5, 6];
// const result = nums.reduce((acc, currVal) => {
// return acc - currVal;
// });
// console.log(result);
// acc current val
// 1 2
// 3 3
// 6 4
// 10 5
// 15 6
// 21
// let nums = [21, 221, 2, 1, 34, 123, 4342, 56, 4];
// const maxVal = nums.reduce((acc, currentVal) => {
// if (currentVal > acc) {
// return currentVal;
// }
// return acc;
// });
// console.log(maxVal);
// // acc currVal
// // 21 221
// // 221 2
// // 221 1
// // 221 34
// // 221 123
// // 221 4342
// // 4342
// const maxVal = nums.reduce((max, currVal) => Math.max(max, currVal));
// console.log(maxVal);
// const nums = [1, 2, 3, 4, 5, 6];
// console.log(nums.reduce((acc, currVal) => acc + currVal, 100));
// function multiply(a, b) {
// return a * b;
// }
// const multiply = (a = 1, b = 1) => a * b;
// console.log(multiply());
// const greet = (name, message = 'hi') => `${message}, ${name}`;
// console.log(greet('Jack'));
// function multiply(a, b) {
// console.log(arguments);
// }
// multiply();
// const nums = [10, 20, 45, 67, 1, 23, 100];
// console.log(Math.min(...nums));
// function printVals(a, b, c) {
// console.log(a);
// console.log(b);
// console.log(c);
// }
// const names = ['Jane', 'John', 'Jack'];
// // printVals(...names);
// printVals(...'John');
// const moderator = { canEdit: true, authority: 5 };
// const user = { canView: true, authority: 2.5 };
// const admin = {};
// let userInfo = {
// isLoggedIn: false,
// lastLoggedIn: '12/12/2022',
// something: true,
// };
// userInfo = { ...userInfo, isLoggedIn: true };
// function add(...nums) {
// return nums.reduce((acc, currVal) => acc + currVal);
// }
// console.log(add(10, 5, 10, 25, 12, 10));
function greet(a, b, ...names) {
console.log(a);
console.log(b);
console.log(names);
}
greet('John', 'Jane', 'Jack', 'Jim', 'James', 'Joe', 'Jin');
// const users = ['john', 'jane', 'jack'];
// // const admin = users[0];
// // const mod = users[1];
// // const sub = users[2];
// // const [admin, mod, sub] = users;
// // const [admin, ...others] = users;
// const [admin, , sub] = users;
// console.log(admin);
// // console.log(others);
// // console.log(mod);
// console.log(sub);
// const user = {
// firstName: 'John',
// lastName: 'Doe',
// email: 'john.doe@gmail.com',
// phone: 99982234567,
// };
// const { firstName, email: emailAddress } = user;
// console.log(firstName);
// // console.log(lastName);
// console.log(emailAddress);
// // console.log(phone);
// const profile = {
// name: 'John Doe',
// age: 25,
// job: 'Full Stack Dev',
// company: 'Google',
// };
// // function printData(user) {
// // console.log(`My name is ${user.name} and I am ${user.age} years old.`);
// // console.log(`I work as a ${user.job} at ${user.company}.`);
// // }
// function printData({ name, age, job, company }) {
// console.log(`My name is ${name} and I am ${age} years old.`);
// console.log(`I work as a ${job} at ${company}.`);
// }
// printData(profile);
// const movieReviews = [4.5, 5.0, 3.2, 2.1, 4.7, 3.8, 3.1, 3.9, 4.4];
// const highest = Math.max(...movieReviews);
// const lowest = Math.min(...movieReviews);
// let total = 0;
// movieReviews.forEach((rating) => (total += rating));
// const average = total / movieReviews.length;
// const info1 = {
// highest,
// lowest,
// average,
// };
// console.log(info1);
// const username = 'janedoe';
// const role = 'admin';
// const user = {
// [role.toUpperCase()]: username,
// [1 + 2 + 3]: 'test',
// };
// console.log(user);
// const addProperty = (obj, k, v) => {
// return { ...obj, [k]: v };
// };
// console.log(addProperty({ name: 'john' }, 'age', 20));
// function cube(x) {
// return x * x * x;
// }
// const math = {
// multiply: function (x, y) {
// return x * y;
// },
// divide: function (x, y) {
// return x / y;
// },
// square: function (x) {
// return x * x;
// },
// cube,
// };
// const math = {
// multiply(x, y) {
// return x * y;
// },
// divide(x, y) {
// return x / y;
// },
// square(x) {
// return x * x;
// },
// cube,
// };
// console.log(math.multiply(10, 2));
// console.log(math.square(10));
// console.log(math.cube(3));
// console.log('Hello Worlds');
function namaste() {
console.log(this);
// console.log('Hello World');
}
var helloworld = '123';
console.log(this);
const profile = {
name: 'John Doe',
age: 25,
greet: function () {
// console.log(this);
console.log(this.name);
},
};
// // namaste();
// profile.greet();
// // function fullName() {
// // return `${this.firstName} ${this.lastName} is an ${this.role}`;
// // }
// // const user = {
// // firstName: 'John',
// // lastName: 'Doe',
// // role: 'admin',
// // fullName() {
// // return `${this.firstName} ${this.lastName} is an ${this.role}`;
// // },
// // logDetails() {
// // console.log(`${this.fullName()} and is cool!`);
// // },
// // };
// // const logDetails = user.logDetails;
// // user.logDetails();
// // logDetails();
// // user.logDetails();
// // const user2 = {
// // firstName: 'Jane',
// // lastName: 'Smith',
// // role: 'moderator',
// // fullName,
// // };
// // user.fullName();
// // user2.fullName();
// // user2.introduce();
// const hellos = {
// messages: [
// 'hello world',
// 'hello universe',
// 'hello darkness',
// 'hello hello',
// 'heylo',
// ],
// pickMsg() {
// const index = Math.floor(Math.random() * this.messages.length);
// return this.messages[index];
// },
// start() {
// setInterval(() => console.log(this.pickMsg()), 1000);
// },
// };
// const user = {
// firstName: 'John',
// lastName: 'Doe',
// role: 'admin',
// fullName: () => {
// console.log(`${this.firstName} ${this.lastName} is an ${this.role}`);
// },
// };
// user.fullName();
// // console.log(hellos.pickMsg());
// // hellos.start();
/* <html>
<head>
<title></title>
</head>
<body>
<header>
<h1></h1>
</header>
<footer>
<p></p>
</footer>
</body>
</html>;
window = {
document: {
head: {
title: {},
},
body: {
header: {
h1: {},
},
footer: {
p: {},
},
},
},
}; */
// const title = document.getElementById('title');
// const paras = document.getElementsByTagName('p');
// const els = document.getElementsByClassName('special');
// console.dir(title.innerText);
// title.innerText = 'Hello World';
// setInterval(function () {
// title.innerText = Math.random();
// }, 500);
// console.dir(els);
// const ul = document.getElementsByTagName('ul')[0];
// const res = ul.getElementsByClassName('john');
// console.log(res);
// const title = document.querySelector('#title');
// const paras = document.querySelectorAll('p');
// const els = document.querySelectorAll('.special');
// console.dir(els);
// console.log(title.innerText);
// title.innerText = 'Hello World';
// const ul = document.querySelector('ul');
// // console.log(ul.innerText);
// ul.innerText = 'Hello World';
// const spc = document.querySelector('.spc');
// console.log(spc.textContent);
const title = document.querySelector('#title');
// console.log(title.innerHTML);
setInterval(function () {
title.innerHTML = Math.random();
}, 50);
// const title = document.querySelector('.special');
// title.innerHTML = 'This is <u>some</u> test title';
// const link = document.querySelector('a');
// link.href = 'https://msn.com';
// const img = document.querySelector('img');
// // console.log(img.src);
// // console.log(img.alt);
// img.alt = 'New alternative text';
// const input = document.querySelector('input');
// // console.dir(input.id);
// // console.log(input.getAttrit.setAttribute('type', 'cbute('id'));
// // console.log(input.getAttribute('max'));
// input.max = 500;
// input.setAttribute('min', '-100');
// input.setAttribute('type', 'checkbox');
// input.type = 'radio';
// const li = document.querySelector('li');
// console.dir(li.parentElement.parentElement.parentElement);
// const ul = document.querySelector('ul');
// console.log(ul.children[2].previousElementSibling);
// const el = document.querySelector('.john');
// console.log(el.nextElementSibling.nextElementSibling);
// const lis = document.querySelectorAll('li');
// console.log(lis);
// for (let li of lis) {
// li.innerText = 'CHANGED';
// }
// const al = document.querySelector('.john');
// al.style.color = 'red';
// al.style.textDecoration = 'underline';
// console.log(al.style);
// al.style.backgroundColor = 'yellow';
// al.style.
// const lis = document.querySelectorAll('li');
// const colors = ['red', 'yellow', 'green', 'orange', 'teal'];
// for (let li of lis) {
// li.style.color = colors[Math.floor(Math.random() * colors.length)];
// }
// const al = document.querySelector('.john');
// const alStyles = getComputedStyle(al);
// // console.log(al.style.color);
// // console.log(al.style.textDecoration);
// console.log(alStyles.textDecoration);
// al.style.fontSize = '100px';
// const lis = document.querySelectorAll('li');
// // lis[1].setAttribute('class', 'todo done');
// const secondLi = lis[1];
// // console.log(secondLi.classList);
// // secondLi.classList.add('done');
// // lis[0].classList.remove('done');
// lis[0].classList.toggle('done');
// lis[1].classList.toggle('done');
// const heading = document.createElement('h1');
// heading.innerText = 'This is a title';
// heading.style.color = 'red';
// // <h1 style="color: red">This is a title</h1>
// const section = document.createElement('section');
// section.style.border = '5px solid red';
// // <section style="border: 5px solid red"></section>
// section.appendChild(heading);
// // <section style="border: 5px solid red">
// // <h1 style="color: red">This is a title</h1>
// // </section>
// const div = document.querySelector('#root');
// div.appendChild(section);
// const ul = document.querySelector('ul');
// const li = document.createElement('li');
// li.innerText = 'This is NEW';
// // ul.appendChild(li);
// const secondLi = document.querySelectorAll('li')[1];
// ul.insertBefore(li, secondLi);
// const p = document.querySelector('p');
// const b = document.createElement('b');
// b.innerText = 'WORLD';
// const i = document.createElement('i');
// i.innerText = 'UNIVERSE';
// p.insertAdjacentElement('beforebegin', b);
// p.insertAdjacentElement('afterbegin', b);
// p.insertAdjacentElement('beforeend', b);
// p.insertAdjacentElement('afterend', b);
// p.append(b, i);
// p.prepend(b, i);
const ul = document.querySelector('ul');
const secondLi = document.querySelectorAll('li')[1];
// console.log(secondLi);
// ul.removeChild(secondLi);
secondLi.remove();
// const btn = document.querySelector('button');
// btn.onclick = () => {
// console.log('Hello World');
// };
// btn.onclick = () => {
// console.log('This is some sample text');
// };
// btn.addEventListener('click', () => {
// console.log('Hello World');
// });
// btn.addEventListener('click', () => {
// console.log('Something else');
// });
// btn.addEventListener('mouseout', () => {
// console.log('I was hovered');
// });
// window.addEventListener('scroll', () => {
// console.log('I am scrolling');
// });
// const btn = document.querySelector('button');
// btn.addEventListener('mouseover', function () {
// const height = Math.floor(Math.random() * window.innerHeight);
// const width = Math.floor(Math.random() * window.innerWidth);
// btn.style.left = `${width}px`;
// btn.style.top = `${height}px`;
// });
// btn.addEventListener('click', function () {
// btn.innerText = 'You Won!';
// document.body.style.backgroundColor = 'green';
// });
// const inp = document.querySelector('input');
// const list = document.querySelector('ul');
// inp
// const colors = [
// 'red',
// 'orange',
// 'yellow',
// 'green',
// 'blue',
// 'purple',
// 'indigo',
// 'violet',
// ];
// const container = document.querySelector('#boxes');
// container.style.display = 'flex';
// const span = document.querySelector('span');
// const printColor = function () {
// span.innerText = this.style.backgroundColor;
// span.style.color = this.style.backgroundColor;
// };
// for (let color of colors) {
// const box = document.createElement('div');
// box.style.backgroundColor = color;
// box.style.height = '100px';
// box.style.width = '100px';
// box.addEventListener('click', printColor);
// container.appendChild(box);
// }
// const btn = document.querySelector('button');
// btn.addEventListener('mouseover', function (event) {
// console.dir(event.target);
// });
// const inp = document.querySelector('input');
// const h1 = document.querySelector('h1');
// inp.addEventListener('keyup', function (e) {
// console.log(e.key);
// });
// inp.addEventListener('input', function (e) {
// h1.innerText = e.target.value;
// });
// const inp = document.querySelector('input');
// const ul = document.querySelector('ul');
// inp.addEventListener('keypress', function (e) {
// if (e.key === 'Enter') {
// if (!this.value) {
// return;
// }
// const li = document.createElement('li');
// li.innerText = this.value;
// const btn = document.createElement('button');
// btn.innerText = 'Delete Task';
// li.append(btn);
// ul.append(li);
// li.addEventListener('click', function (e) {
// e.target.style.textDecoration = 'line-through';
// });
// this.value = '';
// }
// });
// const multiply = (x, y) => x * y;
// const square = (x) => multiply(x, x);
// const rightTriangle = (a, b, c) => {
// return square(a) + square(b) === square(c);
// };
// rightTriangle(4, 5, 14);
// console.log('The first log');
// alert('An interruption in between');
// console.log('The last log');
console.log('The first log');
setTimeout(() => {
console.log('The line that takes time to complete');
}, 3000);
console.log('The last log');
// console.log('The first log');
// alert('An interruption in between');
// console.log('The last log');
// console.log('The first log');
// setTimeout(() => {
// console.log('The line that takes time to complete');
// }, 3000);
// console.log('The last log');
// const btn = document.querySelector('button');
// setTimeout(() => {
// btn.style.transform = `translateX(100px)`;
// setTimeout(() => {
// btn.style.transform = `translateX(200px)`;
// setTimeout(() => {
// btn.style.transform = `translateX(300px)`;
// setTimeout(() => {
// btn.style.transform = `translateX(400px)`;
// setTimeout(() => {
// btn.style.transform = `translateX(500px)`;
// setTimeout(() => {
// btn.style.transform = `translateX(600px)`;
// }, 1000);
// }, 1000);
// }, 1000);
// }, 1000);
// }, 1000);
// }, 1000);
// const willGetAPlayStation = new Promise((resolve, reject) => {
// const random = Math.random();
// if (random > 0.5) {
// resolve();
// } else {
// reject();
// }
// });
// willGetAPlayStation
// .then(() => {
// console.log("I'm happy! Thank you uncle.");
// })
// .catch(() => {
// console.log('F U uncle.');
// });
// const makePlayStationPromise = () => {
// return new Promise((resolve, reject) => {
// setTimeout(() => {
// const rand = Math.random();
// if (rand < 0.5) {
// resolve({ success: true });
// } else {
// reject({ success: false });
// }
// }, 5000);
// });
// };
// makePlayStationPromise()
// .then((data) => {
// console.log(data);
// console.log('I got a playstation!');
// })
// .catch((error) => {
// console.log(error);
// console.log("$@#$% I didn't get anything!");
// });
// const fakeRequest = (url) => {
// return new Promise((resolve, reject) => {
// setTimeout(() => {
// const pages = {
// '/users': [
// { id: 1, username: 'john' },
// { id: 2, username: 'jane' },
// ],
// '/about': 'This is the about page',
// };
// const data = pages[url];
// if (data) {
// resolve({ status: 200, data });
// } else {
// reject({ status: 404 });
// }
// }, 1000);
// });
// };
// fakeRequest('/helloworld')
// .then((data) => console.log(data))
// .catch((err) => console.log(err));
const fakeRequest = (url) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const pages = {
'/users': [
{ id: 1, username: 'john' },
{ id: 2, username: 'jane' },
],
'/users/1': {
id: 1,
username: 'johndoe',
topPostId: 53231,
city: 'mumbai',
},
'/users/5': {
id: 1,
username: 'janedoe',
topPostId: 32443,
city: 'pune',
},
'/posts/53231': {
id: 1,
title: 'Really amazing post',
slug: 'really-amazing-post',
},
};
const data = pages[url];
if (data) {
resolve({ status: 200, data });
} else {
reject({ status: 404 });
}
}, 1000);
});
};
fakeRequest('/users')
.then((res) => {
const id = res.data[0].id;
return fakeRequest(`/users/${id}`);
})
.then((res) => {
const topPostId = res.data.topPostId;
return fakeRequest(`/posts/${topPostId}`);
})
.then((res) => {
console.log(res);
})
.catch((err) => console.log(err));
// const result = fetch('https://pokeapi.co/api/v2/pokemon');
// fetch('https://pokeapi.co/api/v2/pokasdasdemon')
// .then((res) => {
// console.log('The request was successfull');
// console.log(res);
// })
// .catch((err) => {
// console.log('SOMETHING WENT WRONG');
// });
// axios
// .get('https://pokeapi.co/api/v2/poasdsadkemon')
// .then((res) => {
// console.log('The request was successfull');
// console.log(res.data);
// })
// .catch((err) => {
// console.log('SOMETHING WENT WRONG');
// });
// const checkStatusAndParse = (res) => {
// if (!res.ok) {
// throw new Error();
// }
// return res.json();
// };
// fetch('https://pokeapi.co/api/v2/pokemon')
// .then(checkStatusAndParse)
// .then((data) => {
// return fetch(data.results[0].url);
// })
// .then(checkStatusAndParse)
// .then((data) => {
// console.log(data);
// })
// .catch((err) => {
// console.log('SOMETHING WENT WRONG');
// });
// axios
// .get('https://pokeapi.co/api/v2/pokemon')
// .then((res) => {
// return axios.get(res.data.results[0].url);
// })
// .then((res) => {
// console.log(res.data);
// })
// .catch((err) => {
// console.log('SOMETHING WENT WRONG');
// });
// const div = document.querySelector('div');
// axios.get('https://pokeapi.co/api/v2/pokemon').then((res) => {
// const pokemons = res.data.results;
// const ul = document.createElement('ul');
// for (let pokemon of pokemons) {
// console.log(pokemon);
// // axios.get(pokemon.url).then()
// const li = document.createElement('li');
// li.innerText = pokemon.name;
// ul.append(li);
// }
// div.append(ul);
// });
const inp = document.querySelector('input');
const ul = document.querySelector('ul');
const btn = document.querySelector('button');
btn.addEventListener('click', function () {
const li = document.createElement('li');
li.innerText = inp.value;
// li.addEventListener('click', function () {
// li.remove();
// });
const check = document.createElement('input');
check.type = 'checkbox';
check.addEventListener('click', function () {
if (check.checked) {
li.style.textDecoration = 'line-through';
} else {
li.style.textDecoration = 'none';
}
});
const del = document.createElement('button');
del.innerText = 'Delete Task';
del.addEventListener('click', function () {
li.remove();
});
li.append(check);
li.append(del);
ul.append(li);
inp.value = '';
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script
crossorigin
src="https://unpkg.com/react@17/umd/react.production.min.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"
></script>
<script type="text/babel">
// const heading = document.createElement('h1');
// heading.innerText = 'Hello World!';
// const rootElement = document.querySelector('#root');
// rootElement.append(heading);
// const heading = React.createElement(
// 'h1',
// {
// className: 'title',
// id: 'test',
// },
// 'Hello from React'
// );
const heading = (
<h1 className="title" id="test">
Hello from React
</h1>
);
const props = {
className: 'test1',
};
const name = 'asdasknmdksajn';
const para = (
<p {...props}>
This is a {name === 'john' ? name.toUpperCase() : 'JACK'}
</p>
);
// const para = React.createElement('p', {}, 'This is a paragraph');
const div = React.createElement('div', { children: [heading, para] });
const div = (
<div>
<h1>Hello World</h1>
<p>This is some para</p>
</div>
);
const div = React.createElement(
'div',
{},
React.createElement('h1', {}, 'Hello World'),
React.createElement('p', {}, 'This is some para')
);
ReactDOM.render(div, document.querySelector('#root'));
</script>
</body>
</html>
const http = require('http');
const fs = require('fs');
const server = http.createServer((request, response) => {
// console.log(request.url);
// console.log(request.method);
// console.log(request.headers);
// // process.exit();
switch (request.url) {
case '/':
response.setHeader('Content-Type', 'text/html');
response.write(`
<html lang="en">
<head>
<title>Home Page</title>
</head>
<body>
<h1>Home Page</h1>
<p>Welcome to my home page.</p>
</body>
</html>
`);
response.end();
break;
case '/login':
response.setHeader('Content-Type', 'text/html');
response.write(`
<html lang="en">
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<p>Please sign in.</p>
</body>
</html>
`);
response.end();
break;
default:
fs.writeFileSync('test.txt', 'Page nahi mila');
response.setHeader('Content-Type', 'text/html');
response.write(`
<html lang="en">
<head>
<title>Not found</title>
</head>
<body>
<h1>404 - ${request.url}</h1>
<p>Page not found.</p>
</body>
</html>
`);
response.end();
}
// if (request.url === '/' && request.method === 'GET') {
// response.setHeader('Content-Type', 'text/html');
// response.write(`
// <html lang="en">
// <head>
// <title>Home Page</title>
// </head>
// <body>
// <h1>Home Page</h1>
// <p>Welcome to my home page.</p>
// </body>
// </html>
// `);
// response.end();
// }
// if (request.url === '/login' && request.method === 'GET') {
// response.setHeader('Content-Type', 'text/html');
// response.write(`
// <html lang="en">
// <head>
// <title>Login</title>
// </head>
// <body>
// <h1>Login</h1>
// <p>Please sign in.</p>
// </body>
// </html>
// `);
// response.end();
// }
});
server.listen(5000);
2. Chakra UI Installation and Setup
3. Create Header and Footer components
4. Create HomeScreen product listings
5. Install and Implement React Router
6. Design and build the ProductScreen component.
Setting up the backend
Fetching data from our backend using React
9. More backend setup
10. Setup environment variables
11. Convert imports to ES Modules
12. Install and setup MongoDB
13. Connect to the database
14. Improve console log messages.
15. Create database models for data
16. Prepare sample data for the backend data seeding
17. Create database seeder for quick sample data generation (optional)
18. Fetching products from the database
19. Do Postman setup to work with our API _(optional)_Custom error handling. Run the following in the root folder.
20. Custom error handling. Run the following in the root folder.
21. Introduction to Redux
22. Create our first reducer
23. Getting Redux State in the Home Screen
24. Create Message and Loader components.
25. Single product details screen Reducer and Action
26. Cart and Quantity
27. Cart Screen and Route
28. Cart Functionality
29. Completing CartScreen.js and creating ‘add to cart’ functionality
30. Clean up the backend routes by extracting their logic into controllers
31. User Authentication Endpoints (Backend Routes)
32. Using Json Web Tokens (JWT)
33. Creating custom Authentication Middleware to accessprotected routes.
34. User registration
35. User Login Reducer and Action
36. User Login Screen
37. Implement all the Login – Redux functionality in the LoginScreen component.
38. Header modification to show User and User Logout feature
39. User Register, Constants, Reducer, Action and Screen.
40. Update User Profile endpoint in the backend
41. User Profile Screen and Getting User Details
42. Add Update User Profile functionality
43. Shipping Screen and Save Address
44. Checkout Steps Component
45. PaymentScreen – where users can choose the payment method
46. Place Order Screen
47. Backend: Order controller and endpoint (route)
48. Create Order
49. Get Order By ID (Backend Endpoint)
50. Create the order details reducer and action (frontend)
51. Create the Order Screen component
52. Backend endpoint for updating an order to paid
53. Order pay reducer and action
54. Adding PayPal Payments
55. Show Orders on Profile Page
56. Clear state on logout
57. Admin Middleware and Getting Users Endpoint
58. Admin User List – Frontend
59. Admin Screen page security
60. Delete User Functionality (for Admins)
61. Backend endpoints for getting and updating user by it’s ID
62. User Edit screen and User Details screen components
63. Update user functionality
64. Admin – Product List
65. Admin – Delete Products
66. Create and Update Product Backend Endpoints
67. Admin – Create Product Screen
68. Product Edit Screen
69. Admin – Update Product Functionality
70. Image Upload Configuration and Endpoint
71. Upload images from the frontend
72. Admin – Order List
73. Admin – Mark order as delivered
74. Create Review Endpoint
75. Create Review Endpoint
76. Adding product reviews on the frontend