Lab guideFullstack

FullStack Development Daily Evening August 2023

Last updated 29 November 2023

FullStack Development Daily Evening August 2023

JavaScript Scratchpad 1-5

// let greeting = 'Hello World, Welcome to RST Forum.';
// let result = greeting.indexOf('World').toUpperCase();

// let message = 'Hello world,\nthis is a new line.';
let message = `Hello world,
this
is a new line.`;


// // // let age = 25;

// // // if (age >= 18) {
// // // 	console.log('Welcome');
// // // }

// // // let num = 34;

// // // if (num % 2 === 0) {
// // // 	console.log('Number is even');
// // // }

// // let age = 100;

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

// // let password = 'helloworld';

// // if (password.length > 8) {
// // 	if (password.indexOf(' ') !== -1) {
// // 		console.log('Password cannot contain spaces');
// // 	} else {
// // 		console.log('Valid password');
// // 	}
// // } else {
// // 	console.log('Password has to be longer than 8 chars');
// // }

// const loggedInUser = null;

// if (loggedInUser) {
// 	console.log('Welcome to your dashboard');
// } else {
// 	console.log('Please login to view content');
// }

// let day = 6;

// switch (day) {
// 	case 0:
// 		console.log('Mon');
// 		break;
// 	case 1:
// 		console.log('Tue');
// 		break;
// 	case 2:
// 		console.log('Wed');
// 		break;
// 	default:
// 		console.log('Invalid day code');
// }

// if (day === 0) {
// 	console.log('Mon');
// } else if (day === 1) {
// 	console.log('Tue');
// } else if (day === 2) {
// 	console.log('Wed');
// }

let statusRn = 'idle';

let color =
    statusRn === 'online' ? 'green' : statusRn === 'offline' ? 'red' : 'yellow';
console.log(color);

// statusRn === 'online' ? console.log('Green') : console.log('Red');

// if (statusRn === 'online') {
// 	console.log('Green');
// } else {
// 	console.log('Red');
// }


// const product1 = [
// 	'iPhone 15 Pro',
// 	'Apple',
// 	'Some description...',
// 	500,
// 	130000,
// 	true,
// ];

// console.log(product1[4]);

// const product2 = {
// 	name: 'iPhone 15 Pro',
// 	brand: 'Apple',
// 	description: 'Some description...',
// 	price: 130000,
// 	inStock: 500,
// 	discounted: true,
// 	1: 'hello',
// };

// console.log(product2.price);

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

// const arr = {0: 1, 1: 1, 2: 3}
// const str = "hello"
// const str = {0: 'h', 1: '2', 2: 'l', 3: 'l', 4: 'o', length: 5}

// const playlist = [
// 	{
// 		title: '',
// 		album: '',
// 		artist: ['', ''],
// 	},
// 	{
// 		title: '',
// 		album: '',
// 		artist: ['', ''],
// 	},
// 	{
// 		title: '',
// 		album: '',
// 		artist: ['', ''],
// 	},
// ];

// const student = {
// 	firstName: 'John',
// 	lastName: 'Doe',
// 	frameworks: ['ReactJS', 'Express.js'],
// 	levels: {
// 		backend: 50,
// 		frontend: 45,
// 		data: 5,
// 	},
// };

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

// for (let counter = 100; counter > 0; counter--) {
// 	console.log(`${counter}: Hello World`);
// }

// const names = ['john', 'jane', 'jack', 'jim', 'tim', 'ali', 'ram', 'jay'];

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

// const movies = [
// 	{ movieName: 'Inception', rating: 3.8 },
// 	{ movieName: 'Avengers', rating: 2.4 },
// 	{ movieName: 'Iron Man', rating: 2.9 },
// ];

// for (let i = 0; i < movies.length; i++) {
// 	const movie = movies[i];
// 	console.log(`${movie.movieName} has a rating of ${movie.rating}`);
// }

// const word = 'Hello World';

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

// let reversedWord = '';

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

// console.log(reversedWord);

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

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

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

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

// let i = 0;

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

