Lab guideFullStack

Full Stack Sunday Afternoon

Last updated 6 December 2023

Full Stack Sunday Afternoon

Scratchpad #1 and #2 JAVASCRIPT

'hello world, welcome to rst forum.'.indexOf('welcome');

// 13.toUpperCase()

Javascript

// let cart = 10;
// let itemPrice = 5;

// let message =
//   'You have ' + cart + ' items in your cart. Total price = ' + cart * itemPrice;

// // console.log(message);

// message = `You have ${cart} ${'items'.toUpperCase()} in your cart. Total price = $${
//   cart * itemPrice
// }`;

// // console.log(message);

// let age = 25;
// message = 'You are ' + age + ' years old';
// message = `You are ${age * 2} years old`;

// console.log(message);

// let age = 21;

// if (10) {
//   console.log('You are allowed to enter.');
// }

// let username = 'johndoe';

// if (username) {
//   console.log('You can see the contents of this page');
// } else if (username === 'admin') {
//   console.log('You can do whatever you want');
// } else {
//   console.log('Get out!');
// }

// let age = 21;

// if (age >= 21) {
//   console.log('You can enter and drink');
// } else if (age >= 18) {
//   console.log('Not allowed');
// } else if (age === 2) {
//   console.log('ajsndkjas');
// }

// 'hello'.toUpperCase().indexOf();

// let age = 78;

// if (age > 18) {
//   console.log('Entry Granted!');
// } else if (age >= 21) {
//   console.log('Drinks Allowed');
// } else if (age >= 65) {
//   console.log('Drinks FREE!');
// } else {
//   console.log('ENTRY DENIED!');
// }

// let age = 1;

// if (age >= 18) {
//   if (age >= 65) {
//     console.log('Drinks FREE!');
//   } else if (age >= 21) {
//     console.log('Drinks Allowed');
//   } else {
//     console.log('Entry Granted!');
//   }
// } else {
//   console.log('ENTRY DENIED!');
// }

// 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('Password is too short');
// }

// !!!!!(!!!!(false && true) && !!!!(!true && false))

// let age = 1;

// if (age >= 18) {
//   if (age >= 65) {
//     console.log('Drinks FREE!');
//   } else if (age >= 21) {
//     console.log('Drinks Allowed');
//   } else {
//     console.log('Entry Granted!');
//   }
// } else {
//   console.log('ENTRY DENIED!');
// }

// if (age >= 18 && and < 21) {
//   console.log('Entry Granted!');
// } else if (age >= 21 && age < 65) {
//   console.log('Drinks Allowed');
// } else if (age >= 65) {
//   console.log('Drinks FREE!');
// } else {
//   console.log('ENTRY DENIED!');
// }

// let day = 5;

// 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 day code');
// }

// let day = 43;

// 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('Sunday');
//     break;
//   default:
//     console.log('Day is invalid');
// }

let age = 10;

// if (age > 18) {
//   console.log('You can enter');
// } else {
//   console.log('You cannot enter');
// }

// age > 18 ? console.log('You can enter') : console.log('You cannot enter');

// age >= 18 && age < 21
//   ? console.log('You can enter')
//   : age > 21 && age < 65
//   ? console.log('You can drink')
//   : age >= 65
//   ? console.log('Drinks are free')
//   : console.log('Not allowed');

let status = 'online';

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

console.log(color);

Scratchpad #4

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

// for (let num = 1; num <= 10; num++) {
//   console.log(`${num}*${num}=${num * num}`);
// }

// for (let i = 50; i >= 0; i -= 5) {
//   console.log(i);
// }

// for (let i = 20; i >= 0; i--) {
//   console.log(i);
// }

// const nums = [12, 34, 56, 34, 78, 54, 23, 12];

// 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 c = 0; c < movies.length; c++) {
//   let movie = movies[c];
//   console.log(movie.movieName + '\n\n' + c);
// }

// const movies = { movieName: 'Inception', rating: 3.8 };

