FullStack Morning Apr 2023
JS #3
// // // let age = 30;
// // // if (age >= 21) {
// // // console.log('You are allowed to enter.');
// // // }
// // // console.log('Hello World');
// // // let num = NaN;
// // // if (num % 2 === 0) {
// // // console.log('Number is even');
// // // } else if (num % 2 !== 0) {
// // // console.log('Number is odd');
// // // } else {
// // // console.log('Invalid number');
// // // }
// // let age = 21;
// // if (age >= 65) {
// // console.log('Drink are free');
// // } else if (age >= 21) {
// // console.log('You can enter and drink');
// // } else if (age >= 18) {
// // console.log("You can enter but you can't drink");
// // } else {
// // console.log('You are not allowed');
// // }
// let password = 'hello';
// if (password.length > 8) {
// if (password.indexOf(' ') === -1) {
// console.log('Valid Password');
// } else {
// console.log('Password cannot contain spaces');
// }
// } else {
// console.log('Invalid password');
// }
// let loggedInUser = 0;
// if (loggedInUser) {
// console.log('Welcome here');
// } else {
// console.log('You have to login to view the content.');
// }
// let age = 88;
// if (age >= 18 && age < 21) {
// console.log("You can enter but you can't drink");
// } else if (age >= 21 && age < 65) {
// console.log('You can enter and drink');
// } else if (age >= 65) {
// console.log('Drink are free');
// } else {
// console.log('You are not allowed');
// }
// let day = 2;
// if (day === 0) {
// console.log('Sunday');
// } else if (day === 1) {
// console.log('Monday');
// } else if (day === 2) {
// console.log('Tuesday');
// } else {
// console.log('Invalid day code');
// }
// let day = 0;
// switch (day) {
// case 0:
// console.log('Sunday');
// break;
// case 1:
// console.log('Monday');
// break;
// case 'hello':
// console.log('Something else');
// break;
// default:
// console.log('Invalid day code');
// }
let status = 'idle';
let color =
status === 'online' ? 'green' : status === 'offline' ? 'red' : 'yellow';
// let color;
// if (status === 'online') {
// color = 'green';
// } else {
// color = 'red';
// }
console.log(color);
JS #4 and #5
// const products = [
// ['iPhone 14', 'Apple', 'Some desc...', 500, 100000, true],
// ['iPhone 14', 'Apple', 'Some desc...', 500, 100000, true],
// ['iPhone 14', 'Apple', 'Some desc...', 500, 100000, true],
// ];
// const prod1 = ['iPhone 14', 'Apple', 'Some desc...', 100000, 500, true];
// console.log(prod1[3]);
const prod2 = {
brand: 'Apple',
description: 'Some description...',
price: 100000,
inStock: 500,
name: 'iPhone 14',
discounted: true,
info: {
firstName: 'John',
lastName: 'Doe',
},
10000: true,
'hello world': false,
};
console.log(prod2.info);
console.log(prod2['10000']);
console.log(prod2['hello world']);
// // // const pallette = {
// // // red: '#eb4d4b',
// // // yellow: '#f9ca24',
// // // blue: '#30336b',
// // // };
// // // let color = 'yellow';
// // // console.log(pallette[color]);
// // const fitnessData = {
// // totalSteps: 400000,
// // totalKms: 253.32,
// // avgCalorieBurn: 2300,
// // workoutsThisWeek: '5 of 7',
// // avgSleep: '5:45',
// // };
// // delete fitnessData.avgSleep;
// // fitnessData.hello = 'world';
// // fitnessData.totalSteps++;
// // console.log(fitnessData);
// // const student = {
// // firstName: 'John',
// // lastName: 'Doe',
// // frameworks: ['ReactJS', 'Express.js'],
// // levels: {
// // backend: 50,
// // frontend: 45,
// // data: 5,
// // },
// // };
// // console.log(student.frameworks[1]);
// // const shoppingCart = [
// // {
// // product: 'Apple iPhone',
// // price: 100000,
// // quantity: 100,
// // },
// // {
// // product: 'One Plus Nord',
// // price: 60000,
// // quantity: 1000,
// // },
// // {
// // product: 'Alienware M15',
// // price: 299999,
// // quantity: 1,
// // },
// // ];
// // console.log(shoppingCart[1].price);
// // for (let count = 0; count < 99999999999; count++) {
// // console.log(`${count}*${count}=${count * count}`);
// // }
// // for (let count = 10; count >= 0; count++) {
// // console.log(count);
// // }
// // const nums = [12, 34, 56, 34, 78, 54, 23, 12];
// // for (let i = 0; i < nums.length; i++) {
// // console.log(nums[i]);
// // }
// // for (let i = 0; i < nums.length; i++) {
// // console.log(`The value at index ${i} is ${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++) {
// const movie = movies[i];
// console.log(`${movie.movieName} has a rating of ${movie.rating}.`);
// }
// const word = 'Hello World';
// // for (let i = 0; i < word.length; i++) {
// // console.log(word[i]);
// // }
// let reversedWord = '';
// for (let i = word.length - 1; i >= 0; i--) {
// // console.log(word[i]);
// reversedWord += word[i];
// }
// console.log(reversedWord);
// for (let i = 1; i < 6; i++) {
// console.log('OUTER LOOP:', i);
// for (let j = 1; j < 6; j++) {
// console.log('\tINNER LOOP', j);
// }
// }
// const gameBoard = [
// [4, 64, 8, 4],
// [128, 32, 4, 16],
// [16, 4, 4, 32],
// [2, 16, 16, 2],
// ];
// let total = 0;
// for (let i = 0; i < gameBoard.length; i++) {
// for (let j = 0; j < gameBoard[i].length; j++) {
// console.log(gameBoard[i][j]);
// total += gameBoard[i][j];
// }
// }
// console.log(total);
// for (let i = 0; i < 10; i++) {
// console.log(i);
// }
// let count = 0;
// while (count < 10) {
// console.log(count);
// count++;
// }
// const target = Math.floor(Math.random() * 10) + 1;
// let guess = Math.floor(Math.random() * 10) + 1;
// while (guess !== target) {
// if (guess === 2) {
// break;
// }
// console.log(`TARGET: ${target} | COMP GUESS: ${guess}`);
// guess = Math.floor(Math.random() * 10) + 1;
// }
// console.log(`TARGET: ${target} | COMP GUESS: ${guess}`);
// const target = Math.floor(Math.random() * 10) + 1;
// let guess = Math.floor(Math.random() * 10) + 1;
// while (true) {
// if (guess === target) {
// break;
// }
// console.log(`TARGET: ${target} | COMP GUESS: ${guess}`);
// guess = Math.floor(Math.random() * 10) + 1;
// }
// console.log(`TARGET: ${target} | COMP GUESS: ${guess}`);
const nums = [12, 34, 56, 34, 78, 54, 23, 12];
// for (let i = 0; i < nums.length; i++) {
// console.log(nums[i]);
// }
// for (let num of nums) {
// console.log(num);
// }
// for (let char of 'hello world') {
// console.log(char);
// }
// const matrix = [
// [1, 4, 7],
// [9, 7, 2],
// [9, 4, 6],
// ];
// let total = 0;
// for (let arr of matrix) {
// for (let num of arr) {
// total += num;
// }
// }
// 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 key of Object.keys(productPrices)) {
console.log(key, productPrices[key]);
}
for (let key in productPrices) {
console.log(key, productPrices[key]);
}
JS #6
// // function greet() {
// // console.log('Hello World');
// // console.log('Hello World');
// // console.log('Hello World');
// // console.log('Hello World');
// // }
// // for (let i = 0; i < 10; i++) {
// // greet();
// // }
// // function rollDie() {
// // let roll = Math.floor(Math.random() * 6) + 1;
// // console.log(`Rolled: ${roll}`);
// // }
// // function throwDice(times) {
// // for (let i = 0; i < times; i++) {
// // rollDie();
// // }
// // }
// // throwDice(50);
// // function greet(person, message) {
// // console.log(`${message} ${person}`);
// // }
// // greet('John Doe', 'Hello', 'world', true, 100);
// // greet('Jane Smith');
// // function greet(name, message) {
// // return `${message} ${person}`;
// // }
// // console.log(greet('Jane Doe', 'Hello'));
// // function isNumber(val) {
// // if (typeof val === 'number') {
// // return true;
// // }
// // return false;
// // }
// // console.log(isNumber(10));
// // let firstName = 'Jane';
// // function greet() {
// // let firstName = 'John';
// // console.log(firstName);
// // }
// // greet();
// // console.log(firstName);
// // var firstName = 'Jane';
// // if (true) {
// // var firstName = 'John';
// // console.log(firstName);
// // }
// // console.log(firstName);
// // for (var i = 0; i < 10; i++) {
// // console.log('Inside the for loop', i);
// // }
// // console.log('Outside the for loop', i);
// // function outer() {
// // const firstName = 'John';
// // function inner() {
// // const firstName = 'Jane';
// // console.log(firstName);
// // }
// // inner();
// // }
// // outer();
// // function greet() {
// // console.log('Hello World');
// // }
// // const hello = greet;
// // hello();
// function math(a, b, fn) {
// return fn(a, b);
// }
// function add(a, b) {
// return a + b;
// }
// function sub(a, b) {
// return a - b;
// }
// console.log(math(10, 2, sub));
// console.log(
// math(10, 6, function (a, b) {
// return a ** b;
// })
// );
// // const square = function (a) {
// // return a ** 2;
// // };
// // console.log(square(10));
// const math = [
// function (a, b) {
// return a + b;
// },
// function (a, b) {
// return a - b;
// },
// function (a, b) {
// return a * b;
// },
// function (a, b) {
// return a / b;
// },
// ];
// console.log(math[2](10, 5));
const math = {
add: function (a, b) {
return a + b;
},
sub: function (a, b) {
return a - b;
},
mul: function (a, b) {
return a * b;
},
div: function (a, b) {
return a / b;
},
};
console.log(math.add(10, 5));
JS #7
// // // // function math(a, b, fn) {
// // // // return fn(a, b);
// // // // }
// // // // function sub(a, b) {
// // // // return a - b;
// // // // }
// // // // console.log(math(10, 5, sub));
// // // let total = 0;
// // // function getValue(val) {
// // // val = val + 10;
// // // return val;
// // // }
// // // console.log(getValue(total));
// // // console.log(getValue(total));
// // // console.log(getValue(total));
// // // console.log(getValue(total));
// // // // Example 2
// // // 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)
// // // // Example 3
// // // 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;
// // };
// // }
// // let square = raiseBy(2);
// // let cube = raiseBy(3);
// // let hypercube = raiseBy(4);
// // console.log(hypercube(2));
// // function isBetween(x, y) {
// // return function (num) {
// // return num >= x && num <= y
// // }
// // }
// // const isUnderAge = isBetween(0, 18)
// // const canEnterButNotDrink = isBetween(18, 21)
// // const canDrink = isBetween(21, 65)
// // const isSenior = isBetween(65, 100)
// // console.log(isUnderAge(5))
// // console.log(canEnterButNotDrink(20))
// // console.log(canDrink(30))
// // console.log(isSenior(70))
// // setInterval(function () {
// // console.log('Hello World');
// // }, 1000);
// // (function () {
// // console.log('Hello World');
// // })();
// // console.log(
// // (function (num) {
// // return function (x) {
// // return x ** num;
// // };
// // })(10)(5)
// // );
// // // console.log(result(5));
// // greet();
// // function greet() {
// // console.log('Hello World');
// // }
// console.log(hello);
// let hello = 'world';
// const nums = ['jane', 'jack', 'hello', true, false, 0, null, undefined];
// // for (let num of nums) {
// // console.log(num);
// // }
// nums.forEach(function (num, i) {
// console.log(i, num, 'Hello');
// });
// 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());
// });
// const names = ['john', 'jack', 'jane', 'james'];
// const uppercasedNames = names.map(function (name) {
// return 'hello';
// });
// // const uppercasedNames = [];
// // for (let name of names) {
// // uppercasedNames.push(name.toUpperCase());
// // }
// console.log(uppercasedNames);
const nums = [2, 3, 4, 7, 6, 8, 13, 10, 19, 12, 14, 22, 21, 16];
const doubles = nums.map(function (num) {
return {
number: num,
isEven: num % 2 === 0,
};
});
console.log(doubles);
JS #8
// // // let nums = [1, 2, 3, 4, 5];
// // // let doubles = nums.map(function (num) {
// // // return num * 2;
// // // });
// // // console.log(doubles);
// // // function square(x) {
// // // return x ** 2;
// // // }
// // // const square2 = x => x ** 2
// // // console.log(square2(2))
// // let nums = [1, 2, 3, 4, 5];
// // let doubles = nums.map((num) => num * 2);
// // console.log(doubles);
// // let movies = ['The Terminator', 'The Avengers', 'Jurassic Park', 'Titanic'];
// // const result = movies.find((movie) => movie[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: 3.5,
// // },
// // {
// // title: 'The Great Gatsby',
// // author: 'F. Scott Fitzgerald',
// // rating: 3.8,
// // },
// // ];
// // const result = books.find((book) => book.rating < 4);
// // console.log(result);
// // const goodBook = books.find((b) => b.rating >= 4.3);
// // const georgeBook = books.find((b) => b.author.includes('George'));
// // const lowRated = books.find((book) => {
// // return book.rating < 4;
// // });
// // console.log(goodBook);
// // console.log(georgeBook);
// 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.filter((book) => book.rating < 4);
// console.log(result);
// 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) => {
// const title = book.title.toLowerCase();
// return title.includes(query);
// });
// console.log(goodBook);
// console.log(georgeBooks);
// console.log(lowRated);
// console.log(booksWithThe);
// const names = ['jack', 'james', 'john', 'jane', 'josh', 'jrad'];
// const result = names.every((name) => name[0] == 'j');
// console.log(result);
// 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', 'jrad'];
// const result = names.some((name) => name[0] === 'b');
// console.log(result);
// const prices = [500.4, 211, 23, 5, 4, 22.2, -23.2, 9233];
// const result = prices.sort((a, b) => a - b);
// console.log(result);
// const nums = [1, 2, 3, 4, 5];
// const result = nums.reduce((acc, currVal) => acc * currVal);
// console.log(result);
// // acc currVal
// // 1 2
// // 3 3
// // 6 4
// // 10 5
// // 15
// let nums = [21, 221, 2, 1, 34, 123, 4342, 56, 4];
// const maxVal = nums.reduce((acc, currVal) => {
// if (currVal > acc) {
// return currVal;
// }
// return acc;
// });
// acc currVal
// 21 221
// 221 2
// 221 1
// 221 34
// 221 4342
// 4342
// // Example 2 -> Product (multiply everything)
// [3, 2, 4, 6, 9].reduce((total, currentVal) => {
// return total * currentVal;
// });
// // Example 3 -> Finding max value
// let nums = [21, 221, 2, 1, 34, 123, 4342, 56, 4];
// const maxVal = nums.reduce((max, currentVal) => {
// if (currentVal > max) {
// return currentVal;
// }
// return max;
// });
// console.log(maxVal); // 4342
// // A shorter way is to use the Math.max and implicit return
// const maxVal = nums.reduce((max, currVal) => Math.max(max, currVal));
// console.log(maxVal);
const nums = [1, 2, 3, 4, 5];
console.log(nums.reduce((acc, currVal) => acc + currVal, 100));
JS #9
// // // function add(a = 0, b = 0) {
// // // return a + b;
// // // }
// // // console.log(add(5, 30));
// // // function printVals(a, b, c) {
// // // console.log(a);
// // // console.log(b);
// // // console.log(c);
// // // }
// // // const data = ['hello', 'world', 'test'];
// // // printVals(...'hello');
// // // function add(...nums) {
// // // return nums.reduce((acc, currVal) => acc + currVal);
// // // }
// // // console.log(add(10, 5, 43, 1, 21, 123, 344));
// // // function printNames(name1, name2, ...others) {
// // // console.log(name1);
// // // console.log(name2);
// // // console.log(others);
// // // }
// // // printNames('john', 'jane', 'jack', 'josh');
// // function profile({ firstName, lastName, age }) {
// // console.log(
// // `Hello, my name is ${firstName} ${lastName} and I am ${age} years old`
// // );
// // }
// // profile({ firstName: 'John', lastName: 'Doe', age: 20 });
// 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, hello: 'world' };
// console.log(info1);
// const getReviewDetails = (arr) => {
// const highest = Math.max(...arr);
// const lowest = Math.min(...arr);
// const total = arr.reduce((accumulator, nextVal) => accumulator + nextVal);
// const average = total / arr.length;
// return {
// highest,
// lowest,
// total,
// average,
// };
// };
// const reviewList = [4.5, 5.0, 3.2, 2.1, 4.7, 3.8, 3.1, 3.9, 4.4];
// const statistics = getReviewDetails(reviewList);
// const username = 'janedoe';
// const role = 'admin';
// const user1 = {
// [role.toUpperCase()]: username,
// };
// console.log(user1);
const addProperty = (obj, k, v) => {
return { ...obj, [k]: v };
};
console.log(addProperty({ name: 'John' }, 'age', 25));
JS #10
// // const math = {
// // multiply(x, y) {
// // return x * y;
// // },
// // divide(x, y) {
// // return x / y;
// // },
// // square(x) {
// // return x ** 2;
// // },
// // };
// // console.log(math.multiply(2, 5));
// // console.log('Hello World!');
// // function namaste() {
// // console.log('Hello World');
// // console.log(this);
// // // this =
// // }
// // namaste();
// function namaste() {
// console.log(`Hello, my name is ${this.firstName} ${this.lastName}.`);
// }
// const profile1 = {
// firstName: 'John',
// lastName: 'Doe',
// namaste,
// };
// const profile2 = {
// firstName: 'Jane',
// lastName: 'Smith',
// namaste,
// };
// const hello = profile2.namaste;
// hello();
// // namaste();
// // profile1.namaste();
// // profile2.namaste();
// const hello = {
// 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(() => {
// // this = hello
// console.log(this.pickMsg());
// }, 1000);
// },
// };
// hello.start();
const user1 = {
firstName: 'John',
lastName: 'Doe',
greet: () => {
console.log(`Hello my name is ${this.firstName} ${this.lastName}`);
},
};
user1.greet();
JS #11
// // const title = document.getElementById('special');
// // console.dir(title);
// // const listItems = document.getElementsByTagName('li');
// // console.log(listItems);
// const hellos = document.getElementsByClassName('hello');
// // console.log(hellos[1]);
// const list = hellos[1];
// // const listItems = document.getElementsByTagName('li');
// // console.log(listItems);
// // console.log(list);
// const listItems = list.getElementsByTagName('li');
// console.log(listItems);
// const result = document.querySelectorAll('#special');
// console.log(result);
// const h1 = document.querySelector('h1');
// console.log(h1.innerText);
// h1.innerText = 'This is something else';
// setInterval(function () {
// h1.innerText = Math.random();
// }, 1000);
// const ul = document.querySelector('ul');
// console.log(ul);
// ul.innerText = 'Hello';
// const p = document.querySelector('p');
// // console.log(p.textContent);
// p.innerHTML = 'Hello <strong>World</strong>';
// p.innerHTML += ' <em>this is more content</em>';
// const a = document.querySelector('a');
// // a.href = 'https://yahoo.co.in';
// a.setAttribute('href', 'https://hey.com');
// // console.log(a.href);
// console.log(a.getAttribute('href'));
// const li = document.querySelector('.li');
// // console.log(li.previousElementSibling);
// // console.log(li.nextElementSibling.nextElementSibling);
// console.log(li.parentElement.parentElement);
// const lis = document.querySelectorAll('li');
// for (let li of lis) {
// li.innerText = Math.random();
// }
// const h1 = document.querySelector('h1');
// h1.style.color = 'red';
// h1.style.backgroundColor = 'black';
// h1.style.padding = '20px 40px';
// h1.style.borderRadius = '50%';
// h1.style.textAlign = 'center';
// const lis = document.querySelectorAll('li');
// const colors = ['red', 'yellow', 'green', 'orange', 'teal'];
// for (li of lis) {
// li.style.color = colors[Math.floor(Math.random() * colors.length)];
// li.style.fontSize = '20';
// li.style.fontWeight = 'bold';
// li.style.backgroundColor = 'black';
// li.style.fontFamily = 'Helvetica, sans-serif';
// }
// const h1 = document.querySelector('h1');
// const h1Styles = getComputedStyle(h1);
// console.log(h1Styles.color);
// const li = document.querySelector('li');
// // li.className = 'todo done';
// li.classList.add('hello');
// // li.classList.remove('todo');
// // li.classList.toggle('todo');
// console.log(li.classList);
const root = document.querySelector('#root');
const title = document.createElement('h1');
title.innerText = 'Hello World. This is an element created using JavaScript.';
title.style.color = 'red';
title.style.textDecoration = 'underline';
const container = document.createElement('div');
container.style.padding = '40px 100px';
container.style.border = '1px solid red';
container.appendChild(title);
root.appendChild(container);
// ----------------
const li = document.createElement('li');
li.innerText = 'Hello World';
const ul = document.querySelector('ul');
const targetLi = ul.querySelector('li');
ul.insertBefore(li, targetLi);