let target = Math.floor(Math.random() * 10) + 1; // 3
let guess = Math.floor(Math.random() * 10) + 1; // 6

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

console.log(`FINAL RESULT\nTarget: ${target} | Guess: ${guess}`);

Scratchpad 6-11

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

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

// // console.log(`FINAL RESULT\nTarget: ${target} | Guess: ${guess}`);

// const names = ['john', 'jane', 'jack', 'jim', 'tim', 'ali', 'ram', 'jay'];

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

// // for (let name of names) {
// // 	console.log(name);
// // }

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

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

// // for (let row of matrix) {
// // 	for (let col of row) {
// // 		console.log(col);
// // 	}
// // }

// // const cats = ['fashion', 'mobiles', 'books'];
// // const prods = ['tshirt', 'samsung', '1984'];

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

// const productPrices = {
// 	Apple: 80000,
// 	OnePlus: 50000,
// 	Samsung: 90000,
// };

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

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

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

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

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

// function flipCoin() {
// 	const num = Math.random();
// 	if (num > 0.5) {
// 		console.log('Heads');
// 	} else {
// 		console.log('Tails');
// 	}
// }

// for (let i = 0; i < 5; i++) {
// 	flipCoin();
// }

// // flipCoin();

// 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();
// greet('John');
// greet('Jane', 'Hello');

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

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

// function throwDice(times) {
// 	if (typeof times === 'undefined') {
// 		times = 1;
// 	}
// 	for (let i = 0; i < times; i++) {
// 		rollDie();
// 	}
// }

// throwDice();

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

// // console.log('hello'.toUpperCase());
// console.log(greet('Jane', 'Hello'));

// function isNumber(val) {
// 	if (typeof val !== 'number') {
// 		return false;
// 	} else {
// 		return true;
// 	}
// }

// console.log(isNumber('40'));

// let fullName = 'John Doe';

// function greet() {
// 	let fullName = 'Jane Smith';
// 	console.log(fullName);
// }

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

// let fullName = 'Jane Smith';

// if (true) {
// 	var fullName = 'John Doe';
// 	console.log(fullName);
// }

// console.log(fullName);

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

// console.log('Value of i outside:', i);

// function outer() {
// 	function inner() {
// 		let movie = 'Avengers';
// 		console.log(movie);
// 	}

// 	inner();
// 	console.log(movie);
// }

// outer();

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

// let a = greet;

// a();

// console.log(a);

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

// const greet2 = function () {
// 	console.log('Hello Moon');
// };

// greet2();

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

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

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

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

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

math.add(10, 4);


// var hello;

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

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

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

// // function repeat(func, num) {
// // 	for (let i = 0; i < num; i++) {
// // 		func();
// // 	}
// // }

// // function sayHello() {
// // 	console.log('Hello World!');
// // }
// // function sayGoodbye() {
// // 	console.log('Bye World!');
// // }

// // repeat(sayHello, 10);
// // repeat(sayGoodbye, 5);

// // function randomPick(f1, f2) {
// // 	let randNum = Math.random();
// // 	if (randNum < 0.5) {
// // 		f1();
// // 	} else {
// // 		f2();
// // 	}
// // }

// // randomPick(sayHello, sayGoodbye);

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

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

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

// function capitalizeString(str) {
// 	let words = str.split(' ');
// 	let capitalizedWords = [];
// 	for (let word of words) {
// 		capitalizedWords.push(word[0].toUpperCase() + word.slice(1));
// 	}
// 	let capitalizedStr = capitalizedWords.join(' ');
// 	return capitalizedStr;
// }

// console.log(capitalizeString('This is a test message'));

// let message = 'hello world this is some test message';

// let words = message.split(' ');

// let capitalizedWords = [];

// for (let word of words) {
// 	capitalizedWords.push(word[0].toUpperCase() + word.slice(1));
// }

// let capitalizedMessage = capitalizedWords.join(' ');

// console.log(capitalizedMessage);

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

// const isUnderAge = isBetween(0, 18);
// const canEnterButNotDrink = isBetween(18, 21);
// const canDrink = isBetween(21, 65);
// const isSenior = isBetween(65, 100);