// for (let c = 0; c < 2; c++) {
//   console.log(movies[c]);
// }

// const arr = [1, 2, 3];

// arr[-1]

// {0: 1, 1: 2, 2: 3}

// const word = 'Hello World';
// let reversedWord = '';

// for (let i = word.length - 1; i >= 0; i--) {
//   // console.log(word[i]);
//   reversedWord += word[i];
// }

// console.log(reversedWord);

// for (let i = 0; i < 10; i++) {
//   console.log(`OUTER LOOP: ${i}`);

//   for (let j = 0; j < 10; j++) {
//     console.log(`   INNER LOOP: ${j}`);
//   }
// }

// const gameBoard = [
//   [
//     [1, 2, 3, 4],
//     [5, 6, 7, 8],
//     [9, 10, 11, 12],
//     [13, 14, 15, 16],
//   ],
//   [
//     [1, 2, 3, 4],
//     [5, 6, 7, 8],
//     [9, 10, 11, 12],
//     [13, 14, 15, 16],
//   ],
//   [
//     [1, 2, 3, 4],
//     [5, 6, 7, 8],
//     [9, 10, 11, 12],
//     [13, 14, 15, 16],
//   ],
//   [
//     [ , 2, 3, 4],
//     [5, 6, 7, 8],
//     [9, 10, 11, 12],
//     [13, 14, 15, 16],
//   ],
// ];

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

// const vals = [];

// for (let i = 0; i < 5; i++) {
//   let random = Math.floor(Math.random() * 100) + 1;
//   vals.push(random);
// }

// console.log(vals);

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

// let i = 0;

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

// console.log(i);

// const randomNum = Math.floor(Math.random() * 5000) + 1; // 33

// let guess = Math.floor(Math.random() * 5000) + 1; // 33

// while (guess !== randomNum) {
//   console.log(`You guessed ${guess}. Random number was ${randomNum}`);

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

// console.log(
//   `You guess was ${guess}. Random number was ${randomNum}. Good job.`
// );

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

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

// console.log(`\nGame over!\nTarget: ${target} | Guess: ${guess}.`);

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

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

//   if (target === guess) {
//     break; // break out of the loop when condition is true
//   }

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

// console.log(`\nGame over!\nTarget: ${target} | Guess: ${guess}.`);

// const nums = [12, 123, 123, 423, 54, 56, 456345, 233, 1212];

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

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

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

// for (let char of 'hello') {
//   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 num of row) {
//     console.log(num);
//     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 item of Object.keys(productPrices)) {
// //   console.log(productPrices[item]);
// // }

// for (let item in productPrices) {
//   console.log(productPrices[item]);
// }

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

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

// let fullName = 'John Doe';

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

// // greet('Jack Doe');
// // greet('Jackie Chan');

// greet('Jack Ma', 'Hello');

// function add(a, b) {
//   console.log(a + b);
// }

// add(10, 20);
// add();

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

// 'john'.toUpperCase();

// function add(x, y) {
//   console.log(x + y);
// }

// add(10, 5);

// let score = 100 / 4 + 5;

// let newScore = score + score * 2;

// console.log(newScore / score);

// function add(x, y) {
//   // console.log('Hello World');
//   return x + y;
// }

// let score = add(10, 8);

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

function square(num) {
  if (typeof num === 'number') {
    return num * num;
  } else {
    return 'Please provide a number';
  }
}

console.log(square(12334));

Scratchpad #5

// const arr = [];

// for (let i = 0; i < 4; i++) {
//   const innerArr = [];

//   for (let j = 0; j < 4; j++) {
//     let random = Math.floor(Math.random() * 100) + 1;
//     innerArr.push(random);
//   }

//   arr.push(innerArr);
// }

// console.log(arr);

// function greet(name, message) {
//   const result = `${message}, ${name}`;
//   return result;
// }

// greet('Jack');

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

// greet();

