Full Stack Morning June 21

Full Stack Morning June 21

Scratchpad #1

let greeting = 'Hello World, Welcome to RST Forum.';

// let result = greeting.toLowerCase().indexOf('rst');

// console.log(result);

// let result2 = greeting.indexOf('RST').toUpperCase();

let result3 = greeting.indexOf('RST') * '23A' + '23A';
console.log(result3);

Scratchpad #2

// let score = ;

// console.log('Hello World');
// console.log('Your score is more than 99');
// console.log(100 + 56 / 2);

// if (score > 10) {
//   console.log('This code is inside the if statement');
// }

// if (score > 100) {
//   console.log('Score is above 100');
// } else if (score < 100) {
//   console.log('Score is less than 100');
// } else {
//   console.log('Score is not a number');
// }

// let role = 'admin';

// if (role === 'admin') {
//   console.log('You have access');
// } else if (role === 'moderator') {
//   console.log('You are granted access with limited priviledges');
// } else if (role === 'user') {
//   console.log('Welcome to your dashboard');
// } else {
//   console.log('Access Denied');
// }

// if (role === 'admin') {
//   console.log('You have access');
// }

// if (role === 'moderator') {
//   console.log('You are granted access with limited priviledges');
// }

if (role === 'user') {
  console.log('Welcome to your dashboard');
} else {
  console.log('Access Denied');
}

let age = 21;

if (age > 18) {
  console.log('Entry Granted!');
}

if (age >= 21) {
  console.log('Drinks Allowed');
}

if (age >= 65) {
  console.log('Drinks FREE!');
}

Scratchpad #3

// let age = 18;

// if (age > 18) {
//   console.log('You can enter but you cannot drink.');
// } else if (age > 21) {
//   console.log('You can enter and can drink');
// } else if (age > 65) {
//   console.log('Drinks are free');
// } else {
//   console.log('You are not allowed');
// }

// if (age >= 18) {
//   if (age >= 65) {
//     console.log('Drinks are free');
//   } else if (age >= 21) {
//     console.log('You can enter and can drink');
//   } else {
//     console.log('You can enter but you cannot drink.');
//   }
// } else {
//   console.log('You are not allowed');
// }

// let password = 'helloworld@123';

// // outer condition
// if (password.length >= 6) {
//   // inner condition
//   if (password.indexOf(' ') !== -1) {
//     console.log('Password cannot include spaces');
//   } else {
//     console.log('Valid Password');
//   }
// } else {
//   console.log('Password is too short!');
// }

// let loggedInUser = 'johndoe@gmail.com';

// if (loggedInUser) {
//   console.log(`Welcome ${loggedInUser}`);
// } else {
//   console.log('Please log in');
// }

// let age = 99;

// if (age >= 18 && age < 21) {
//   console.log('You can enter but you cannot drink.');
// } else if (age >= 21 && age < 65) {
//   console.log('You can enter and you can drink');
// } else if (age >= 65) {
//   console.log('Drinks are free');
// } else {
//   console.log('You are not allowed');
// }

// let day = 15;

// if (day === 1) {
//   console.log('MON');
// } else if (day === 2) {
//   console.log('TUE');
// } else if (day === 3) {
//   console.log('WED');
// } else if (day === 4) {
//   console.log('THU');
// } else if (day === 5) {
//   console.log('FRI');
// } else if (day === 6) {
//   console.log('SAT');
// } else if (day === 7) {
//   console.log('SUN');
// } else {
//   console.log('Invalid num');
// }

// let day = 'Monday';

// switch (day) {
//   case 'Monday':
//     console.log('MON');
//     break;
//   case 2:
//     console.log('TUE');
//     break;
//   case 3:
//     console.log('WED');
//     break;
//   default:
//     console.log('Invalid num');
// }

let status = 'offline';

let color;

if (status === 'offline') {
  color = 'red';
} else if (status === 'online') {
  color = 'green';
} else {
  color === 'yellow';
}

let color =
  status === 'offline' ? 'red' : status === 'online' ? 'green' : 'yellow';

Scratchpad #4

// let foods = ['carrot', 'apple', 'cabbage', [1, 2, 3, 4]];

// // console.log(foods[0]);
// // console.log(foods.length);

// console.log(foods);

// foods[0] = 'onion';
// foods[foods.length] = 'toothpaste';
// foods[foods.length] = 'tobacco';

// foods[15] = 'stone';

// console.log(foods);

// let movies = ['Alien', 'Mad Max', 'Inception', 'Desh Drohi', 'Jaani Dushman'];

// movies.push('Gunda');

// if (movies.includes('gunda')) {
//   console.log('You are awesome!');
// } else {
//   console.log('Too bad!');
// }

// const product = {
//   name: 'Apple iPhone',
//   price: 100000,
//   'brand name': 'Apple',
//   100: 'something',
//   brandName: 'Apple',
// };

// console.log(product.name);
// console.log(product.price);
// console.log(product[100]);
// console.log(product['brand name']);

// product['brand name'];

const emails = [
  {
    senderName: 'John Doe',
    senderEmail: 'john@gmail.com',
    message: '....',
  },
  {
    senderName: 'John Doe',
    senderEmail: 'john@gmail.com',
    message: '....',
  },
  {
    senderName: 'John Doe',
    senderEmail: 'john@gmail.com',
    message: '....',
  },
  {
    senderName: 'John Doe',
    senderEmail: 'john@gmail.com',
    message: '....',
  },
  {
    senderName: 'John Doe',
    senderEmail: 'john@gmail.com',
    message: '....',
  },
  {
    senderName: 'John Doe',
    senderEmail: 'john@gmail.com',
    message: '....',
  },
  {
    senderName: 'John Doe',
    senderEmail: 'john@gmail.com',
    message: '....',
  },
];

console.log(emails[0]);

Scratchpad #5

// let firstName;

// let playerOneScore

// let PlayerOneScore

// const GST_TIER_ONE // constants

// const pallette = {
//   red: '#eb4d4b',
//   yellow: '#f9ca24',
//   blue: '#30336b',
// };

// const userInput = 'red';

// console.log(pallette[userInput]);

// pallette[userInput];
// pallette.yellow;

// console.log(pallette['yellow']);

// const fitnessData = {
//   totalSteps: 400000,
//   totalKms: 253.32,
//   avgCalorieBurn: 2300,
//   workoutsThisWeek: '5 of 7',
//   avgSleep: '5:45',
// };

// const name2 = 'Kamal R Khan';

// const song = {
//   name: 'Brown Munde',
//   artist: name2,
//   duration: 4.2,
//   album: null,
//   composers: [
//     {
//       name: 'Honey Singh',
//       label: 'T-series',
//       profilePicture: '/assets/images/singh.png',
//     },
//     {
//       name: 'Divine',
//       label: 'YouTube',
//       profilePicture: '/assets/images/singh.png',
//     },
//     {
//       name: 'Emiway',
//       label: 'YouTube',
//     },
//   ],
// };

// console.log(song);
// console.log(song.composers[1].name);

// for (let i = 0; i < 10; i++) {
//   console.log(i, 'Hello World');
// }

// for (let number = 10; number > 0; number--) {
//   console.log(number);
// }

// for (let i = 0; i < 100; i += 5) {
//   console.log(i, 'Hello World');
// }

// for (let i = 20; i >= 0; i++) {
//   console.log(i, i * 2, i * 3, i + 7);
// }

// for (let i = 0; i < 10; i++) {
//   // console.log(`${i}: Hello World`);
//   // console.log('i: Hello World');
//   console.log(`${i} x ${i} = ${i * i}`);
// }