// console.log(isUnderAge(5));
// console.log(canEnterButNotDrink(20));
// console.log(canDrink(30));
// console.log(isSenior(70));

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

// function sub(a, b) {
// 	return a - b;
// }

// console.log(math(10, 2, sub));

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

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

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

// greet();

// console.log(hello);
// let hello = 'world';

// const nums = [1, 2, 300, 4, 5, 6, 7, 8];

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

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

const movies = [
    {
        title: 'Avengers',
        rating: 2.1,
    },
    {
        title: 'Dr. Strange',
        rating: 3.9,
    },
    {
        title: 'Tenet',
        rating: 4.0,
    },
    {
        title: 'Joker',
        rating: 4.7,
    },
];

// movies.forEach(function (movie, i) {
// 	console.log(i, `${movie.title} has a rating of ${movie.rating}`);
// });

movies.forEach(function () {
    console.log('Hello world');
});

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

// const upperNames = names.map(function (name) {
// 	// ['JOHN', 'JACK', 'JANE', 'JAMES']
// 	return name.toUpperCase();
// });

// // const upperNames = [];

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

// console.log(upperNames);

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

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

// console.log(doubles);

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

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

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

// const square = (x) => {
// 	return x ** 2;
// };

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

// const square = x => {
// 	return x ** 2;
// };

// const greet = () => {
// 	return "Hello World"
// }

// const square = x => (
// 	x ** 2
// );

// const square = x => (x ** 2);

// const square = x => x ** 2;

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

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

// const doubles = nums.map(num => num * 2);

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

// // using regular function expressions
// const doubles1 = nums.map(function (n) {
//   return n * 2
// })

// // using arrow functions
// const doubles2 = nums.map(n => {
//   return n * 2
// })

// // using arrow function's one-liner implicit return
// const doubles3 = nums.map(n => n * 2)
// const parityList = nums.map(n => n % 2 === 0 ? 'Even' : 'Odd')

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

// let result = movies.find((movie) => {
// 	// return movie.includes('Park');
// 	// return movie[0] === 'T';
// 	return movie.length > 20;
// })

// console.log(result);

// const books = [
//   {
//     title: 'The Shining',
//     author: 'Stephen King',
//     rating: 4.1
//   },
//   {
//     title: 'Sacred Games',
//     author: 'Vikram Chandra',
//     rating: 4.5
//   },
//   {
//     title: '1984',
//     author: 'George Orwell',
//     rating: 4.9
//   },
//   {
//     title: 'The Alchemist',
//     author: 'Paulo Coelho',
//     rating: 3.5
//   },
//   {
//     title: 'The Great Gatsby',
//     author: 'F. Scott Fitzgerald',
//     rating: 3.8
//   }
// ]

// // const result = books.find((book) => book.rating < 4);
// // console.log(result);

// const result = books.filter((book) => book.rating < 4);
// console.log(result);

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

// const georgeBook = books.find(b => (
//   b.author.includes('George')
// ))

// const lowRated = books.find(book => {
//   return book.rating < 4
// })

// console.log(goodBook)
// console.log(georgeBook)

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

// const result = nums.filter((num) => num > 100);
// console.log(result);

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

// const georgeBooks = books.filter(b => (
//   b.author.includes('George')
// ))

// const lowRated = books.filter(book => {
//   return book.rating < 4
// })

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

// console.log(goodBook)
// console.log(georgeBooks)
// console.log(lowRated)
// console.log(booksWithThe)

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

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

// const bestBooks = books.every(book => (
//   book.rating >= 4
// ))

// const notAuthor = books.every(
//   book => book.author.toLowerCase() !== 'chetan bhagat'
// )

// console.log(bestBooks)
// console.log(notAuthor)

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

// const result = names.some((name) => name[0] === 'b');
// console.log(result);

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

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

// console.log(prices);

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

// books.sort((a, b) => b.rating - a.rating);
// console.log(books);

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

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

// acc  	currVal
// 1      2
// 3			3
// 6      4
// 10     5
// 15