// function add(x, y) {
//   if (typeof x !== 'number' || typeof y !== 'number') {
//     return 'Please provide a valid number';
//   }
//   return x + y;
// }

// console.log(add(10, [1, 2, 3]));

// let fullName = 'John Doe';

// function greet() {
//   let fullName = 'Jack Ma';
//   console.log(fullName);
// }

// function greetAgain(name) {
//   console.log(name);
// }

// let fullName = 'John Doe';
// greetAgain(fullName);
// greetAgain('Zuhair');

// console.log(fullName);

// let name = 'Jack Smith';

// if (true) {
//   let name = 'John Doe';
//   console.log(name);
// }

// console.log(name);

// for (var i = 0; i < 5; i++) {
//   var name = 'Tom';
//   console.log(i, name);
// }

// console.log(i);
// // console.log(name);

// function outer() {
//   let movie = 'Inception';

//   function inner() {
//     // const movie = 'Shutter Island';
//     console.log(movie);
//   }

//   console.log(movie);

//   inner();
// }

// outer();

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

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

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

// 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, 5, add));

// console.log(
//   math(10, 5, function (a, b) {
//     return a / b;
//   })
// );

// const maths = {
//   pi: 3.14,
//   add: function (a, b) {
//     return a + b;
//   },
//   sub: function (a, b) {
//     return a - b;
//   },
//   div: function (a, b) {
//     return a / b;
//   },
//   mul: function (a, b) {
//     return a * b;
//   },
// };

// console.log(maths.pi);
// console.log(maths.add(10, 5));
// console.log(maths.mul(10, 5));

// const maths2 = [
//   function (a, b) {
//     return a + b;
//   },
//   function (a, b) {
//     return a - b;
//   },
// ];

// console.log(maths2[0](10, 5));

// function math(a, b, fn) {
//   return fn(a, b);
// }

// function test() {
//   function test2() {
//     return 'hello';
//   }
// }

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

// repeat(function () {
//   console.log('hello world');
// }, 10);

// function chance(f1, f2) {
//   const random = Math.random();

//   if (random > 0.5) {
//     f1();
//   } else {
//     f2();
//   }
// }

// chance(
//   function () {
//     console.log('John Doe');
//   },
//   function () {
//     console.log('Jack Doe');
//   }
// );

// // factory function
// function raiseBy(num) {
//   return function (x) {
//     return x ** num;
//   };
// }

// const square = raiseBy(2);
// const cube = raiseBy(3);
// const tesseract = raiseBy(4);

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

// tesseract(3);
// console.log(raiseBy(5));

// const test = raiseBy(5);

// test(10);

// 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 freeDrinks = isBetween(65, 100);

// // const isUnderAge = function (num) {
// //   return num >= 0 && num <= 18;
// // };

// // console.log(isUnderAge(12));
// console.log(canDrink(12));

// function math(a, b, fn) {
//   return fn(a, b);
// }

// const result = math(10, 3, function (a, b) {
//   return a * b;
// });

// console.log(result);

// console.log(
//   math(10, 20, function (a, b) {
//     return a + b;
//   })
// );

// setTimeout(function () {
//   console.log('Hello World');
// }, 5000);

// greet();

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

// console.log(fullName);

// var fullName = 'John Doe';

// let fullName = 'John Doe';
// console.log(fullName);

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

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

// technically let and const are hoisted
// but they are not initialized
// meaning javascript knows that these
// variables exist internally

// const nums = [12, 345, 21, 12, 35, 2, 12123, 123];

// nums.forEach(function (num, i) {
//   console.log(i, num);
// });

// for (let num of nums) {
//   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,
//   },
// ];

// console.log(movies.forEach(function (movie) {
//   console.log(movie.title.toUpperCase());
// }));

// for (let movie of movies) {
//   console.log(movie.title.toUpperCase());
// }

// const uppercasedNames = [];

// for (let name of names) {
//   uppercasedNames.push(name.toUpperCase());
// }