// 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++) {
//   console.log(`${movies[i].movieName} has a \nrating of ${movies[i].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--) {
//   reversedWord += word[i];
//   console.log(word[i]);
//   console.log(reversedWord, '\n\n');
// }

// console.log('LOOP KHATAM... ALAG SE PRINT');
// console.log(reversedWord);

// for (let i = 0; i < 5; i++) {
//   for (let j = 0; j < 5; j++) {
//     console.log(i, j);
//   }
// }

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 = [
  [
    [1, 2, 3],
    [12, 46, 3678, 23],
    [12, 2345546, 5464, 3],
    [128, 32, 4, 16],
  ],
  [
    [1, 2, 3],
    [34534, 46, 3678, 23],
    [12, 23446, 53424, 3],
    [128, 2342, 74, 16],
  ],
  [
    [1, 34, 234],
    [132, 46, 3678, 233],
    [132, 2345546, 56464, 3],
    [128, 32, 4, 16],
  ],
  [
    [1, 2324, 3],
    [12342, 4346, 363478, 23],
    [12, 2334446, 5464, 3],
    [1228, 32, 4342, 16],
  ],
];

// rahul@rstforum.co.in

Scratchpad #6

// let i = 0;

// while (i < 10) {
//   console.log(i);
//   i++;
// }

let target = Math.floor(Math.random() * 100) + 1;
let guess = Math.floor(Math.random() * 100) + 1;

// console.log(target);
// console.log(guess);

// while (guess !== target) {
//   if (guess === 13) {
//     console.log('13 is an unlucky number.\nBreaking out of this loop.');
//     break; // manually break out of the loop
//   }

//   console.log(`Target: ${target} | Guess: ${guess}`);
//   guess = Math.floor(Math.random() * 100) + 1;
// }

// while (true) {
//   console.log(`Target: ${target} | Guess: ${guess}`);

//   if (guess === target) {
//     break; // manually break out of the loop
//   }

//   guess = Math.floor(Math.random() * 100) + 1;
// }

// console.log(`Target: ${target} | Guess: ${guess}`);

// let categories = [
//   'fashion',
//   'electronics',
//   'mobiles',
//   'books',
//   'toys',
//   'groceries',
// ];

// for (let i = 0; i < categories.length; i++) {
//   console.log(categories[i]);
// }

// for (let category of categories) {
//   console.log(category);
// }

// const nums = [
//   [1, 2, 3, 4],
//   [5, 6, 7, 8],
//   [9, 10, 11, 12],
// ];

// for (let arr of nums) {
//   for (let num of arr) {
//     console.log(num);
//   }
// }

// for (let char of 'hello') {
//   console.log(char.toUpperCase());
// }

// const matrix = [
//   [1, 4, 7],
//   [9, 7, 2],
//   [9, 4, 10],
// ];

// let total = 0;

// for (let row of matrix) {
//   for (let num of row) {
//     total = total + num;
//   }
// }

// console.log(`The total is ${total}.`);

// const cats = ['fashion', 'mobiles', 'books', 'electronics'];
// 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,
};

// productPrices.Apple
// productPrices['Apple']

// for (let prop of productPrices) {
//   console.log(prop);
// }

// for (let prop of Object.keys(productPrices)) {
//   console.log(prop);
//   console.log(productPrices[prop]);
// }

// // For...in is to be used with Objects. You will get the key
// for (let key in productPrices) {
//   console.log(key, productPrices[key]);
// }

// // for (let prop of Object.values(productPrices)) {
// //   console.log(prop);
// // }

// console.log()

// function greet() {
//   console.log('Hello World');
//   console.log(Math.random());
// }

// greet();
// greet();
// greet();
// greet();

// for (let i = 0; i < 50; i++) {
//   greet();
// }

// function rollDie() {
//   let roll = Math.floor(Math.random() * 6) + 1;
//   console.log(`Rolled: ${roll}`);
// }

// function throwDice() {
//   rollDie();
//   rollDie();
//   rollDie();
//   rollDie();
// }

// throwDice();

// function greet(name, message) {
//   console.log(`${message}, ${name}`);
// }

// greet('John');
// greet('Kamal', 'Hi');

function add(num1, num2, num3) {
  console.log(num1 + num2 + num3);
}

add(10, 43);

Scratchpad #7

// function greet(name) {
//   return `Hello, ${name}`;
// }

// function greet2(name) {
//   return `Hi there, ${greet(name)}`;
// }

// let result = greet('John');

// console.log(result);

// let result = console.log('Hello World');
// console.log(result);

// console.log(greet(greet('John')));

// console.log(greet2('Jack'));

// function isNumber(val) {
//   if (typeof val !== 'number') {
//     let a = 10;
//     console.log(a);
//     return false;
//   } else {
//     return true;
//   }
// }

// console.log(isNumber(50));

// function greet() {
//   let msg = 'Hello World';
//   return msg + '!';
// }

// console.log(msg);

// console.log(greet());

// var naam = 'John Doe';

// function sayHello() {
//   var naam = 'Jack';
//   console.log(naam);
// }

// console.log(naam);

// // sayHello();

// let i = 0;

// while (i < 5) {
//   var naam = 'Jack Ma';
//   console.log(naam);
//   i++;
// }

// console.log(naam);

// for (var i = 0; i < 10; i++) {
//   console.log(i);
// }

// console.log('This is the value of i: ', i);

// let movie = 'Robot';

// 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(movie);

//   inner();
// }

// outer();

function square(a) {
  return a * a;
}

// const cube = function (a) {
//   return a * a * a;
// };

// // console.log(square(5));
// console.log(cube(10));

// const allMyFuncs = [
//   function (a) {
//     return a * a;
//   },
//   function (a) {
//     return a * a * a;
//   },
// ];

// console.log(allMyFuncs[0](10));

// function mul(a, b) {
//   return a * b;
// }

// const calc = {
//   add: function (a, b) {
//     return a + b;
//   },
//   sub: function (a, b) {
//     return a - b;
//   },
//   mul: mul,
// };

// console.log(calc.mul(10, 5));

// function say(f) {
//   f();
//   f();
// }

// function hello() {
//   console.log('hello john');
// }

// say(hello);

// say(function () {
//   console.log('HEYYYYYY');
// });

// // 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) {
  // inner function has access
  // to parent function's scope
  return function (x) {
    return x ** num;
  };
}

let cube = raiseBy(3);
let square = raiseBy(2);
let tesseract = raiseBy(4);

// let cube = function (x) {
//     return x ** 3;
// };

// let square = function (x) {
//     return x ** 2;
// };

// let tesseract = function (x) {
//     return x ** 4;
// };

console.log(cube);

// Username: rst-fullstackdevelopment-564421
// Password: psig8u
// Port(s): 14014

// Username: rst-fullstackdevelopment-489021
// Password: ypjb56
// Port(s): 14015

Scratchpad #8

// function add(num1, num2) {
//   console.log(num1 + num2);
//     return num1 + num2;
// }

// var john;

// let result = add(10, 5);

// console.log(add(10, 5));

// console.log(result);

// let movie = 'Robot';

// function outer() {
//   function inner() {
//     let movie = 'John Wick';
//     let ratings = `${movie} has a rating of 4.2`;
//     return ratings;
//   }
//   return inner();
// }

// outer();

// function multipleGreets(fn) {
//   console.log(fn());
//   console.log(fn());
//   console.log(fn());
// }