// let nums = [21, 221, 2, 1, 34, 123, 4342, 56, 4];

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

// acc    currVal
// 21			221
// 221 		2
// 221		1
// 221	  34
// 221

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

// const result = nums.reduce((acc, currVal) => acc + currVal, 100);
// console.log(result);

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

console.log(multiple(10));

// function printProfile(firstName, lastName, age) {
// 	console.log(firstName, lastName, age);
// }

// const data = ['John', 'Doe', 20];

// printProfile(data[0], data[1], data[2]);
// printProfile(...data);

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

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

// function add(a, b, ...nums) {
// 	console.log(a);
// 	console.log(b);
// 	console.log(nums);
// 	// let total = 0;
// 	// for (let num of nums) {
// 	// 	total += num;
// 	// }
// 	// return total;
// }

// console.log(add(10, 5, 20, 30, 40, 50));

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

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

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

// console.log(admin, mod, sub, others);

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

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

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

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

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

// function printProfile({ firstName, lastName, age }) {
// 	console.log(
// 		`Hello, my name is ${firstName} ${lastName} and I am ${age} years old.`
// 	);
// }

// printProfile({ firstName: 'Jane', lastName: 'Doe', age: 20 });

// const movieReviews = [4.5, 5.0, 3.2, 2.1, 4.7, 3.8, 3.1, 3.9, 4.4];
// const highest = Math.max(...movieReviews);
// const lowest = Math.min(...movieReviews);

// let total = 0;
// movieReviews.forEach((rating) => (total += rating));
// const average = total / movieReviews.length;

// const result = { highest, lowest, avg: average, hello: 'world' };

// console.log(result);

// const getReviewDetails = (arr) => {
// 	const highest = Math.max(...arr);
// 	const lowest = Math.min(...arr);
// 	const total = arr.reduce((accumulator, nextVal) => accumulator + nextVal);
// 	const average = total / arr.length;

// 	return {
// 		highest,
// 		lowest,
// 		total,
// 		average,
// 	};
// };

// const reviewList = [4.5, 5.0, 3.2, 2.1, 4.7, 3.8, 3.1, 3.9, 4.4];

// const statistics = getReviewDetails(reviewList);

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

// const user1 = { [role]: username }; // {admin: 'janedoe'}
// console.log(user1);

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

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

// const math = {
// 	add(x, y) {
// 		return x + y;
// 	},
// 	sub(x, y) {
// 		return x - y;
// 	},
// 	greet: 'Hello World',
// };

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

// console.log('HELLO WORLD');

// SCOPE

// function helloWorldFromJS() {
// 	console.log(this);
// 	console.log('Hello world from JavaScript');
// }

// helloWorldFromJS();

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

const user1 = {
    firstName: 'John',
    lastName: 'Doe',
    age: 20,
    greet2: function () {
        console.log('Hello World');
        console.log(this);
    },
};

// greet1();
// user1.greet2();

const aaaaaaa = 'hello world';

console.log(window);

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

// // greet();

// // function greet() {
// // 	console.log(
// // 		`Hello, my name is ${this.firstName} ${this.lastName} and I am ${this.age} years old.`
// // 	);
// // }

// // const user1 = {
// // 	firstName: 'Jane',
// // 	lastName: 'Doe',
// // 	age: 20,
// // 	greet,
// // };

// // const user = {
// // 	firstName: 'John',
// // 	lastName: 'Smith',
// // 	age: 22,
// // 	fullName: function () {
// // 		return `${this.firstName} ${this.lastName}`;
// // 	},
// // 	greet: function () {
// // 		console.log(
// // 			`Hello, my name is ${this.fullName()} and I am ${this.age} years old.`
// // 		);
// // 	},
// // };

// // const outerFullName = user.fullName;
// // console.log(outerFullName());
// // console.log(user.fullName());
// // // user.greet();

// const user = {
// 	firstName: 'John',
// 	lastName: 'Smith',
// 	age: 22,
// 	greet: () => {
// 		console.log(
// 			`Hello, my name is ${this.firstName} ${this.lastName} and I am ${this.age} years old.`
// 		);
// 	},
// };