// console.log(uppercasedNames);
// const names = ['john', 'jack', 'jane', 'james'];

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

// console.log(uppercasedNames2);

// console.log(
//   names.map(function (name) {
//     return name.toUpperCase();
//   })
// );

// const nums = [10, 20, 30, 40, 50];

// const squaredNumbers = nums.map(function (num) {
//   return num * num;
// });

// console.log(squaredNumbers);

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

// console.log(result);

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

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

// // Arrow function
// const add = (a, b) => {
//   return a + b;
// }

// const add = (a, b) => (
//   a + b
// )

// const greet = name => (
//   name.toUpperCase()
// )

// const greet = () => (
//   "hello world"
// )

// const add = (a, b) => (a + b);

// const add = (a, b) => a + b;

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

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

// const uppercasedNames = names.map((name) => name.toUpperCase());

let fullName = 'John Doe';

function greet() {
  fullName = 'Jane Doe';
  console.log(fullName);
}

function changeName(name) {
  return name;
}

fullName = changeName('Jane Doe');

greet();

console.log(fullName);

Scratchpad #6

// function add(x, y) {
//   return x + y;
// }

// const add = (x, y) => {
//   const res = x + y;
//   return res;
// };

// const add = (x, y) => x + y;

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

// function isBetween2(x, y) {
//   return function (num) {
//     return num >= x && num <= y;
//   };
// }

// const isBetween = (x, y) => (num) => num >= x && num <= y;

// const isUnderAge = isBetween(0, 18);

// console.log(isUnderAge(12));

// let searchQuery = 'Terminator';

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

// const result = movies.find((movie) => movie.toLowerCase().includes('Ar'));

// 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 goodBook = books.find((b) => b.rating >= 4.3);

// // console.log(goodBook);

// const goodBook = books.filter((b) => b.rating >= 4.3);

// console.log(goodBook);

// const nums = [9, 8, 3, 4, 6, 12, 17, 23, 0];

// const odds = nums.filter((n) => n % 2 === 1);

// console.log(odds);

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

// const results = names.every((name) => name[0] === 'j');

// console.log(results);

// const books = [
//   {
//     title: 'The Shining',
//     author: 'Stephen King',
//     rating: 4.1,
//   },
//   {
//     title: 'Sacred Games',
//     author: 'Vikram Chandra',
//     rating: 4.5,
//   },
//   {
//     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,
//   },
// ];

// console.log(books.every((book) => book.title));
// console.log(books.some((book) => book.title));

// // for (let book of books) {
// //   console.log(book.title);
// // }

// const prices = [500.4, 211, 23, 5, 4, 22.2, -23.2, 9233];

// const prices = [4, 5, 8, 2, 1, 4, 9];

// // prices.sort((a, b) => a - b);
// prices.sort((a, b) => b - a);

// console.log(prices);

// const prices = [1, 2, 3, 4];

// // const res = prices.reduce((acc, currVal) => acc * currVal);

// // const res = prices.reduce((acc, currVal) => (currVal > acc ? currVal : acc));

// const res = prices.reduce((acc, currVal) => acc + currVal, 25);

// console.log(res);

// const multiply = (x, y) => {
//   if (typeof y === 'undefined') {
//     y = 1;
//   }
//   return x * y;
// };

// const multiply = (x, y = 1) => {
//   return x * y;
// };

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

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

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

// const printVals = (a, b, c) => {
//   console.log(a);
//   console.log(b);
//   console.log(c);
// };

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

// // printVals(...names);

// printVals(...'john');

// const nums1 = [1, 2, 3];
// const nums2 = [4, 5, 6];

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

// const admin = { ...user, ...moderator };

// console.log(admin);

// const add = (...nums) => {
//   let total = 0;
//   for (let num of nums) {
//     total += num;
//   }
//   return total;
// };

// const add = (...nums) => nums.reduce((acc, currVal) => acc + currVal);

// console.log(add(10, 4, 4, 3, 54, 64));

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