// function hello() {
//   // console.log('Hello World!');
//   return 'Hello World';
// }

// multipleGreets(hello);

// console.log(hello());

// function logHello() {
//   console.log('Hello World');
// }

// setTimeout(logHello, 2000);

// setTimeout(function () {
//   console.log('hello world');
// }, 5000);

// console.log(add(10, 5));

// console.log(john);

// // All the functions

// // function add(a, b) {
// //   return a + b;
// // }

// let john = 'john doe';

// const nums = [9, 2, 4, 6, 2, 3, 7, 6];

// // nums.forEach(function (n) {
// //   console.log(n * n);
// // });

// // for (let n of nums) {
// //   console.log(n * n);
// // }

// nums.forEach(function (el) {
//   if (el % 2 === 0) {
//     console.log(el);
//   }
// });

// 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, idx) {
//   console.log(`${idx + 1} --- ${movie.title.toUpperCase()}`);
// });

// const names = ['john', 'jack', 'jane', 'james'];

// // const upperCasedNames = names.map(function (name) {
// //   return name.toUpperCase();
// // });

// // console.log(upperCasedNames);

// let 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];

// console.log(
//   nums.forEach(function (n) {
//     console.log(n);
//   })
// );

// console.log(
//   nums.map(function (n) {
//     console.log(n);
//   })
// );

// const numDetails = nums.map(function (n) {
//   return {
//     number: n,
//     isEven: n % 2 === 0,
//   };
// });

// console.log(numDetails);

// function square(num) {
//   return num * num;
// }

// const square = function (num) {
//   return num * num;
// };

// const square2 = (num) => {
//   return num * num;
// };

// console.log(square(10));

// console.log(square2(5));

// const raiseTo = (num, pow) => {
//   return num ** pow;
// };

// console.log(raiseTo(10, 4));

// const square2 = num => {
//   // let a = 10;
//   return num * num;
// };

// const square3 = num => (
//   num * num
// );

// const square4 = num => (num * num);

// const square5 = num => num * num;

// console.log(square5(50));


// const raiseTo = (num, pow) => (
//   num ** pow
// );
// console.log(raiseTo(9, 3))



const nums = [1, 2, 3, 45, 6];

nums.forEach(n => console.log(n))

nums.forEach(function (n) {
  console.log(n)
})

const numsSqrd = nums.map(n => n * n);

const numsCubed = nums.map(function (n) {
  return n * n * n;
})


// Block Scope
// Block scoped (let and const)
if (true) {
  let first_name = 'John'
  const last_name = 'Doe'
  console.log(first_name + ' ' + last_name)
}
console.log(first_name, last_name) // ERROR

// Block scoped (var)
if (true) {
  var first_name = 'John'
  var last_name = 'Doe'
  console.log(first_name + ' ' + last_name)
}
console.log(first_name, last_name) // WORKS

// Problematic code
for (var i = 0; i < 10; i++) {
  console.log(i)
}
console.log(i) // WORKS!

Scratchpad #9

// const math = (a, b, fn) => {
//   return fn(a, b);
// };

// console.log(math(5, 4, (a, b) => a + b));

// math(5, 4, function (a, b) {
//   return a + b;
// });

// const movies = ['The Terminator', 'The Avengers', 'Jurassic Park', 'Titanic'];

// console.log(movies.find((movie) => movie.includes('The')));

// 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.title === '1984');

// console.log(result);

// const movies = ['The Terminator', 'The Avengers', 'Jurassic Park', 'Titanic'];

// const results = movies.filter((movie) => movie.includes('The'));

// const bookResults = books.filter((book) => book.rating > 4);

// // console.log(results);
// console.log(bookResults);

// let query = ' ';

// const filteredBooks = books.filter((book) => {
//   return book.title.toLowerCase().includes(query);
// });

// console.log(filteredBooks);

// const names = ['jack', 'james', 'john', 'jane', 'josh', 'brad'];

// const result = names.every((name) => name[0] === 'j');
// const result2 = names.every((name) => name.length > 3);

// console.log(result);
// console.log(result2);

// 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) => b - a);

// console.log(result);

// const bookResults = books.sort((a, b) => a.rating - b.rating);

// console.log(bookResults);

// const nums = [12, 2, 1, 11, 2, 3, 2, 2, -10];

// const result = nums.reduce((acc, currVal) => acc * currVal);

// // acc    currVal
// // 12            2
// // 14            1
// // 15            11
// // 26            2
// // 28            3
// // 31            2
// // 33            2
// // 35            -10
// // 25

// console.log(result);

// const maxVal = nums.reduce((acc, currentVal) => {
//   if (currentVal > acc) {
//     return currentVal;
//   }
//   return acc;
// });

// const maxVal = nums.reduce((acc, currVal) => (currVal > acc ? currVal : acc));

// console.log(maxVal);

// // 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);

// // accumulator will be 3 (first value) by default
// [3, 2, 4, 6, 9]
//   .reduce((accumulator, currentValue) => {
//     return accumulator + currentValue;
//   })

//   [
//     // accumulator will now be 100 initially
//     (3, 2, 4, 6, 9)
//   ].reduce((accumulator, currentValue) => {
//     return accumulator + currentValue;
//   }, 100);

// function add(a = 0, b = 0) {
//   return a + b;
// }

// console.log(add());

// const multiply = (x, y) => {
//   // old way of setting default
//   // parameter values
//   if (typeof y === 'undefined') {
//     y = 1;
//   }

//   // using ternary operator instead
//   // of an if statement
//   y = typeof y === 'undefined' ? 1 : y;

//   return x * y;
// };

// function add(a = 0, b = 0) {
//   return a + b;
// }

// console.log(add(10));

// const nums = [5, 10, 11, 2, 1];

// console.log(Math.max(...nums));

// console.log()

function printVals(a, b, c) {
  console.log(a);
  console.log(b);
  console.log(c);
}

const names = ['john', 'jack', 'jane', 'brad'];
const naam = 'John';

// printVals(...names);

printVals(...naam);

Scratchpad #10

// const moderator = { canEdit: true, authority: 5 };

// const user = { canView: true, authority: 2.5 };

// const admin = { ...moderator, ...user, authority: 'HELLO' };

// console.log(admin);

// const arr = ['john', 'jack', 'james', 'jane', 'jamal'];

// console.log({ name: 'john', ...arr });

// > const details = {name: 'John', age: 25, job: 'programmer'}
// undefined
// >
// > details
// { name: 'John', age: 25, job: 'programmer' }
// >
// >
// > {...details, address: 'nagpada'}
// { name: 'John', age: 25, job: 'programmer', address: 'nagpada' }
// >
// >
// > let newDetails = {...details, address: 'nagpada'}
// undefined
// >
// > newDetails
// { name: 'John', age: 25, job: 'programmer', address: 'nagpada' }
// >
// >
// > nameDetails = {...newDetails, favMovie: 'Desh Drohi'}
// {
//   name: 'John',
//   age: 25,
//   job: 'programmer',
//   address: 'nagpada',
//   favMovie: 'Desh Drohi'
// }
// >
// >
// > nameDetails
// {
//   name: 'John',
//   age: 25,
//   job: 'programmer',
//   address: 'nagpada',
//   favMovie: 'Desh Drohi'
// }
// >
// > nameDetails = {...newDetails, [true, false, null]}
// nameDetails = {...newDetails, [true, false, null]}
//                                    ^