// // user.greet();

// const hellos = {
// 	messages: [
// 		'hello world',
// 		'hello universe',
// 		'hello darkness',
// 		'hello hello',
// 		'heylo',
// 	],
// 	pickMsg() {
// 		const index = Math.floor(Math.random() * this.messages.length);
// 		return this.messages[index];
// 	},
// 	start() {
// 		setInterval(() => {
// 			// this = hellos
// 			console.log(this);
// 			console.log(this.pickMsg());
// 		}, 1000);
// 	},
// };

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

// document = {
// 	head: {
// 		meta: {},
// 		meta: {},
// 	},
// };

// console.dir(document.all);

// const title = document.getElementById('title');
// console.log(title);

// const lis = document.getElementsByTagName('li');
// console.log(lis);

// const ol = document.getElementsByTagName('ol')[0];
// const listItems = ol.getElementsByTagName('li');
// console.log(listItems);

// const testItems = document.getElementsByClassName('test');
// console.log(testItems);

// const h1 = document.querySelector('h1');
// const lis = document.querySelectorAll('li');
// console.log(lis);

// const tests = document.querySelectorAll('.test');
// console.log(tests);

// const h1 = document.querySelector('h1');
// // console.log(h1.innerText);
// // h1.innerText = 'This is something else';

// setInterval(function () {
// 	h1.innerText = Math.random();
// }, 500);

// const el = document.querySelector('.helloworld');
// console.log(el.textContent);

// const p = document.querySelector('.test');
// // console.log(p.innerHTML);
// p.innerHTML = 'Hello World. THis is some <strong>STRONG</strong> text.';
// p.innerHTML += '-----------------';

// const a = document.querySelector('a');
// // console.log(p);
// a.href = 'https://duckduckgo.com';
// a.id = 'helloWorld';

const a = document.querySelector('a');
// a.href = 'https://yahoo.com';
// a.setAttribute('href', 'https://test.com');

// console.log(a.href);
// console.log(a.getAttribute('href'));

// console.log(a.id);
// console.log(a.getAttribute('id'));

// console.log(a.parentElement.parentElement.parentElement);
// console.log(a.parentElement.nextElementSibling);

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

// console.log(ol.children);

const colors = [
    'red',
    'yellow',
    'purple',
    'blue',
    'green',
    'aqua',
    'pink',
    'orange',
    'black',
];

// const fontSizes = [
// 	'30px',
// 	'20px',
// 	'10px',
// 	'100px',
// 	'45px',
// 	'5px',
// 	'120px',
// 	'200px',
// 	'999px',
// ];

// const lis = document.querySelectorAll('li');
// const list = lis[0];

// list.style.backgroundColor = 'red';
// list.style.fontSize = '30px';
// list.style.color = 'white';
// document.body.style.backgroundColor = 'yellow';

// for (let li of lis) {
// 	setInterval(function () {
// 		const randomNum = Math.floor(Math.random() * colors.length);
// 		li.innerText = Math.random();
// 		li.style.color = colors[randomNum];
// 		li.style.fontSize = fontSizes[randomNum];
// 		document.body.style.backgroundColor = colors[randomNum];
// 	}, 200);
// }

// const ul = document.querySelector('#todoList');
// const li = ul.querySelector('li');
// // console.log(li);
// // li.className = 'todo done';
// li.classList.add('done');
// li.classList.remove('todo');
// li.classList.toggle('done');

// console.log(li.classList);

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

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

// const h1 = document.createElement('h1');
// h1.innerText = 'Hello World from JavaScript';
// h1.style.color = 'red';
// h1.style.fontSize = '50px';

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

// const ul = document.querySelector('#todoList');
// const li = ul.querySelector('.test');

// const listItem = document.createElement('li');
// listItem.classList.add('todo');
// listItem.innerText = 'HELLLLLO WORLDD!!!!';

// // ul.appendChild(listItem);

// ul.insertBefore(listItem, li);

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