// names('John', 'Jane', 'Jack', 'James', 'Jim', 'Julie');

// function add() {
//   console.log(arguments);
// }

// add(10, 20);

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

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

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

// console.log(admin, user);

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

// const [num1, num2] = nums;

// console.log(num1, num2);

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

// const firstName = user.firstName;
// const lastName = user.lastName;

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

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

// function doSomething(options) {
//   console.log(options.name);
//   console.log(options.phone);
//   console.log(options.email);
//   console.log(options.test);
// }

// function doSomething({ name, phone, email, test }) {
//   console.log(name);
//   console.log(phone);
//   console.log(email);
//   console.log(test);
// }

// doSomething({
//   name: 'John',
//   phone: 21323,
//   email: 'john@gmail.com',
//   test: true,
// });

// 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: highest, lowest: lowest, average: average };

// const info = { highest, lowest, avg: average };

// console.log(info);

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

// const user1 = { [role]: username, [1 + 2 + 3]: username };

// console.log(user1);

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

// console.log(addProperty({ name: 'John' }, 'age', 25));

// const val1 = 'role';
// const val2 = 'Administrator';

// const profile = { [val1]: val2 };

// console.log(profile);

// const maths = {
//   add: (a, b) => a + b,
//   sub: (a, b) => a - b,
//   mul: (a, b) => a * b,
// };

// const maths = {
//   pi: 3.14,
//   add(a, b) {
//     return a + b;
//   },
//   sub(a, b) {
//     return a - b;
//   },
//   mul(a, b) {
//     return a - b;
//   },
// };

// console.log(maths.add(10, 2));

// console.log(this);

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

// window.helloWorld();

const user = {
  firstName: 'John',
  lastName: 'Doe',
  greet: function () {
    console.log(this);
  },
};

function helloWorld() {
  console.log(this);
}

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

user.greet();

helloWorld();
user.greet();

const newGreet = user.greet;

newGreet();

Scratchpad #7

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

// // // console.dir(window.document.body.children[0]);

// // // setTimeout(() => {
// // //   window.document.body.children[0].innerText = 'John Doe';
// // // }, 5000);

// // // const p = document.getElementById('para');

// // // // console.dir(p.innerText);

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

// // // for (let para of ps) {
// // //   para.innerText = 'CHANGED!!!';
// // //   // console.log(para.innerText);
// // // }

// // // const blueTexts = document.getElementsByClassName('blue-text');

// // // console.log(blueTexts);

// // // const ul = document.getElementsByTagName('ul')[0];

// // // const imps = ul.getElementsByClassName('imp');

// // // console.log(imps);

// // // const p = document.querySelector('p');
// // // const para = document.querySelector('#para');
// // // const blueText = document.querySelector('.blue-text');

// // // const ps = document.querySelectorAll('p');
// // // // const para = document.querySelector('#para');
// // // const blueTexts = document.querySelectorAll('.blue-text');

// // // console.log(p, para, blueText);
// // // console.log(ps, blueTexts);

// // // const ful = document.querySelectorAll('.ful li.imp');

// // // console.log(ful);

// // const h1 = document.querySelector('h1');
// // console.log(h1.innerText);
// // // h1.innerText =

// // const ul = document.querySelector('ul');
// // ul.innerText = 'Hello World';

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

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

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

// // // console.log(p.innerText);
// // // console.log(p.textContent);

// // console.log(p.innerHTML);

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

// // p.innerHTML =
// //   '<div><p>Hello World. <strong>This is</strong> some test message.</p></div>';

// // p.innerHTML += ' Hello World again.';

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

// // console.log(img.src);
// // img.alt = 'This is the new alt info';

// // const h1 = document.querySelector('h1');
// // console.log(h1.className);

// // h1.id = 'HelloWorld';

// // h1.style = 'color: red';

// // console.log(h1.href);

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

// // console.log(h1.getAttribute('class'));
// // console.log(h1.getAttribute('hello'));