// Uncaught SyntaxError: Unexpected token ','
// >
// >
// > nameDetails = {...newDetails, someArr: [true, false, null]}
// {
//   name: 'John',
//   age: 25,
//   job: 'programmer',
//   address: 'nagpada',
//   someArr: [ true, false, null ]
// }
// >
// >
// > nameDetails = {...newDetails, ...[true, false, null]}
// {
//   '0': true,
//   '1': false,
//   '2': null,
//   name: 'John',
//   age: 25,
//   job: 'programmer',
//   address: 'nagpada'
// }
// >
// > nameDetails = {...newDetails, ...['john', 'jack', 'kamal']}
// {
//   '0': 'john',
//   '1': 'jack',
//   '2': 'kamal',
//   name: 'John',
//   age: 25,
//   job: 'programmer',
//   address: 'nagpada'
// }

// function add(num1, num2) {
//   return num1 + num2;
// }

// function add(...nums) {
//   return nums.reduce((acc, currVal) => acc + currVal);
// }

// console.log(add(10, 30, 50, 1, -50, 9));

// const printNames = (name1, name2, ...others) => {
//   console.log(name1);
//   console.log(name2);
//   console.log(others);
// };

// printNames('John', 'Jack', 'James', 'Jim', 'Jamal', 'Jane', 'Jessica');

// const users = ['john', 'jane', 'jack'];

// // const admin = users[0];
// // const moderator = users[1];
// // const user = users[2];

// // const [admin, moderator, user] = users;

// // const [admin, , user] = users;

// const [admin, ...others] = users;

// console.log(admin, others);

// const user = {
//   firstName: 'John',
//   lastName: 'Doe',
//   email: 'john.doe@gmail.com',
//   phone: '99982234567',
// };

// const firstName = user.firstName;

// const { firstName, ...others } = user;

// const { firstName, lastName, email: emailAddress, phone } = user;

// console.log(firstName, lastName, emailAddress, phone);

// const { firstName } = user;

// console.log(firstName);

// const greet = ({ firstName, lastName, age }) => {
//   console.log(
//     `My name is ${firstName} ${lastName}. I am ${age} years old. How are you?`
//   );
// };

// greet({ firstName: 'John', lastName: 'Doe', age: 25 });

// 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 info = {
//   highest,
//   lowest,
//   totalResult: total,
//   average,
// };

// console.log(info);

// 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);

// console.log(statistics);

// const username = 'janedoe';
// const role = 'admin';

// const profile = { [role]: username, [1 + 1]: 'hello' };

// console.log(profile);

// const addProperty = (obj, k, v) => {
//   return { ...obj, [k]: v };
// };

// console.log(addProperty({ firstName: 'john', lastName: 'Doe' }, 'age', 25));

const math = {
  add: (...nums) => nums.reduce((acc, currVal) => acc + currVal),
  div: (num1, num2) => num1 / num2,
  random: (max = 100) => Math.floor(Math.random() * max) + 1,
};

console.log(math.add(10, 20, 45, 3, 2, 12, 3));

console.log(math.random());

const math = {
  multiply: function (x, y) {
    return x * y;
  },
  divide: function (x, y) {
    return x / y;
  },
  subtract: function (x) {
    return x - x;
  },
};

function square(x) {
  return x * x;
}

const power = {
  square, // square: square
  cube: function (x) {
    return x * x * x;
  },
  hypercube: function (x) {
    return x * x * x * x;
  },
};

console.log(power.square(20)); // 400
console.log(power.cube(20)); // 8000
console.log(power.hypercube(20)); // 160000

Scratchpad #11

// const nums = [1, 2, 3, 4, 5];

// const printAll = (...nums) => {
//   console.log('This is the value of nums: ', nums);
//   let total = 0;
//   nums.forEach((num) => (total += num));
//   return total;
// };

// console.log(printAll(...nums));

// const math = {
//   multiply(x, y) {
//     console.log(this);
//     return x * y;
//   },
//   divide(x, y) {
//     return x / y;
//   },
//   subtract(x) {
//     return x - x;
//   },
//   add: (x, y) => x + y,
// };

// // console.log(math.multiply(10, 4));

// function greet() {
//   // console.log('Hello World!');
//   console.log(this);
// }

// function helloWorld() {
//   console.log('Hello');
// }

// greet();
// console.log('\n\n');
// math.multiply(10, 2);

// console.log(this);

// greet();
// window.greet();

// math.add()

// greet()

// var helloJohn = 'John Doe';
// let helloJOHN = 'John Doe';

// console.log(window);

// function greet() {
//   console.log(this);
// }

// // greet();

// function sayName() {
//   console.log(`My name is ${this.firstName} ${this.lastName}`);
// }

// const user = {
//   firstName: 'John',
//   lastName: 'Doe',
//   role: 'admin',
//   fullName() {
//     console.log(
//       `My full name is ${this.firstName} ${this.lastName} and I am an ${this.role}`
//     );
//   },
// };

// const user2 = {
//   firstName: 'Jack',
//   lastName: 'Ma',
//   role: 'Chairman',
//   fullName: user.fullName,
//   sayName,
// };

// user2.sayName();