// const b = document.createElement('b');
// b.innerText = 'BOLD TEXT';

// const i = document.createElement('i');
// i.innerText = 'ITALIC TEXT';

// // p.insertAdjacentElement('afterend', b);

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

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

// button.addEventListener('click', function () {
// 	const randomNum = Math.floor(Math.random() * colors.length);
// 	document.body.style.backgroundColor = colors[randomNum];
// });
// button.addEventListener('mousedown', function () {
// 	console.log('TEST MESSAGE');
// });

// button.onmouseover = function () {
// 	const randomNum = Math.floor(Math.random() * colors.length);
// 	document.body.style.backgroundColor = colors[randomNum];
// 	console.log('Hello World');
// };

// button.onclick = function () {
// 	console.log('TEST MESSAGE');
// };

// btn.addEventListener('mouseover', function () {
// 	btn.innerText = 'Button Hovered!';
// });

// btn.addEventListener('mouseout', function () {
// 	btn.innerText = 'Button 1';
// });

// // Attach a scroll event on the window itself
// window.addEventListener('scroll', function () {
// 	console.log('Stop Scrolling!');
// });
// -------------------
// const input = document.querySelector('input');
// const ul = document.querySelector('ul');
// const button = document.querySelector('button');

// button.addEventListener('click', function () {
// 	if (!input.value) {
// 		document.body.style.backgroundColor = 'red';
// 		return;
// 	}

// 	document.body.style.backgroundColor = 'white';

// 	const li = document.createElement('li');
// 	li.innerText = input.value;
// 	li.addEventListener('click', function () {
// 		li.classList.toggle('done');
// 	});

// 	const deleteButton = document.createElement('button');
// 	deleteButton.innerText = 'Delete';
// 	deleteButton.addEventListener('click', function () {
// 		li.remove();
// 	});
// 	li.append(deleteButton);

// 	ul.append(li);
// 	input.value = '';
// });
// -------------------

// const button = document.querySelector('button');
// button.style.position = 'relative';

// button.addEventListener('mouseover', function () {
// 	const height = Math.floor(Math.random() * window.innerHeight);
// 	const width = Math.floor(Math.random() * window.innerWidth);
// 	button.style.left = `${width}px`;
// 	button.style.top = `${height}px`;
// });

// button.addEventListener('click', function () {
// 	document.body.style.backgroundColor = 'green';
// 	button.innerText = 'You Win!';
// });

Scratchpad 11-14

const a = document.querySelector('a');
// a.href = 'https://yahoo.com';
// a.setAttribute('href', 'https://test.com');

// console.log(a.href);
// console.log(a.getAttribute('href'));

// console.log(a.id);
// console.log(a.getAttribute('id'));

// console.log(a.parentElement.parentElement.parentElement);
// console.log(a.parentElement.nextElementSibling);

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

// console.log(ol.children);

const colors = [
    'red',
    'yellow',
    'purple',
    'blue',
    'green',
    'aqua',
    'pink',
    'orange',
    'black',
];

// const fontSizes = [
// 	'30px',
// 	'20px',
// 	'10px',
// 	'100px',
// 	'45px',
// 	'5px',
// 	'120px',
// 	'200px',
// 	'999px',
// ];

// const lis = document.querySelectorAll('li');
// const list = lis[0];

// list.style.backgroundColor = 'red';
// list.style.fontSize = '30px';
// list.style.color = 'white';
// document.body.style.backgroundColor = 'yellow';

// for (let li of lis) {
// 	setInterval(function () {
// 		const randomNum = Math.floor(Math.random() * colors.length);
// 		li.innerText = Math.random();
// 		li.style.color = colors[randomNum];
// 		li.style.fontSize = fontSizes[randomNum];
// 		document.body.style.backgroundColor = colors[randomNum];
// 	}, 200);
// }

// const ul = document.querySelector('#todoList');
// const li = ul.querySelector('li');
// // console.log(li);
// // li.className = 'todo done';
// li.classList.add('done');
// li.classList.remove('todo');
// li.classList.toggle('done');