// // h1.setAttribute('id', 'impTitle');

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

// // console.log(p.nextElementSibling.nextElementSibling);

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

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

// // console.log(p.nextElementSibling);
// // console.log(p.nextElementSibling.nextElementSibling.nextElementSibling);

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

// // for (let item of ul.children) {
// //   item.innerText = 'Changed!';
// // }

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

// // h1.style.color = 'red';
// // h1.style.textDecoration = 'underline';
// // h1.style.fontWeight = '300';

// // 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)];
// //   li.style.fontSize = '20';
// //   li.style.fontWeight = 'bold';
// //   li.style.backgroundColor = 'black';
// //   li.style.fontFamily = 'Helvetica, sans-serif';
// //   li.style.border = '2px solid red';
// //   li.style.borderTopLeftRadius = '50px';
// // }

// // {color: 'red', fontSize: '20px'}
// // function addStyles(el, styles) {
// //   for (let key in styles) {
// //     el.style[key] = styles[key];
// //   }
// // }

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

// // addStyles(heading, {
// //   color: 'green',
// //   fontSize: '30px',
// //   textDecoration: 'underline',
// // });

// // const heading = document.querySelector('h1');
// // heading.style.textDecoration = 'underline';
// // // console.log(heading.style.color);

// // const headingStyles = getComputedStyle(heading);
// // // headingStyles.textDecoration = 'underline';
// // console.log(headingStyles.textDecoration);

// // const heading = document.querySelector('h1');
// // // heading.className = 'blue-text red-text';

// // // heading.classList.add('purple-text');
// // // heading.classList.remove('blue-text');
// // heading.classList.toggle('blue-text');

// // const h1 = document.createElement('h1');
// // h1.innerText = 'Hello World';
// // h1.style.color = 'red';
// // h1.style.fontSize = '20px';
// // h1.classList.add('heading');

// // const p = document.createElement('p');
// // p.innerText = 'hello world this is some sample text';

// // const div = document.createElement('section');
// // div.style.padding = '20px';
// // div.style.border = '1px solid black';

// // div.appendChild(h1);
// // div.appendChild(p);

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

// // root.appendChild(div);

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

// // const li1 = document.createElement('li');
// // li1.innerText = 'Brand new task to complete';

// // const li2 = document.createElement('li');
// // li2.innerText = 'Another Task';
// // li2.classList.add('test-li');

// // ul.appendChild(li1);
// // ul.appendChild(li2);

// // const li3 = document.createElement('li');
// // li3.innerText = 'Brand new li. 3rd li.';

// // ul.insertBefore(li3, li2);

// // // ul.appendChild(li3);

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

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

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

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

// const li1 = document.createElement('li');
// li1.innerText = 'Brand new task to complete';

// const li2 = document.createElement('li');
// li2.innerText = 'Another Task';
// li2.classList.add('test-li');

// const li3 = document.createElement('li');
// li3.innerText = 'Third li';

// // ul.appendChild(li1);
// // ul.appendChild(li2);

// ul.append(li1, li2);

// ul.prepend(li3);

// ////////////////////

// ul.removeChild()

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

const li1 = ul.querySelector('li');
const li2 = li1.nextElementSibling;

ul.removeChild(li2);

li1.remove();

HTML