// user.fullName();
// user2.fullName();
// // console.log(user.firstName);

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!`);
  },
  sayName: () => console.log(this),
};

// // const logDetails = user.logDetails;
// // user.logDetails();
// // logDetails();

// user.sayName();

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: function () {
    // this = hellos
    console.log(this);
    setInterval(() => console.log(this.pickMsg()), 1000);
    // setInterval(function () {
    //   console.log(this.pickMsg());
    // }, 1000);
  },
  // this = {}
  start2: () => setInterval(() => console.log(this.pickMsg()), 1000),

  // start() {
  //   // setInterval(function () {
  //   //   // will print 'TEST' every 1 sec
  //   //   // console.log('TEST');
  //   //   console.log(this.pickMsg());
  //   // }, 1000);
  //   console.log(this); // hellos
  //   setInterval(() => console.log(this.pickMsg()), 1000);
  // },
};

// console.log(hellos.pickMsg());

// setInterval(function () {
//   console.log('Hello World!');
// }, 2000);

hellos.start();

Scratchpad #12

// const helloNew = (designation, firstName, lastName) => {
//   return { [designation]: firstName, lastName };
// };

// console.log(helloNew('firstName', 'John', 'Doe'));

// const users = ['John', 'Jack', 'Jane'];

// const [admin, , user] = users;

// // console.log(admin);
// // console.log(moderator);
// console.log(user);

// const add = (num1, num2, ...nums) => {
//   return [num1, num2, nums];
// };

// console.log(add())

// 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(3, 4, 5);

// 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 moveX = (element, amount, delay, callback) => {
//   setTimeout(() => {
//     element.style.transform = `translateX(${amount}px)`;
//     if (callback) {
//       callback();
//     }
//   }, delay);
// };

// const btn = document.querySelector('button');

// moveX(btn, 100, 500, () => {
//   moveX(btn, 200, 500, () => {
//     moveX(btn, 300, 500, () => {
//       moveX(btn, 400, 500, () => {
//         moveX(btn, 500, 500, () => {
//           moveX(btn, 600, 500);
//         });
//       });
//     });
//   });
// });

// const willGetAPlayStation = new Promise((resolve, reject) => {
//   //
//   // reject();
//   resolve();
// });

// console.log(willGetAPlayStation);

const willGetAPlayStation = new Promise((resolve, reject) => {
  const rand = Math.random();

  if (rand < 0.5) {
    resolve();
  } else {
    reject();
  }
});

console.log(willGetAPlayStation);

Scratchpad #13

// const willGetAPlayStation = new Promise((resolve, reject) => {
//   const rand = Math.random();

//   if (rand < 0.5) {
//     resolve();
//   } else {
//     reject();
//   }
// });

// willGetAPlayStation
//   .then(() => console.log('Thank you for the Playstation!'))
//   .catch(() => console.log('F@#@$@#$ you'));

// console.log('Hello World!');

// const makePlayStationPromise = () => {
//   return new Promise((resolve, reject) => {
//     setTimeout(() => {
//       const rand = Math.random();
//       if (rand < 0.5) {
//         resolve();
//       } else {
//         reject();
//       }
//     }, 5000);
//   });
// };

// const result = makePlayStationPromise();

// result
//   .then(() => console.log('Thank You'))
//   .catch(() => console.log('Desh Drohi'));

// makePlayStationPromise()
//   .then(() => console.log('Hello World'))
//   .catch(() => console.log('Good bye world!'));

// console.log('Hello World');

// 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]; // page['/users']

//       if (data) {
//         resolve({ status: 200, data });
//       } else {
//         reject({ status: 404 });
//       }
//     }, 3000);
//   });
// };

// fakeRequest('/uses')
//   .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((response) => {
//     const id = response.data[0].id;
//     fakeRequest(`/users/${id}`)
//       .then((response) => {
//         const postId = response.data.topPostId;
//         fakeRequest(`/pots/${postId}`)
//           .then((response) => console.log(response))
//           .catch((err) => console.log(err));
//       })
//       .catch((err) => console.log(err));
//   })
//   .catch((err) => console.log(err));

// Refactored
fakeRequest('/users')
  .then((response) => {
    console.log("\nFirst request's response\n", response);
    const id = response.data[0].id;
    return fakeRequest(`/users/${id}`);
  })
  .then((response) => {
    console.log("\nSecond request's response\n", response);
    const postId = response.data.topPostId;
    return fakeRequest(`/posts/${postId}`);
  })
  .then((response) => {
    console.log("\nThird request's response\n");
    console.log(response);
  })
  .catch((err) => console.log(err));

Scratchpad #14

// const req = new XMLHttpRequest();

// // If request is successful
// req.onload = function () {
//   const data = JSON.parse(this.responseText);
//   console.log(data);
//   console.log(this.responseText);
// };

// // If request fails
// req.onerror = function (err) {
//   console.log('ERROR... THIS IS WRONG', err);
// };

// req.open('get', 'https://swapi.dev/api/people/1', true);
// req.setRequestHeader('Accept', 'application/json');

// req.send();

// console.log(req);

// GET
// POST
// PUT
// DELETE

// DOM

// <button type="submit">Click me</button>

// button.type = "button"

// const logo = document.getElementById('logo');

// logo.innerText = 'Dummy CORP';

// console.dir(logo);

// const paras = document.getElementsByTagName('p');
// // console.log(paras);

// for (let item of paras) {
//   item.innerText = 'Hello World';
//   // console.dir(item);
// }

// const notes = document.getElementsByClassName('note');

// console.log(notes);

// const points = document.getElementsByClassName('points')[0];
// const listItem = points.getElementsByClassName('imp-point')[0];
// console.dir(points);
// console.log(listItem);

// const heading = document.querySelector('h1');
// console.dir(heading);

// const logo = document.querySelector('#logo');
// console.dir(logo);

// const note = document.querySelector('.note');
// note.innerText = 'Hello World';
// console.dir(note);

// const paraNote = document.querySelector('img.notebook');
// console.dir(paraNote);

const notes1 = document.getElementsByClassName('.note');
const notes2 = document.querySelectorAll('.note');
console.log(notes);
console.log();

Scratchpad #15

// const p = document.querySelector('.imp-para');

// p.innerText = 'Hello World';

// document.body.innerText = 'Hello Body';

// const ul = document.getElementsByClassName('points');

// console.log(ul);
// ul[0].innerText = 'Hello';

// const h1 = document.querySelector('h1');
// const ul = document.querySelector('ul.points');
// const special = document.querySelector('.special');

// // console.log(ul.textContent);

// console.log(special.textContent);

// console.log(h1.textContent);

// const p = document.querySelector('.imp-para');

// // p.innerText = '<strong>Hello</strong> World';
// // p.innerHTML = '<strong>Hello</strong> World';

// p.innerHTML += ' How are <em>you?</em>';
// p.innerHTML = p.innerHTML.toUpperCase();

// console.log(p.innerHTML);

// const img = document.querySelector('img');
// console.log(img.width);

// const input = document.querySelectorAll('input');
// input[1].value = '34';
// // console.log(input[0].value);

// img.src = 'https://miro.medium.com/max/1200/1*mk1-6aYaf_Bes1E3Imhc0A.jpeg';

// const range = document.querySelector('input[type="range"]');

// console.log(range.getAttribute('max'));
// console.log(range.getAttribute('min'));
// console.log(range.getAttribute('type'));

// range.setAttribute('type', 'number');
// range.setAttribute('value', 1500);

// const firstLi = document.querySelector('li');

// // console.log(firstLi.parentElement.parentElement.parentElement);

// // const ul = document.querySelector('ul');

// // console.log(document.body.children);

// // console.log(firstLi.nextElementSibling.nextElementSibling);
// console.log(firstLi.nextElementSibling.previousElementSibling);

// const ul = document.querySelector('ul');
// const lis = ul.children;

// console.log(lis);

// for (let listItem of lis) {
//   // listItem.innerText = '<strong>CHANGED</strong>';
//   // console.log(listItem.style);
//   listItem.style.color = 'red';
//   listItem.style.backgroundColor = 'yellow';
//   listItem.style.border = '4px solid green';
//   listItem.style.padding = '5px 10px';
//   listItem.style.fontSize = '40px';
// }

// 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 para = document.querySelector('.imp-para');

// console.log(para.style);
// console.log(getComputedStyle(para));

// const paraStyles = getComputedStyle(para);

// para.style.textDecoration = 'underline';

// console.log(paraStyles.textDecoration);

// para.setAttribute('class', 'fancy-text fancy-text-cancelled');
// para.setAttribute('class', 'fancy-text');

para.classList.add('fancy-text');
// para.classList.remove('cancelled');
para.classList.toggle('cancelled');

index.html for JS

<!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>Hello World</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <header>
      <h1 id="logo">Acme Corp</h1>
      <p class="note">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Ea, fugiat?
      </p>
    </header>
    <section>
      <p id="intro" class="note">
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Incidunt aut
        molestiae suscipit officia consequatur esse facere modi earum eaque
        recusandae voluptate iste fuga saepe, ipsum perspiciatis dignissimos
        facilis, sequi cupiditate, neque non repellat illum blanditiis?
        Voluptatum similique exercitationem accusantium natus.
      </p>
      <img
        class="note"
        src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png"
        alt="Car"
        width="50%"
      />
    </section>
    <p class="imp-para cancelled">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto fugiat, in
      atque incidunt sint <strong>adipisci suscipit</strong> sed doloribus
      architecto! Quasi.
    </p>
    <ul class="points">
      <li class="imp-point">Lorem ipsum dolor sit amet.</li>
      <li>Hello World</li>
      <li>Jack Ma</li>
      <li>Xi Jingping</li>
      <li>Lorem ipsum dolor sit amet.</li>
    </ul>

    <!-- <p class="special">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis,
      consectetur.
      <script>
        console.log('HELLO WORLD!');
      </script>
    </p> -->
    <button class="points">Click me</button>
    <br />
    <br />
    <form>
      <label for="firstName">First Name</label>
      <input type="text" id="firstName" value="John Doe" /><br />
      <label for="age">Age</label>
      <input type="number" id="age" /><br />
      <input type="range" min="10" max="100" /><br />
      <input type="submit" value="Submit Form" />
    </form>

    <script src="./scratchpad_15.js"></script>
  </body>
</html>





<!-- CSS -->
<!-- .fancy-text {
  color: darkgoldenrod;
  font-weight: bold;
  border: 3px double darkolivegreen;
  font-family: sans-serif;
  padding: 10px 20px;
  font-size: 16px;
}

.cancelled {
  text-decoration: line-through;
} -->

Scratchpad #16

// const h2 = document.createElement('h2');

// h2.innerText = 'This is a h2';
// h2.style.color = 'red';
// h2.style.fontSize = '40px';
// h2.classList.add('fancy-text');
// // <h2 style="color: red; font-size: 40px">This is a h2</h2>

// const section = document.createElement('section');
// // <section></section>

// section.appendChild(h2);
// // <section><h2 style="color: red; font-size: 40px">This is a h2</h2></section>

// const img = document.createElement('img');
// img.setAttribute(
//   'src',
//   'https://images.unsplash.com/photo-1627392689954-0a4d150687a7?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80'
// );
// img.style.width = '400px';
// // <img src="...." style="width: 400px" />

// const imgLink = document.createElement('a');
// imgLink.setAttribute(
//   'href',
//   'https://images.unsplash.com/photo-1627392689954-0a4d150687a7?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80'
// );
// imgLink.setAttribute('target', '_blank');
// // <a href="...." target="_blank"></a>

// imgLink.appendChild(img);
// // <a href="...." target="_blank"><img src="...." style="width: 400px" /></a>

// section.appendChild(imgLink);
// // <section>
// //    <h2 style="color: red; font-size: 40px">This is a h2</h2>
// //    <a href="...." target="_blank"><img src="...." style="width: 400px" /></a>
// // </section>

// // document.body.appendChild(section);

// const root = document.querySelector('#root');

// root.appendChild(section);

// const todos = document.querySelector('#todos');

// const newTask = document.createElement('li');
// newTask.innerText = 'Brand new task to complete';
// newTask.classList.add('todo');
// newTask.style.color = 'purple';
// newTask.style.fontWeight = 'bold';

// // todos.appendChild(newTask);

// const firstTask = document.querySelector('li');
// const helloTask = document.querySelector('.hello');

// // todos.insertBefore(newTask, firstTask);
// todos.insertBefore(newTask, helloTask);

// const b = document.createElement('b');
// b.innerText = 'HELLO Universe';

// const p = document.querySelector('p');

// // p.insertAdjacentElement('beforebegin', b);
// // p.insertAdjacentElement('afterbegin', b);
// p.insertAdjacentElement('beforeend', b);
// p.insertAdjacentElement('afterend', b);

// const b = document.createElement('b');
// b.innerText = 'HELLO WORLD';
// const i = document.createElement('i');
// i.innerText = 'GOODBYE GALAXY';

// const p = document.querySelector('p');

// p.append(b, i);
// p.prepend(i, b);

// const todos = document.querySelector('#todos');

// const firstTask = todos.querySelector('li');
// console.log(firstTask);
// const secondTask = firstTask.nextElementSibling;
// console.log(secondTask);

// // todos.removeChild(firstTask);
// // todos.removeChild(secondTask);

// firstTask.remove();
// secondTask.remove();

const btn = document.querySelector('#btn1');

// btn.onclick = console.log('Button Pressed');

// let count = 0;

// btn.onclick = function () {
//   count++;
//   console.log(`Button Pressed - ${count}`);
// };

// btn.onclick = function () {
//   console.log('Second event call');
// };

const sec = document.querySelector('#sec');

const addEl = () => {
  const p = document.createElement('p');
  p.innerText = 'New paragraph';
  p.style.display = 'inline';
  sec.appendChild(p);
};

btn.addEventListener('click', function () {
  console.log('I got clicked!');
});

btn.addEventListener('click', function () {
  alert('POPUP!');
});

btn.addEventListener('mouseover', function () {
  console.log('Hovered!!');
  addEl();
});

Scratchpad #17

// // const btn = document.querySelector('#btn1');

// // btn.addEventListener('click', () => {
// //   console.log('ALERT MESSAGE FROM CLICK EVENT');
// // });

// // btn.addEventListener('mouseover', () => {
// //   console.log('I was hovered');
// // });

// // btn.addEventListener('mouseout', () => {
// //   console.log('The point is no longer on me');
// // });

// // window.addEventListener('scroll', function () {
// //   console.log('Stop Scrolling!');
// // });

// // const btn = document.querySelector('button');

// // btn.addEventListener('mouseover', function () {
// //   // console.log('Mouse over button')
// //   // To get the current height and width of your browser screen
// //   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';
// // });

// // // document.addEventListener('click', () => {
// // //   console.log(window.innerHeight);
// // //   console.log(window.innerWidth);
// // // });

// const colors = [
//   'red',
//   'orange',
//   'yellow',
//   'green',
//   'blue',
//   'purple',
//   'indigo',
//   'violet',
// ];

// const container = document.querySelector('#boxes');

// // const printColor = function (box) {
// //   console.log(box.style.backgroundColor);
// // };

// const printColor = function (event) {
//   console.log(this.style.backgroundColor);
//   // console.log(event);

//   if (event.altKey) {
//     console.log('Shoot the machine gun');
//   }
// };

// const changeColor = function () {
//   const h1 = document.querySelector('h1');
//   h1.style.color = this.style.backgroundColor;
//   h1.innerText = this.style.backgroundColor + ' selected';
// };

// for (let color of colors) {
//   const box = document.createElement('div'); // Create a square box

//   box.style.backgroundColor = color; // Style the box
//   box.classList.add('box'); // Add a class

//   container.append(box); // Append box to container

//   // Add event listener to the box
//   // box.addEventListener('click', function () {
//   //   // console.log('Box clicked!')
//   //   // console.log(box.style.backgroundColor);
//   //   // document.body.style.backgroundColor = color;
//   //   printColor(box);
//   // });

//   box.addEventListener('click', printColor);
//   box.addEventListener('click', changeColor);
// }

// const box = document.querySelector('#box');

// document.body.addEventListener('keydown', function (evt) {
//   // console.log(evt);

//   if (evt.key === 's') {
//     // console.dir(box);
//     box.style.bottom = `-${box.offsetTop + 10}px`;
//   } else if (evt.key === 'd') {
//     console.dir(box);
//     box.style.left = `${box.offsetLeft + 10}px`;
//   } else if (evt.key === 'a') {
//     console.dir(box);
//     box.style.left = `-${box.offsetLeft + 10}px`;
//   } else if (evt.key === 'w') {
//     // console.dir(box);
//     console.log(`-${box.offsetTop - 10}px`);
//     box.style.top = `-${box.offsetTop - 10}px`;
//   }
// });

// const taskAdd = document.querySelector('#addtask');
// const todos = document.querySelector('#todos');

// taskAdd.addEventListener('keypress', function (e) {
//   if (e.key === 'Enter') {
//     if (!this.value) {
//       return;
//     }
//     const newTaskText = this.value;
//     const newTask = document.createElement('li');
//     newTask.innerText = newTaskText;
//     todos.append(newTask);
//     this.value = '';
//   }
// });

const form = document.querySelector('#payment-form');

const creditCard = document.querySelector('#cc');
const terms = document.querySelector('#terms');
const brand = document.querySelector('#brand');

form.addEventListener('submit', function (e) {
  // alert('FORM SUBMITTED');
  e.preventDefault(); // prevent the default form behavior

  console.log('cc', creditCard.value);
  console.log('terms', terms.checked);
  console.log('brand', brand.value);
});

HTML/CSS for JS

<!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>Hello World</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <!-- <div id="root"></div> -->
    <!-- <ul id="todos">
      <li>First task</li>
      <li class="hello">Hello World</li>
    </ul>

    <p>
      Lorem ipsum, dolor sit amet consectetur adipisicing elit. Excepturi
      provident amet delectus reiciendis iure recusandae.
    </p>

    <button id="btn1">Click Me</button>

    <section id="sec" style="height: 2000px"></section> -->

    <!-- <button>Click me</button> -->

    <!-- <h1>Color</h1> -->

    <!-- <div id="boxes"></div> -->

    <!-- <div id="box"></div> -->

    <!-- <input type="text" id="addtask" placeholder="Write task" />
    <hr />
    <ol id="todos"></ol> -->

    <form id="payment-form">
      <input type="text" id="cc" />
      <div>
        <input type="checkbox" id="terms" />
        <label for="terms">I agree to terms</label>
      </div>
      <input type="text" id="brand" /><br />
      <button type="submit">Submit Form</button>
    </form>

    <script src="./scratchpad_17.js"></script>
  </body>
</html>

Scratchpad #19

// function getData() {
//   const data = axios.get('https://swapi.dev/api/planets');
//   return data.then((res) => res.data);
// }

// console.log(getData());

// async function greet() {
//   return 'Hello!';
// }

// async function problem() {
//   throw new Error('Problem!');
// }

// console.log(greet());
// console.log(problem());

// async function add(x, y) {
//   if (typeof x !== 'number' || typeof y !== 'number') {
//     throw 'X and Y must be numbers';
//   }
//   return x + y;
// }

// console.log(add(10, 5));
// console.log(add(10, 'Hello'));

// add(10, '5')
//   .then((data) => console.log(data))
//   .catch((err) => console.log(err));

// function getPlanets() {
//   return axios.get('https://swapi.dev/api/planets');
// }

// console.log(getPlanets());

// function getPlanets1() {
//   const res = axios.get('https://swapi.dev/api/planets');
//   console.log(res);
// }

// async function getPlanets2() {
//   const planets = await axios.get('https://swapi.dev/api/planets');
//   const film = await axios.get(planets.data.results[0].films[0]);
//   const vehicle = await axios.get(film.data.vehicles[0]);
//   console.log(vehicle.data);
//   console.log('########## Hello World ##########');
// }

// function getPlanets3() {
//   axios
//     .get('https://swapi.dev/api/planets')
//     .then((res) => axios.get(res.data.results[0].films[0]))
//     .then((res) => axios.get(res.data.vehicles[0]))
//     .then((res) => console.log(res.data));
// }

// // getPlanets1();
// // console.log(getPlanets2());
// getPlanets2();

// getPlanets3();

// async function getPlanets2() {
//   try {
//     const planets = await axios.get('https://swapi.dev/api/plaets');
//     const film = await axios.get(planets.data.results[0].films[0]);
//     const vehicle = await axios.get(film.data.vehicles[0]);
//     console.log(vehicle.data);
//   } catch (err) {
//     console.log('SOMETHING WENT WRONG', err);
//   }
// }

// // getPlanets2().catch((err) => console.log('SOMETHING WENT WRONG'));

// getPlanets2();

// const getPokemon = async () => {
//   const pokemonPromise1 = axios.get('https://pokeapi.co/api/v2/pokemon/1');
//   const pokemonPromise2 = axios.get('https://pokeapi.co/api/v2/pokemon/2');
//   const pokemonPromise3 = axios.get('https://pokeapi.co/api/v2/pokemon/3');

//   // const pokemon1 = await pokemonPromise1;
//   // const pokemon2 = await pokemonPromise2;
//   // const pokemon3 = await pokemonPromise3;

//   const results = await Promise.all([
//     pokemonPromise1,
//     pokemonPromise2,
//     pokemonPromise3,
//   ]);

//   console.log(results);

//   // console.log(pokemon1.data);
//   // console.log(pokemon2.data);
//   // console.log(pokemon3.data);
// };

// getPokemon();

// axios.get('https://pokeapi.co/api/v2/pokemon/').then((res) => {
//   res.data.results.forEach((data) =>
//     axios.get(data.url).then((res) =>
//       res.data.types.forEach((p) => {
//         p.type.name !== 'flying' ? console.log(p) : null;
//       })
//     )
//   );
// });

// async function getPokemon() {
//   const pokemons = await axios.get('https://pokeapi.co/api/v2/pokemon/');

//   const pokemonsData = pokemons.data.results.map(async (pokemon) => {
//     const result = await axios.get(pokemon.url);
//     return result.data;
//   });

//   console.log(pokemonsData);
// }

// getPokemon();

// 1 = get all pokemon data for each pokemon and push it in an array

async function getPokemons() {
  const allPokemons = []; // 1. Fill this with complete pokemon objects

  const pokemons = await axios.get('https://pokeapi.co/api/v2/pokemon/');

  pokemons.data.results.forEach(async (pokemon) => {
    const result = await axios.get(pokemon.url);
    allPokemons.push(result.data);
  });

  console.log(allPokemons);

  // allPokemons.forEach((data) => console.log(data));
}

getPokemons();

Scratchpad #20

// const user = {
//   firstName: 'John',
//   lastName: 'Doe',
//   age: 25,
//   greet() {
//     console.log(`My name is ${this.firstName} ${this.lastName}`);
//   },
// };

// const data = [20, 45, 245, 245, 1, 2];

// console.log(user);
// console.log(data);

// function initializeDeck() {
//   const deck = [];
//   const suits = ['hearts', 'diamonds', 'spades', 'clubs'];
//   const values = '2,3,4,5,6,7,8,9,10,J,Q,K,A';
//   for (let value of values.split(',')) {
//     for (let suit of suits) {
//       deck.push({ value, suit });
//     }
//   }
//   return deck;
// }

// function drawCard(deck, drawnCards) {
//   const card = deck.pop();
//   drawnCards.push(card);
//   return card;
// }

// function drawMultiple(numCards, deck, drawnCards) {
//   const cards = [];
//   for (let i = 0; i < numCards; i++) {
//     cards.push(drawCard(deck, drawnCards));
//   }
//   return cards;
// }

// function shuffle(deck) {
//   // loop over array backwards
//   for (let i = deck.length - 1; i > 0; i--) {
//     // pick random index before current element
//     let j = Math.floor(Math.random() * (i + 1));
//     [deck[i], deck[j]] = [deck[j], deck[i]];
//   }
//   return deck;
// }

// const deck = initializeDeck();
// shuffle(deck);

// const hand = [];

// drawCard(deck, hand);
// drawMultiple(2, deck, hand);

// console.log(deck);
// console.log(hand);

// --------------------------------

// const makeDeck = () => {
//   return {
//     deck: [],
//     drawnCards: [],
//     suits: ['hearts', 'diamonds', 'spades', 'clubs'],
//     values: '2,3,4,5,6,7,8,9,10,J,Q,K,A',
//     initializeDeck() {
//       const { suits, values, deck } = this;
//       for (let value of values.split(',')) {
//         for (let suit of suits) {
//           deck.push({ value, suit });
//         }
//       }
//       return deck;
//     },
//     drawCard() {
//       const card = this.deck.pop();
//       this.drawnCards.push(card);
//       return card;
//     },
//     drawMultiple(numCards) {
//       const cards = [];
//       for (let i = 0; i < numCards; i++) {
//         cards.push(this.drawCard());
//       }
//       return cards;
//     },
//     shuffle() {
//       const { deck } = this;
//       for (let i = deck.length - 1; i > 0; i--) {
//         // console.log(deck);
//         let j = Math.floor(Math.random() * (i + 1));
//         [deck[i], deck[j]] = [deck[j], deck[i]];
//       }
//     },
//   };
// };

// const deck1 = makeDeck();
// const deck2 = makeDeck();
// const deck3 = makeDeck();

// console.log(deck);

// deck.initializeDeck();
// // deck.shuffle();
// deck.drawCard();
// deck.drawMultiple(10);

// console.log(deck1, deck2, deck3);

// function person(firstName, lastName, age) {
//   return {
//     firstName,
//     lastName,
//     age,
//   };
// }
// const jack = person('Jack', 'Doe', 30);

// function Person(firstName, lastName, age) {
//   this.firstName = firstName;
//   this.lastName = lastName;
//   this.age = age;
// }

// Person.prototype.sayName = function () {
//   console.log(`My name is ${this.firstName} ${this.lastName}`);
// };
// Person.prototype.helloWorld = 'Hello World';

// const john = new Person('John', 'Doe', 25);
// const jack = new Person('Jack', 'Ma', 40);

// john.sayName();
// console.log(john.helloWorld);

// console.log(jack);
// jack.sayName();
// // console.log();

// class Person {
//   constructor(firstName, lastName, age) {
//     this.firstName = firstName;
//     this.lastName = lastName;
//     this.age = age;
//   }

//   sayName = function () {
//     console.log(`My name is ${this.firstName} ${this.lastName}`);
//   };
// }

// const john = new Person('John', 'Doe', 25);
// console.log(john);

// class Deck {
//   constructor() {
//     this.deck = [];
//     this.drawnCards = [];
//     this.suits = ['hearts', 'diamonds', 'spades', 'clubs'];
//     this.values = '2,3,4,5,6,7,8,9,10,J,Q,K,A';
//   }

//   initializeDeck() {
//     const { suits, values, deck } = this;
//     for (let value of values.split(',')) {
//       for (let suit of suits) {
//         deck.push({ value, suit });
//       }
//     }
//     return deck;
//   }

//   drawCard() {
//     const card = this.deck.pop();
//     this.drawnCards.push(card);
//     return card;
//   }

//   drawMultiple(numCards) {
//     const cards = [];
//     for (let i = 0; i < numCards; i++) {
//       cards.push(this.drawCard());
//     }
//     return cards;
//   }

//   shuffle() {
//     const { deck } = this;
//     for (let i = deck.length - 1; i > 0; i--) {
//       let j = Math.floor(Math.random() * (i + 1));
//       [deck[i], deck[j]] = [deck[j], deck[i]];
//     }
//   }
// }

// const deck1 = new Deck();
// const deck2 = new Deck();

// console.log(deck1, deck2);

// class User {
//   constructor(username, password) {
//     this.username = username;
//     this.password = password;
//   }

//   login(pass) {
//     if (pass === this.password) {
//       console.log('Welcome back');
//     } else {
//       console.log('Incorrect password entered.');
//     }
//   }
// }

// class Subscriber extends User {
//   logout() {
//     console.log('You have successfully logged out, Subscriber');
//   }
// }

// class Creator extends User {
//   constructor(username, password, totalVideos = 0) {
//     super(username, password);
//     this.totalVideos = totalVideos;
//   }

//   uploadVideo(videoName) {
//     this.totalVideos++;
//     console.log(
//       `Thank you for uploading ${videoName}.\nChannel: ${this.totalVideos} video(s)`
//     );
//   }

//   logout() {
//     console.log('You have successfully logged out, Creator');
//   }
// }

// const john = new User('johndoe', 'john@123');
// const jack = new Subscriber('jackdoe', 'jack@123');

// john.login('john@123');
// jack.login('john@123');

// let a = 'hello';

// a = 5;
// a = 10;

const section = document.querySelector('section');

function createElement(name, data, styles) {
  const el = document.createElement(name);
  el.innerText = data;

  for (let style of styles) {
    // el.style[] = style
  }
}

const para = createElement('p', 'This is a paragraph', {
  color: 'red',
  fontSize: '20px',
});

const button = createElement('button', 'Click me');

section.append(para, button);

React Index File

<!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>React App</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div id="root"></div>

    <script src="https://unpkg.com/react@^16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@^16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

    <script type="text/babel">
      // const el = React.createElement('h1', {
      //   className: 'title',
      //   children: 'Hello World! How are you!',
      // });

      // const headingEl2 = React.createElement('h1', {}, 'Hello World!');
      // const paraEl = React.createElement(
      //   'p',
      //   {},
      //   'I am rendered using React JS'
      // );

      // const children = 'Hello World. This is the page title';
      // const className = 'title';
      // const props = { children, className };

      // const headingEl = <h1 className="title">Hello World</h1>;
      // const headingEl = <h1 className="title" children="Hello World" />;
      // const headingEl = <h1 {...props} className="subtitle" />;

      // const el = React.createElement('section', {
      //   children: [headingEl, paraEl],
      // });

      // const message = 'Hello World';
      // const myClassName = 'special';

      // const element = <h1 className={myClassName}>{message.toUpperCase()}</h1>;

      // Component
      const message = (props) => {
        return <p className={props.className}>{props.children}</p>;
      };

      const header = (props) => {
        return (
          <header>
            <h2>{props.title}</h2>
            <nav>
              <a href={props.linkUrl}>{props.linkText}</a>
            </nav>
          </header>
        );
      };

      // const element = (
      //   <section>
      //     {message({
      //       children: 'Hello World, this is a paragraph',
      //       className: 'imp-para',
      //     })}
      //     {message({ children: 'Second para', className: 'text' })}
      //   </section>
      // );

      // Button/Link component
      const Btn = (props) => {
        if (props.type === 'button') {
          return (
            <button onClick={props.callback} className={props.className}>
              {props.children}
            </button>
          );
        } else {
          return (
            <a href={props.url} className={props.className}>
              {props.children}
            </a>
          );
        }
      };

      // const element = header({
      //   title: 'My Company Logo',
      //   linkUrl: 'google.com',
      //   linkText: 'Google',
      // });

      // {btn({
      //       type: 'button',
      //       label: 'Click me',
      //       callback: () => alert('Hello World'),
      //     })}
      //     {btn({
      //       url: 'https://u5b.f44.myftpupload.com',
      //       linkText: 'RST Forum',
      //       className: 'rst',
      //     })}

      const element = (
        <section>
          {message({ children: 'Some Information', className: 'text' })}

          {React.createElement(Btn, {
            className: 'rst',
            url: 'https://u5b.f44.myftpupload.com',
            linkText: 'RST Forum',
          })}

          <Btn
            type="button"
            callback={() => console.log('Hello World')}
            children="Say Hello"
            className="testclass"
          />

          <Btn
            type="button"
            callback={() => console.log('Hello World')}
            className="testclass"
          >
            Say Hello World
          </Btn>
        </section>
      );

      ReactDOM.render(element, document.querySelector('#root'));
    </script>
  </body>
</html>