// console.log(li.classList);

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

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

// const h1 = document.createElement('h1');
// h1.innerText = 'Hello World from JavaScript';
// h1.style.color = 'red';
// h1.style.fontSize = '50px';

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

// const ul = document.querySelector('#todoList');
// const li = ul.querySelector('.test');

// const listItem = document.createElement('li');
// listItem.classList.add('todo');
// listItem.innerText = 'HELLLLLO WORLDD!!!!';

// // ul.appendChild(listItem);

// ul.insertBefore(listItem, li);

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

// const b = document.createElement('b');
// b.innerText = 'BOLD TEXT';

// const i = document.createElement('i');
// i.innerText = 'ITALIC TEXT';

// // p.insertAdjacentElement('afterend', b);

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

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

// button.addEventListener('click', function () {
// 	const randomNum = Math.floor(Math.random() * colors.length);
// 	document.body.style.backgroundColor = colors[randomNum];
// });
// button.addEventListener('mousedown', function () {
// 	console.log('TEST MESSAGE');
// });

// button.onmouseover = function () {
// 	const randomNum = Math.floor(Math.random() * colors.length);
// 	document.body.style.backgroundColor = colors[randomNum];
// 	console.log('Hello World');
// };

// button.onclick = function () {
// 	console.log('TEST MESSAGE');
// };

// btn.addEventListener('mouseover', function () {
// 	btn.innerText = 'Button Hovered!';
// });

// btn.addEventListener('mouseout', function () {
// 	btn.innerText = 'Button 1';
// });

// // Attach a scroll event on the window itself
// window.addEventListener('scroll', function () {
// 	console.log('Stop Scrolling!');
// });
// -------------------
// const input = document.querySelector('input');
// const ul = document.querySelector('ul');
// const button = document.querySelector('button');

// button.addEventListener('click', function () {
// 	if (!input.value) {
// 		document.body.style.backgroundColor = 'red';
// 		return;
// 	}

// 	document.body.style.backgroundColor = 'white';

// 	const li = document.createElement('li');
// 	li.innerText = input.value;
// 	li.addEventListener('click', function () {
// 		li.classList.toggle('done');
// 	});

// 	const deleteButton = document.createElement('button');
// 	deleteButton.innerText = 'Delete';
// 	deleteButton.addEventListener('click', function () {
// 		li.remove();
// 	});
// 	li.append(deleteButton);

// 	ul.append(li);
// 	input.value = '';
// });
// -------------------

// const button = document.querySelector('button');
// button.style.position = 'relative';

// button.addEventListener('mouseover', function () {
// 	const height = Math.floor(Math.random() * window.innerHeight);
// 	const width = Math.floor(Math.random() * window.innerWidth);
// 	button.style.left = `${width}px`;
// 	button.style.top = `${height}px`;
// });

// button.addEventListener('click', function () {
// 	document.body.style.backgroundColor = 'green';
// 	button.innerText = 'You Win!';
// });


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

// // form.addEventListener('submit', function (event) {
// // 	event.preventDefault();
// // 	console.dir(event.target[0].value);
// // });

// const multiply = (x, y) => x * y;

// const square = (x) => multiply(x, x);

// const rightTriangle = (a, b, c) => {
// 	return square(a) + square(b) === square(c);
// };

// rightTriangle(1, 2, 3);

// console.log('The first log');
// alert('Hello World');
// console.log('The second log');

// console.log('The first log');
// setTimeout(() => {
// 	console.log('Hello World');
// }, 5000);
// console.log('The second 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)`;
// 						setTimeout(() => {
// 							btn.style.transform = `translateX(700px)`;
// 						}, 1000);
// 					}, 1000);
// 				}, 1000);
// 			}, 1000);
// 		}, 1000);
// 	}, 1000);
// }, 1000);

const willGetAPlaystation = new Promise((resolve, reject) => {
    setTimeout(() => {
        const num = Math.random();

        if (num > 0.5) {
            resolve();
        } else {
            reject();
        }
    }, 2000);
});