<!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>

    <!-- <style>
      h1 {
        color: gold;
      }
    </style> -->
  </head>
  <body>
    <!-- <h1 class="blue-text">Hello World</h1>
    <p>
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Labore tempore
      velit explicabo repellat qui laudantium inventore cumque molestiae amet
      ipsa.
    </p>
    <ul class="ful">
      <li class="imp">Lorem ipsum dolor sit amet.</li>
      <li>Lorem <strong>ipsum dolor</strong> sit amet.</li>
      <li>dolor lorem sit amet.</li>
      <li>dolor sit amet.</li>
      <li class="imp">dolor dolorsit amet.</li>
      <li>Lorem ipsum sit amet.</li>
      <li>Lorem dolor sit amet.</li>
    </ul>
    <ul class="lul">
      <li class="imp">Lorem ipsum dolor sit amet.</li>
      <li>Lorem <strong>ipsum dolor</strong> sit amet.</li>
      <li>dolor lorem sit amet.</li>
      <li>dolor sit amet.</li>
      <li class="imp">dolor dolorsit amet.</li>
      <li>Lorem ipsum sit amet.</li>
      <li>Lorem dolor sit amet.</li>
    </ul>
    <h3 class="imp-title blue-text">Lorem Ipsum</h3>
    <div>
      <h5>Lorem ipsum dolor sit amet.</h5>
      <p id="para">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Perferendis
        sunt commodi totam placeat rerum dolore vel esse qui recusandae officia
        hic porro, deleniti, aperiam eius labore necessitatibus, reprehenderit
        repudiandae dolorem?
      </p>
      
    </div> -->

    <!-- <p class="special">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis,
      consectetur. -->
    <!-- <script>
        console.log('HELLO WORLD!');
      </script> -->
    <!-- </p> -->

    <!-- <div>
      <input type="range" min="10" max="1000" />
    </div> -->

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

    <!-- <ul class="todos"></ul> -->

    <!-- <p>
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus ducimus
      earum dolore? Sed unde enim voluptates officia asperiores provident culpa
      facere, nostrum eius aliquam beatae, consequuntur odit id inventore
      excepturi?
    </p> -->

    <ul class="todos">
      <li>Lorem, ipsum dolor.</li>
      <li>Lorem, ipsum dolor. Lorem ipsum dolor sit</li>
      <li>Lorem, ipsum dolor. Lorem</li>
    </ul>

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

Scratchpad #8

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

// // btn.onclick = function () {
// //   console.log('Hello World');
// // };

// // btn.onclick = function () {
// //   console.log('Hello Universe');
// // };

// // Events
// // btn.addEventListener('click', function () {
// //   console.log('Hello World');
// // });

// // btn.addEventListener('mouseover', function () {
// //   console.log('Hello Universe');
// // });

// // window.addEventListener('scroll', () => {
// //   console.log('I was scrolled!');
// // });

// // btn.addEventListener('mouseenter', () => {
// //   console.log('pointer not touching');
// // });

// // 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', () => {
// //   btn.innerText = 'YOU WON!';
// //   document.body.style.backgroundColor = 'green';
// // });

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

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

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

// // // Loop to add each color as a background color (create as many boxes as length of colors)
// // 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!')
// //     document.body.style.backgroundColor = color;
// //     span.innerText = color;
// //   });

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

// //////////////////////////////////

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

// // btn.addEventListener('click', (event) => {
// //   console.log(event);
// // });

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

// // input.addEventListener('keydown', (e) => {
// //   // console.log(e);
// //   console.log(e.key, e.ctrlKey, e.altKey);
// // });

// // input.addEventListener('keyup', (e) => {
// //   // console.log(e);
// //   console.log(e.key, e.ctrlKey, e.altKey);
// // });

// // input.addEventListener('keypress', (e) => {
// //   // console.log(e);
// //   console.log(e.key, e.ctrlKey, e.altKey);
// // });

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

// // input.addEventListener('keypress', (e) => {
// //   // console.dir(e.target.value);
// //   p.innerText = e.target.value;
// // });

// const tasks = [];

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

// form.addEventListener('submit', (e) => {
//   e.preventDefault();

//   const checkbox = document.createElement('input');
//   checkbox.type = 'checkbox';

//   const li = document.createElement('li');
//   li.innerText = e.target.elements.task.value;
//   li.append(checkbox);

//   ul.append(li);
//   e.target.elements.task.value = '';

//   li.addEventListener('click', (e) => {
//     e.target.remove();
//   });

//   li.addEventListener('mouseover', (e) => {
//     e.target.style.cursor = 'pointer';
//   });
// });

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

// setTimeout(() => console.log('Hello World'), 5000);