willGetAPlaystation
    .then(() => {
        console.log('Thank you uncle');
    })
    .catch(() => {
        console.log('f you uncle');
    });


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',
                },
                '/about': 'This is the about page',
            };

            const data = pages[url];

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

// fakeRequest('/users')
// 	.then((res) => {
// 		const userId = res.data[0].id;
// 		console.log('First response');

// 		fakeRequest(`/users/${userId}`)
// 			.then((res) => {
// 				const postId = res.data.topPostId;
// 				console.log('Second response');

// 				fakeRequest(`/posts/${postId}`)
// 					.then((res) => {
// 						console.log('Third response');
// 						console.log(res);
// 					})
// 					.catch((err) => {
// 						console.log(err);
// 					});
// 			})
// 			.catch((err) => {
// 				console.log(err);
// 			});
// 	})
// 	.catch((err) => {
// 		console.log(err);
// 	});

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

// fetch('https://pokeapi.co/api/v2/poopsjiadfiklujnadfsglujnikdfkemon')
// 	.then((response) => {
// 		// console.log('I am the then block\n', response);
// 		if (!response.ok) {
// 			throw new Error();
// 		}
// 		return response.json();
// 	})
// 	.then((data) => {
// 		console.log(data);
// 	})
// 	.catch((err) => {
// 		console.log('I am in the error block\n', err);
// 	});

// axios
// 	.get(
// 		'https://swapi.dev/api/peasdjkfbashjnkdfbjkasdhfbadjkfhgbasdfhjkgsbjkdfhgbjhkople'
// 	)
// 	.then((response) => {
// 		console.log('I am the then block\n', response.data);
// 	})
// 	.catch((err) => {
// 		console.log('I am in the error block\n', err.message);
// 	});

// function getPlanets() {
// 	const planets = axios.get('https://swapi.dev/api/planets');
// 	planets
// 		.then((res) => {
// 			console.log(res.data);
// 		})
// 		.catch((err) => {
// 			console.log(err);
// 		});
// }

// getPlanets();

// async function greet() {
// 	let num = Math.random();
// 	if (num > 0.5) {
// 		return 'Hello World';
// 	} else {
// 		throw 'Goodbye World';
// 	}
// }

// function greet() {
// 	return new Promise((resolve, reject) => {
// 		let num = Math.random();
// 		if (num > 0.5) {
// 			resolve('Hello World');
// 		} else {
// 			reject('Goodbye World');
// 		}
// 	});
// }

// greet()
// 	.then((data) => {
// 		console.log('THEN', data);
// 	})
// 	.catch((err) => {
// 		console.log('CATCH', err);
// 	});

// async function getPlanets() {
// 	try {
// 		const planets = await axios.get('https://swapi.dev/api/planets');
// 		console.log(planets);
// 	} catch (err) {
// 		console.log('IN THE CATCH BLOCK', err);
// 	}
// }

// getPlanets();

// getPlanets().catch((err) => {
// 	console.log('IN THE CATCH BLOCK', err);
// });

const root = document.querySelector('#root');
root.style.display = 'grid';
root.style.gridTemplateColumns = '1fr 1fr 1fr 1fr 1fr';
root.style.gap = '20px';

async function displayPokemon() {
    try {
        const { data } = await axios.get(
            'https://pokeapi.co/api/v2/pokemon?limit=100000'
        );

        for (let pokemon of data.results) {
            const response = await axios.get(pokemon.url);
            const card = document.createElement('div');

            const photo = document.createElement('img');
            photo.src = response.data.sprites.other['official-artwork'].front_default;
            photo.style.width = '100%';

            const title = document.createElement('p');
            title.innerText = response.data.name;
            title.style.textTransform = 'capitalize';
            title.style.textAlign = 'center';

            card.append(photo);
            card.append(title);
            root.append(card);
        }

        // for (let pokemon of data.results) {
        // 	const card = document.createElement('p');
        // 	card.innerText = pokemon.name;
        // 	root.append(card);
        // }
    } catch (err) {
        console.log(err.message);
    }
}

displayPokemon();
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 practicing engineers.