// 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 randomNum = Math.random();

  if (randomNum > 0.5) {
    resolve();
  } else {
    reject();
  }
});

willGetAPlaystation
  .then(() => console.log('Promise fulfilled!'))
  .catch(() => console.log('Promise broken'));

Scratchpad #9

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

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

// myPromise
//   .then(() => console.log('Promise fulfilled'))
//   .catch(() => console.log('Promise rejected'));

// 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 });
//       }
//     }, 3000);
//   });
// };

// fakeRequest('/users')
//   .then((response) => {
//     const userId = response.data[0].id;
//     fakeRequest(`/users/${userId}`)
//       .then((response) => {
//         const postId = response.data.topPostId;
//         fakeRequest(`/posts/${postId}`)
//           .then((response) => {
//             console.log(response);
//           })
//           .catch((err) => console.log(err));
//       })
//       .catch((err) => console.log(err));
//   })
//   .catch((err) => console.log(err));

// fakeRequest('/users')
//   .then((response) => {
//     const userId = response.data[0].id;
//     return fakeRequest(`/users/${userId}`);
//   })
//   .then((response) => {
//     const postId = response.data.topPostId;
//     return fakeRequest(`/posts/${postId}`);
//   })
//   .then((response) => console.log(response))
//   .catch((err) => console.log(err));

// const request = fetch('https://pokeapi.co/api/v2/pokemon/ditto');

// request
//   .then((res) => {
//     if (res.status !== 200) {
//       throw new Error();
//     } else {
//       return res.json();
//     }
//   })
//   .then((data) => {
//     const ability = data.abilities[0].ability.url;
//     return fetch(ability);
//   })
//   .then((res) => {
//     if (res.status !== 200) {
//       throw new Error();
//     } else {
//       return res.json();
//     }
//   })
//   .then((data) => {
//     console.log(data);
//   })
//   .catch((err) => console.log('THE REQUEST DID NOT WORK'));

// console.log(axios);

// axios
//   .get('https://pokeapi.co/api/v2/pokemon/ditto')
//   .then(({ data }) => {
//     const ability = data.abilities[0].ability.url;
//     return axios.get(ability);
//   })
//   .then(({ data }) => {
//     console.log(data);
//   })
//   .catch((err) => console.log('ERROR', err));

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

// axios
//   .get('https://pokeapi.co/api/v2/pokemon')
//   .then(({ data }) => {
//     const pokemons = data.results;

//     for (let pokemon of pokemons) {
//       const li = document.createElement('li');
//       li.innerText = pokemon.name;
//       ul.append(li);
//     }
//   })
//   .catch((err) => console.log(err));

// root.append(ul);

// function getData() {
//   axios
//     .get('https://pokeapi.co/api/v2/pokemon')
//     .then((res) => console.log(res.data));
// }

// getData();

// async function greet() {
//   return 'hello';
// }

// greet()
//   .then((res) => console.log(res))
//   .catch((err) => console.log(err));

// async function add(x, y) {
//   if (typeof x !== 'number' || typeof y !== 'number') {
//     throw new Error();
//   }
//   return x + y;
// }

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

// async function getData() {
//   // const pokemons = axios.get('https://pokeapi.co/api/v2/pokemon');
//   // pokemons.then((res) => console.log(res.data));

//   const req1 = await axios.get('https://pokeapi.co/api/v2/poemon');
//   const req2 = await axios.get(req1.data.results[0].url);
//   console.log(req2.data);
// }

// getData();

async function getData() {
  try {
    const req1 = await axios.get('https://pokeapi.co/api/v2/pokemon');
    const req2 = await axios.get(req1.data.results[0].url);
    console.log(req2.data);
  } catch (err) {
    console.log("This didn't work");
  }
}

getData();
Learn this on the racks

Reading it is one thing. Configuring it is another.

Our batches run labs like this one end to end on real kit, in the Mumbai classroom or live online, taught by practising engineers.