Menu

Full-Stack Development Morning j2522

Full-Stack Development Morning j2522

HTML – CSS Scratchpad

HTML-CSS Flex Grid download zip

JS Scratchpad #1

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

// highScore // camel casing
// player1HighScore

// high-score // kebab casing

// HighScore // pascal casing

// high_score // snake casing

// DAYS_IN_A_WEEK = 7

// dayInAWeek = 7
// DAYSINAWEEK = 7

let highScore = 110;

highScore;

JS Scratchpad #2

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

// // console.log(greeting.toLowerCase().indexOf('welcome'));

// console.log(greeting.indexOf('Welcome').toUpperCase());

// let message = 'This is a \nmulti-line\nstring';

// let username = 'johndoe';

// let message2 = `
//                 This is a
//                 multiline (${username})
//                 string.`;

// console.log(message2);

// let cart = 10;
// let price = 99;

// // let message = 'You have ' + cart + ' items in your cart. Total cost: $' + price;

// // Interpolation
// let message = `You have ${cart} items in your cart. Total cost: $${price}`;

// console.log(message);

let hello = 'Hello World';
hello = 'Hello Universe';

let greeting2 = 'Something else';

console.log(hello);

JS Scratchpad #3

// let age = 10;

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

// let num = 20;

// if (num % 2 === 0) {
// 	console.log('Even');
// } else {
// 	console.log('Odd');
// }

// let age = 2;

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

// let age = 86;

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

let password = 'helloworld@123';

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

Scratchpad #4

// let loggedInUser = null;

// if (loggedInUser) {
// 	console.log('Welcome');
// }

// let age = 67;

// 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 drink');
// } else if (age >= 65) {
// 	console.log('Drinks are free');
// } else {
// 	console.log("You aren't allowed");
// }

// let day = 2;

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

// let num = 10;

// num === 7 || num === 10 ? console.log('Lucky') : console.log('Unlucky');

// if (num === 7) {
// 	console.log('Lucky');
// } else {
// 	console.log('Unlucky');
// }

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

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

// console.log(color);

Scratchpad #5

// // const movies = [
// // 	'Inception',
// // 	'Exorcist',
// // 	'Shutter Island',
// // 	'Ben Hurr',
// // 	'The Taxi Driver',
// // 	"Schindler's List",
// // ];

// let nums2 = [
// 	[1, 2, 3],
// 	[4, 5, 6],
// 	[7, 8, 9],
// 	[73, 83, 91],
// 	[37, 82, 79, 34, 1, 12],
// ];

// // console.log(nums2[nums2.length - 1].reverse()[0]);
// // console.log(nums2[nums2.length - 1][nums2[nums2.length - 1].length - 1]);

// const product1 = [
// 	'iPhone 13 Pro Max Plus',
// 	'Apple',
// 	'Some desc...',
// 	300,
// 	150000,
// 	true,
// ];
// const product2 = [
// 	'Macbook Pro 15 M2',
// 	'Apple',
// 	400000,
// 	'Some desc...',
// 	100,
// 	false,
// ];
// console.log(product2[3]);

// Collection of properties (property: key-value pair)
// const product3 = {
// 	name: 'iPhone 13 Pro Max Plus',
// 	brand: 'Apple',
// 	description: 'Some desc...',
// 	inventory: 300,
// 	discounted: true,
// 	price: 150000,
// 	123: 'hello world',
// 	'hello world': [1, 2, 3],
// 	profile: { firstName: 'John', lastName: 'Doe' },
// };
// console.log(product3.price);
// console.log(product3['price']);
// console.log(product3[123]);
// console.log(product3['hello world'][1]);
// console.log(product3.profile.lastName);
// console.log(product3.profile.firstName);

// const playlist = [
// 	{
// 		songName: 'Some name',
// 		artists: ['John doe', 'Jane Doe'],
// 		trackTime: 3.5,
// 		album: 'Some album name',
// 		trackUrl: 'https://...',
// 	},
// ];

// let key = 'songName';
// console.log(playlist[0][key]);

const product = {
	name: 'iPhone 13 Pro Max Plus',
	brand: 'Apple',
	description: 'Some desc...',
	inventory: 300,
	discounted: true,
	price: 150000,
};

product.brand = 'APPLE';
product['some thing'] = 'Hello World';
product[1234] = 'Hello World';
product.inventory++;
console.log(product);

Scratchpad #6

// for (let i = 0; i < 100; 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--) {
// 	console.log(i);
// }

// const nums = [121, 23, 45, 63, 12, 2, 5, 61, 12, 10];

// let total = 0;

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

// console.log(total);

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

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

// let name = 'hello';

// let reversedWord = '';

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

// console.log(reversedWord);

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

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

// const gameBoard = [
// 	[4, 64, 8, 4],
// 	[128, 32, 4, 16],
// 	[16, 4, 4, 32],
// 	[2, 16, 16, 2],
// ];

// let total = 0;

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

// console.log(total);

// const gameBoard = [
// 	[
// 		[4, 64, 8, 4],
// 		[4, 64, 8, 4],
// 		[4, 64, 8, 4],
// 		[4, 64, 8, 4],
// 	],
// 	[
// 		[4, 64, 8, 4],
// 		[4, 64, 8, 4],
// 		[4, 64, 8, 4],
// 		[4, 64, 8, 4],
// 	],
// 	[
// 		[4, 64, 8, 4],
// 		[4, 64, 8, 4],
// 		[4, 64, 8, 4],
// 		[4, 64, 8, 4],
// 	],
// 	[
// 		[4, 64, 8, 4],
// 		[4, 64, 8, 4],
// 		[4, 64, 8, 4],
// 		[4, 64, 8, 4],
// 	],
// ];

// const nums = [128, 32, 4, 16, 2, 1, -3, 55];

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

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

// while (true) {
// 	console.log(Math.random());
// }

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

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

// console.log(`Guess: ${guess} | Target: ${target}`);
// console.log(`You've guessed it! Number was ${target}`);

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

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

console.log(`You've guessed it! Number was ${target}`);

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

Scratchpad #7

// const arr = [20, 4, 1, 32, 3, 8, 1, 0, 9];
// console.log(arr);

// for (let i = 0; i < arr.length; i++) {
// 	for (let j = 0; j < arr.length; j++) {
// 		if (arr[j] > arr[j + 1]) {
// 			let temp = arr[j];
// 			arr[j] = arr[j + 1];
// 			arr[j + 1] = temp;
// 		}
// 	}
// }

// console.log(arr);

// const nums = [1, 12, 3, 3, 4, 512, 121, 234];

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

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

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

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

// for (let char of 'Hello World') {
// 	console.log(char);
// }

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

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

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

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

// let a = [1, 2, 3, 4];
// let a = { 0: 1, 1: 2, 2: 3, 3: 4 };

// console.log(a[0]);

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

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

// greet();

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

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

// function rollDice(times) {
// 	for (let i = 0; i < times; i++) {
// 		rollDie();
// 	}
// }

// rollDice(1);

// rollDie();

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

// rollTwice();

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

// greet('Hello', 'Jack'); // argument
// greet('John Doe', 'Hi');
// greet('Hi', 'Some name');

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

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

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

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

// let person = 'John Doe';

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

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

// let name = 'John Doe';

// if (true) {
// 	var name = 'Jack Smith';
// 	console.log(name);
// }

// console.log(name);

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

console.log(i);

Scratchpad #8

// let movie = 'Red Man';

// function outer() {
// 	// let movie = 'Gray Man';

// 	function inner() {
// 		// let movie = 'Blue Man';
// 		console.log(movie);
// 	}

// 	inner();
// }

// outer();

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

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

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

// const name = 'john';

// // Function expression / Anonyomous functions
// 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, 3, add));

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

// const func = [
// 	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(func[2](10, 2));

// const math = {
// 	PI: 3.141592653589793,
// 	add: function (a, b) {
// 		return a + b;
// 	},
// };

// console.log(math.PI);
// math.add(10, 4);

// console.log(Math.PI);

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

// const sub = function (x, y) {
// 	return x - y;
// };

// const mul = function (x, y) {
// 	return x * y;
// };

// function div(x, y) {
// 	return x / y;
// }

// const operations = [
// 	add,
// 	sub,
// 	mul,
// 	div,
// 	function (num) {
// 		return num * num;
// 	},
// ];

// console.log(operations[1](10, 4));
// console.log(operations[operations.length - 1](10));

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

// console.log(operations.add(10, 43));
// console.log(operations.sub(10, 43));

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

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

// function multipleGreets(fn, times) {
// 	for (let i = 0; i < times; i++) {
// 		fn();
// 	}
// }

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

// multipleGreets(sayGoodbye, 3000);

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

const result = add(10, 5);

// // Parent function
// function raiseBy(num) {
// 	// child function
// 	const func = function (x) {
// 		return x ** num;
// 	};

// 	return func;
// }

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

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

// // const hello = raiseBy(2);

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

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

const isUnderAge = isBetween(0, 18);
const isLegalAge = isBetween(18, 65);

console.log(isUnderAge(9));
console.log(isLegalAge(21));

Scratchpad #9

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

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

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

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

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

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

// console.log(firstName);

// var firstName = 'John';

// const nums = [12, 123, 12, 23, 4, 55, 6567, 5678];

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

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

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

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

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

// const upperNames = names.map(function (name) {
//   return `${name}`;
// });

// console.log(upperNames);

// const upperNames = [];

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

// console.log(upperNames);

// const nums = [2, 3, 4, 7, 6, 8, 13, 10, 19, 12, 14, 22, 21, 16];

// const doubles = nums.map(function (num) {
//   return num * 2; // we have to return a value
// });
// console.log(doubles);

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

// console.log(result);

// const nums = [2, 3, 4, 7, 6, 8, 13, 10, 19, 12, 14, 22, 21, 16];

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

// // console.log(doubles);

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

// const s = n => n * n;

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

// const nums = [2, 3, 4, 7, 6, 8, 13, 10, 19, 12, 14, 22, 21, 16];

// const doubles = nums.map(n => n * 2);
// console.log(doubles);

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

// const result = movies.find((movie) => {
//   return movie.includes('The');
// });

// 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.filter((book) => book.rating > 4);
// const result = books.find((book) => book.author.includes('George'));
console.log(result);

Scratchpad #10

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

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

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

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

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

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

// const result = names.some((word) => {
//   return word[0] === 'b';
// });

// console.log(result);

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

// // prices.sort();

// // console.log(prices);

// const sortedNumbers = prices.sort((a, b) => b - a);
// console.log(sortedNumbers);

// const nums = [1, 12, 32, 42, 12, 45, 12];

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

// console.log(
//   `The total of nums: ${nums.reduce((acc, currVal) => {
//     return acc - currVal;
//   })}`
// );

// acc     |    currVal
// 1            12
// 13           32
// 45           42
//

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

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

// const maxVal = nums.reduce((acc, currVal) => {
//   return Math.max(acc, currVal);
// });

// console.log(maxVal);

// acc curVal
// 21  221
// 221 2
// 221 1
// 221 34
// 221 123
// 221 4342
// 4342 56
// 4342 4
// 4342

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

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

// console.log(result);

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

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

// const greet = (name, message = 'hi') => {
//   console.log(`${message}, ${name}`);
// };

// greet('John', 'hello');

// const add = (a, b) => {
//   // if (typeof b === 'undefined') {
//   //   b = 0;
//   // }
//   b = typeof b === 'undefined' ? 0 : b;
//   return a + b;
// };

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

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

const data = ['john', 'jack', 'jane', 'hello', 'world'];

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

printValues(...'hello');

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

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

Scratchpad #11

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

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

// console.log(add(10, 23, 4312, 1, 123, 44, 5767, 89));

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

// printNames('John', 'Jack', 'hello', 'world', 'universe');

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

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

// console.log(admin, others);

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

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

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

// const printDetails = ({ name, age, city }) => {
//   console.log(
//     `Hello my name is ${name}. I am ${age} years old and I live in ${city}.`
//   );
// };

// printDetails({ name: 'John Doe', age: 20, city: 'Dhaka' });

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

// console.log(result);

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

// const profile = {
//   [role.toUpperCase()]: username,
//   [1 + 23 * 12]: 'Hello World',
// };

// console.log(profile);

// const addProp = (obj, key, value) => {
//   return { ...obj, [key]: value };
// };

// const result = addProp({ firstName: 'John', lastName: 'Doe' }, 'age', 20);

// console.log(result);

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

// const math = {
//   PI: 3.1415,
//   add(a, b) {
//     return a + b;
//   },
//   sub(a, b) {
//     return a - b;
//   },
//   square,
// };

// console.log(math.add(10, 3));
// console.log(math.square(10));

// console.log({
//   firstName: 'John',
//   lastName: 'Doe',
//   greet() {
//     console.log('Hello World');
//   },
// });

// console.log(this);

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

// helloWorldFromJS();

// const meraObject = {
//   helloWorld() {
//     console.log(this.firstName);
//   },
//   firstName: 'John',
//   lastName: 'Doe',
// };

// meraObject.helloWorld();

let helloWorld = 'Hello World';

console.log(window);

index.html file

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1>My App</h1>

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

Scratchpad #12

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

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

// for (let p of paras) {
//   console.log(p.innerText);
// }

// const lists = document.getElementsByClassName('my-list');

// const secondList = lists[2];

// const cancelled = secondList.getElementsByTagName('strike');
// console.log(cancelled);

// const paras = document.querySelectorAll('p');
// const p = document.querySelectorAll('#impPara');
// const lists = document.querySelectorAll('.my-list');

// console.log(paras);

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

// const h1 = document.querySelector('h1');
// h1.innerText = 'THIS IS SOME NEW TEXT';
// // console.log(h1.innerText);

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

// ol.innerText = 'Hello World';

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

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

// const p = document.querySelector('p');
// p.innerHTML = 'Hello World. <b>This is some other text</b>';
// p.innerHTML += '. This is some <i>text</i>';

// const i = document.querySelector('input');
// i.value = 800;
// console.log(i.value);

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

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

// a.href = 'https://rstforum.net';
// a.innerText = 'RST Forum';

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

// range.setAttribute('min', 432434);
// range.min = 234234;
// console.log(range.getAttribute('min'));
// console.log(range.getAttribute('href'));
// console.log(range.min);
// console.log(range.href);

// range.setAttribute('min', 500);
// range.setAttribute('max', 5000);
// range.min = 200;

// console.log(range.min);
// console.log(range.max);

// range.setAttribute('value', 3000);
// range.setAttribute('type', 'text');

// const p = document.querySelector('#impPara');
// // console.log(p.parentElement.parentElement.parentElement);
// // console.log(p.parentElement.nextElementSibling);
// console.log(
//   p.parentElement.previousElementSibling.previousElementSibling
//     .previousElementSibling
// );

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

// console.log(ul.children);

// const lis = document.querySelectorAll('li');
// for (let li of lis) {
//   li.innerText = 'CHANGED';
// }

// const lis = document.querySelectorAll('li');
// for (let li of lis) {
//   li.style.color = 'red';
//   li.style.textDecoration = 'underline';
//   li.style.backgroundColor = 'yellow';
// }

const nav = document.querySelector('nav');
nav.style.backgroundColor = 'green';

console.log(nav.style.backgroundColor);

Scratchpad #13

// const para = document.querySelector('p');
// // para.style.color = 'green';
// // console.log(para.style.color);

// const paraStyles = getComputedStyle(para);
// console.log(paraStyles.color);
// console.log(paraStyles.textDecoration);

// para.style.color = 'red';
// console.log(paraStyles.color);

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

// // para.style.color = 'gray';
// // para.style.textDecoration = 'line-through';
// // para.style.opacity = 0.5;

// // para.setAttribute('class', 'done');

// // console.log(para.classList);

// // para.classList.add('done');
// // para.classList.remove('done');
// para.classList.toggle('done');

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

// const title = document.createElement('h1');

// title.innerText = 'Hello World from the DOM';
// title.style.color = 'red';
// title.style.textDecoration = 'underline';
// title.style.fontSize = '40px';

// const title2 = document.createElement('h2');
// title2.innerText = 'This is an h2 element created in JavaScript';
// title2.style.color = 'green';

// const div = document.createElement('div');
// div.style.border = '5px solid red';
// div.style.padding = '50px';

// div.appendChild(title);

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

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

// const l1 = document.createElement('li');
// l1.innerText = 'This is task 1';

// todos.appendChild(l1);

// const l2 = document.createElement('li');
// l2.innerText = 'This is task 2';

// // todos.appendChild(l2);
// todos.insertBefore(l2, l1);

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

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

// 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 l1 = document.createElement('li');
// l1.innerText = 'This is task 1';

// todos.appendChild(l1);

// const l2 = document.createElement('li');
// l2.innerText = 'This is task 2';

// todos.appendChild(l2);

// // todos.removeChild(l1);
// l1.remove();
// l2.remove();

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

// btn.onclick = function () {
//   // console.log(Math.random());
//   let num = Math.random();
//   const p = document.createElement('p');
//   p.innerText = num;
//   p.onclick = function () {
//     p.remove();
//   };
//   root.append(p);
// };

// btn.onclick = function () {
//   console.log('I added a para');
// };

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

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

// btn.addEventListener('click', function () {
//   console.log('This is something else');
// });

// btn.addEventListener('mouseout', function () {
//   console.log('I was hovered');
// });

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

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

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

// btn.addEventListener('click', function () {
//   btn.innerText = 'YOU WON!';
//   document.body.style.backgroundColor = 'green';
// });

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

// function printColor(el) {
//   h1.innerText = el.style.backgroundColor;
// }

function printColor() {
  h1.style.color = this.style.backgroundColor;
  h1.innerText = this.style.backgroundColor + ' selected';
}

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

for (let color of colors) {
  const box = document.createElement('div');
  box.style.backgroundColor = color;
  box.classList.add('box');

  box.addEventListener('click', printColor);

  // box.addEventListener('click', function () {
  //   // h1.innerText = color;
  //   printColor(box);
  // });

  container.append(box);
}

Scratchpad #14

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

// function printColor() {
//   h1.style.color = this.style.backgroundColor;
//   h1.innerText = this.style.backgroundColor + ' selected';
// }

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

// for (let color of colors) {
//   const box = document.createElement('div');
//   box.style.backgroundColor = color;
//   box.classList.add('box');

//   box.addEventListener('click', function (e) {
//     console.dir(e.target.clientHeight);
//     console.log(box.style.backgroundColor);
//   });

//   container.append(box);
// }

// const inp = document.querySelector('#something');
// const p = document.querySelector('p');

// inp.addEventListener('keypress', function (event) {
//   p.innerText = event.target.value;
// });

// const form = document.querySelector('form');
// const tasksList = document.querySelector('#tasks');

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

//   const taskItem = document.createElement('li');
//   taskItem.innerText = e.target.children.taskName.value;
//   taskItem.addEventListener('click', function () {
//     // taskItem.style.textDecoration = 'line-through';
//     taskItem.classList.toggle('cancelled');
//   });

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

//   taskItem.append(delBtn);

//   tasksList.append(taskItem);

//   e.target.children.taskName.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(3, 4, 5);

// console.log('The first log');
// alert('An interruption in between');
// console.log('The last log');

// console.log('The first log');

// setTimeout(function () {
//   console.log('I just in the callback function');
// }, 3000);

// console.log('The last log');

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

setTimeout(function () {
  btn.style.transform = 'translateX(100px)';
  setTimeout(function () {
    btn.style.transform = 'translateX(200px)';
    setTimeout(function () {
      btn.style.transform = 'translateX(300px)';
      setTimeout(function () {
        btn.style.transform = 'translateX(400px)';
        setTimeout(function () {
          btn.style.transform = 'translateX(500px)';
          setTimeout(function () {
            btn.style.transform = 'translateX(600px)';
          }, 1000);
        }, 1000);
      }, 1000);
    }, 1000);
  }, 1000);
}, 1000);

Scratchpad #15

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

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

// console.log(willGetPS);

// willGetPS.then(() => {
//   console.log('I got a PS. Thank you parents.');
// });

// willGetPS.catch(() => {
//   console.log('I did not get anything.');
// });

// willGetPS
//   .then(() => {
//     console.log('I got a PS. Thank you parents.');
//   })
//   .catch(() => {
//     console.log('I did not get anything.');
//   });

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

// makePSPromise()
//   .then(() => {
//     console.log('Yayyyy');
//   })
//   .catch(() => {
//     console.log('Booooo');
//   });

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

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

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

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

//         // Make another request
//         fakeRequest(`/posts/${postId}`)
//           .then((response) => {
//             console.log(response);
//           })
//           .catch((err) => {
//             console.log(err);
//           });
//       })
//       .catch((error) => {
//         console.log(error);
//       });
//   })
//   .catch((err) => {
//     console.log(err);
//   });

Scratchpad #16

// // XML
// <songs>
// 	<song>
// 		<title>Song #1</title>
// 		<artists>
// 			<artist>Artist #1</artist>
// 			<artist>Artist #2</artist>
// 		</artists>
// 		<album>Album name</album>
// 		<track-length>3.20</track-length>
// 		<downloadable>true</downloadable>
// 	</song>
// 	<song>
// 		<title>Song #1</title>
// 		<artists>
// 			<artist>Artist #1</artist>
// 			<artist>Artist #2</artist>
// 		</artists>
// 		<album>Album name</album>
// 		<track-length>3.20</track-length>
// 		<downloadable>true</downloadable>
// 	</song>
// </songs>;

// // JSON
// // JavaScript Object Notation

// [
// 	{
// 		"title": "Song #1",
// 		"artists": [
// 			"Artist #1",
// 			"Artist #2"
// 		],
// 		"album": "Album name",
// 		"trackLength": 3.20,
// 		"downloable": true
// 	},
// 	{
// 		"title": "Song #1",
// 		"artists": [
// 			"Artist #1",
// 			"Artist #2"
// 		],
// 		"album": "Album name",
// 		"trackLength": 3.20,
// 		"downloable": true
// 	}
// ]

// fetch('https://swapi.dev/api/people', {
// 	headers: { Accept: 'application/json' },
// })
// 	.then((response) => {
// 		return response.json();
// 	})
// 	.then((data) => console.log(data))
// 	.catch((err) => console.log(err));

// fetch('https://swapi.dev/api/people', {
// 	headers: { Accept: 'application/json' },
// })
// 	.then((response) => {
// 		if (!response.ok) {
// 			throw new Error('THIS IS STUPID');
// 		}
// 		return response.json();
// 	})
// 	.then((data) => {
// 		// console.log(data);
// 		// for (let person of data.results) {
// 		// 	console.log(person.name);
// 		// }
// 		return fetch(data.results[0].homeworld);
// 	})
// 	.then((response) => {
// 		if (!response.ok) {
// 			throw new Error('THIS IS EVEN MORE STUPID');
// 		}
// 		return response.json();
// 	})
// 	.then((data) => {
// 		console.log(data);
// 	})
// 	.catch((err) => {
// 		console.log(err);
// 	});

// axios
// 	.get('https://swapi.dev/api/people')
// 	.then(({ data }) => {
// 		return axios.get(data.results[0].homeworld);
// 	})
// 	.then(({ data }) => {
// 		console.log(data);
// 	})
// 	.catch((err) => {
// 		console.log(err);
// 	});

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

// root.style.display = 'grid';
// root.style.gridTemplateColumns = '1fr 1fr 1fr 1fr';
// root.style.gap = '20px';

// axios
// 	.get('https://swapi.dev/api/people')
// 	.then(({ data }) => {
// 		data.results.map((person) => {
// 			const box = document.createElement('div');
// 			box.style.border = '2px solid black';
// 			box.style.borderRadius = '10px';
// 			box.style.padding = '5px 20px';

// 			const title = document.createElement('h4');
// 			title.innerText = person.name;

// 			const p = document.createElement('p');
// 			p.innerHTML = `<b>Gender</b>: ${person.gender}`;

// 			box.append(title, p);
// 			root.append(box);
// 		});
// 	})
// 	.catch((err) => {
// 		console.log(err);
// 	});

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

// getData();

// async function greet() {
// 	throw new Error('Fail');
// }

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

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

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

// // Function that manually returns a promise

// function add(x, y) {
// 	return new Promise((resolve, reject) => {
// 		if (typeof x !== 'number' || typeof y !== 'number') {
// 			reject('X and Y must be numbers');
// 		}
// 		resolve(x + y);
// 	});
// }

// add(10, 12)
// 	.then((res) => console.log(res))
// 	.catch((err) => console.log(err));

console.log('I am a log');

async function getData() {
	try {
		const response = await axios.get('https://swapi.dev/api/planets');
		console.log(response);
	} catch (err) {
		console.log(err.message);
	}
}

getData();

// getData().catch((err) => {
// 	console.log(err);
// });

console.log('I am a log');

Scratchpad 17

// const getPokemon = async () => {
// 	const p1Promise = axios.get('https://pokeapi.co/api/v2/pokemon/ditto');
// 	const p2Promise = axios.get('https://pokeapi.co/api/v2/pokemon/pikachu');
// 	const p3Promise = axios.get('https://pokeapi.co/api/v2/pokemon/venusaur');

// 	// const p1 = await p1Promise;
// 	// const p2 = await p2Promise;
// 	// const p3 = await p3Promise;

// 	const results = await Promise.all([p1Promise, p2Promise, p3Promise]);

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

// getPokemon();

// 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);
// drawCard(deck, hand);
// drawMultiple(3, 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() {
// 			for (let value of this.values.split(',')) {
// 				for (let suit of this.suits) {
// 					this.deck.push({ value, suit });
// 				}
// 			}
// 			return this.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 game1 = makeDeck();
// const game2 = makeDeck();

// console.log(game1);
// console.log(game2);

// // game.initializeDeck();
// // game.drawCard();
// // game.drawMultiple(4);

// // console.log(game);

// function person(firstName, lastName, age) {
// 	return {
// 		firstName,
// 		lastName,
// 		age,
// 		greet() {
// 			console.log(`Hello my name is ${this.firstName} ${this.lastName}`);
// 		},
// 	};
// }

// function Person(firstName, lastName, age) {
// 	this.firstName = firstName;
// 	this.lastName = lastName;
// 	this.age = age;
// 	// this.greet = function () {
// 	// 	console.log(`Hello my name is ${this.firstName} ${this.lastName}`);
// 	// };
// }

// Person.prototype.greet = function () {
// 	console.log(`Hello my name is ${this.firstName} ${this.lastName}`);
// };
// Person.prototype.hello = 'World';

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

// 	greet() {
// 		console.log(`Hello my name is ${this.firstName} ${this.lastName}`);
// 	}
// }

// const john = person('John', 'Doe', 20);
// const jane = person('Jane', 'Doe', 22);
// const jack = new Person('Jack', 'Smith', 25);
// const jill = new Person('Jill', 'Smith', 27);

// console.log(john);
// console.log(jane);
// console.log(jack);
// console.log(jill);

// jill.greet();

// 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()
// deck1.initializeDeck()
// deck1.shuffle()
// const deck2 = new Deck()
// deck2.initializeDeck()
// deck2.shuffle()

// deck1.drawCard()
// deck2.drawCard()
// deck2.drawCard()
// deck2.drawMultiple(2)

// console.log(deck1)
// console.log(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) {
		super(username, password);
		this.totalVideos = totalVideos;
	}

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

const john = new User('johndoe', 'john123');
const jane = new Subscriber('janedoe', 'jane123');
const jack = new Creator('jack', 'jack123', 23);

console.log(jack);
// // console.log(john);
// john.login('john123');
// jane.login('jane123');
// jane.logout();

React #1

<!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</title>
	</head>
	<body>
		<div id="root"></div>

		<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
		<script
			crossorigin
			src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
		<script
			crossorigin
			src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>

		<script type="text/babel">
			// const root = document.querySelector('#root');
			// const title = document.createElement('h1');
			// title.innerText = 'My Application';
			// root.append(title);

			// const title = React.createElement('h1', {
			// 	children: 'Hello World from React',
			// 	className: 'special',
			// 	id: 'helloworld',
			// });

			// const h1 = React.createElement('h1', null, 'My React Application');
			// const p = React.createElement(
			// 	'p',
			// 	null,
			// 	'Lorem ipsum dolor sit amet consectetur adipisicing elit'
			// );
			// const div = React.createElement('div', { children: [h1, p] });

			// const div2 = React.createElement(
			// 	'div',
			// 	null,
			// 	React.createElement('h2', null, 'I am a second heading'),
			// 	React.createElement('p', null, 'Amet consectetur adipisicing elit')
			// );

			// const React = {
			// 	createElement(elName, options, childEl) {
			// 		const el = document.createElement(elName);
			// 		el.innerText = childEl;
			// 		for (let opt in options) {
			// 			el[opt] = options[opt];
			// 		}
			// 		return el;
			// 	},
			// 	render(el, target) {
			// 		target.append(el);
			// 	},
			// };

			// const h1 = React.createElement(
			// 	'h1',
			// 	{ className: 'hello' },
			// 	'This is my own React'
			// );
			// React.render(h1, document.querySelector('#root'));

			// const div2 = React.createElement(
			// 	'div',
			// 	null,
			// 	React.createElement('h2', null, 'I am a second heading'),
			// 	React.createElement('p', null, 'Amet consectetur adipisicing elit')
			// );

			// const div2 = (
			// 	<div>
			// 		<h2>I am a second heading</h2>
			// 		<p>Amet consectetur adipisicing elit</p>
			// 	</div>
			// );

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

React #2

<!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</title>
	</head>
	<body>
		<div id="root"></div>

		<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
		<script
			crossorigin
			src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
		<script
			crossorigin
			src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>

		<script type="text/babel">
			// const root = document.querySelector('#root');
			// const title = document.createElement('h1');
			// title.innerText = 'My Application';
			// root.append(title);

			// const title = React.createElement('h1', {
			// 	children: 'Hello World from React',
			// 	className: 'special',
			// 	id: 'helloworld',
			// });

			// const h1 = React.createElement('h1', null, 'My React Application');
			// const p = React.createElement(
			// 	'p',
			// 	null,
			// 	'Lorem ipsum dolor sit amet consectetur adipisicing elit'
			// );
			// const div = React.createElement('div', { children: [h1, p] });

			// const div2 = React.createElement(
			// 	'div',
			// 	null,
			// 	React.createElement('h2', null, 'I am a second heading'),
			// 	React.createElement('p', null, 'Amet consectetur adipisicing elit')
			// );

			// const React = {
			// 	createElement(elName, options, childEl) {
			// 		const el = document.createElement(elName);
			// 		el.innerText = childEl;
			// 		for (let opt in options) {
			// 			el[opt] = options[opt];
			// 		}
			// 		return el;
			// 	},
			// 	render(el, target) {
			// 		target.append(el);
			// 	},
			// };

			// const h1 = React.createElement(
			// 	'h1',
			// 	{ className: 'hello' },
			// 	'This is my own React'
			// );
			// React.render(h1, document.querySelector('#root'));

			// const div2 = React.createElement(
			// 	'div',
			// 	null,
			// 	React.createElement('h2', null, 'I am a second heading'),
			// 	React.createElement('p', null, 'Amet consectetur adipisicing elit')
			// );

			// const div2 = (
			// 	<div>
			// 		<h2>I am a second heading</h2>
			// 		<p>Amet consectetur adipisicing elit</p>
			// 	</div>
			// );

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

			// // const p1 = React.createElement(
			// // 	'p',
			// // 	{ className: 'title' },
			// // 	'Hello World'
			// // );
			// // const p = <p className={className} children={children} />;
			// const p = <p {...props} className='hello' />;

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

			// const el = <p className={myClassName}>{message.toUpperCase()}</p>;

			// const blogPost = (
			// 	<article>
			// 		<h4>My Title</h4>
			// 		<p>Some paragraph.. some text</p>
			// 		<a href='#'>Read more</a>
			// 	</article>
			// );

			// const blogPost = (props) => {
			// 	return (
			// 		<article>
			// 			<h4>{props.title}</h4>
			// 			<p>{props.content}</p>
			// 			<a href={props.url}>Read more</a>
			// 		</article>
			// 	);
			// };

			// const blogPost = ({ title, content, url }) => {
			// 	return (
			// 		<article>
			// 			<h4>{title}</h4>
			// 			<p>{content}</p>
			// 			<a href={url}>Read more</a>
			// 		</article>
			// 	);
			// };

			// const blogPost = ({ title, children, url }) => {
			// 	return (
			// 		<article>
			// 			<h4>{title}</h4>
			// 			<p>{children}</p>
			// 			<a href={url}>Read more</a>
			// 		</article>
			// 	);
			// };

			const BlogPost = ({ title, children, url }) => {
				return (
					<article>
						<h4>{title}</h4>
						<p>{children}</p>
						<a href={url}>Read more</a>
					</article>
				);
			};

			const div = (
				<div>
					{React.createElement(
						BlogPost,
						{
							title: 'My second blog post',
							url: '#',
						},
						'Some more paragraph text'
					)}

					<BlogPost title='My Third Blog Post' url='#'>
						Some more paragraph text
					</BlogPost>
				</div>
			);

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

<!-- <h1 className="hello">Hello World</h1> // React.createElement('h1', {className: 'hello'}, 'Hello WOrld') -->

<!-- {React.createElement(blogPost, {
	title: 'My first blog post',
	children: 'Some paragraph text',
	url: '#',
})}

{React.createElement(
	blogPost,
	{
		title: 'My second blog post',
		url: '#',
	},
	'Some more paragraph text'
)} -->

<!-- {blogPost({
	title: 'My first blog post',
	content: 'Some paragraph text',
	url: '#',
})}
{blogPost({
	title: 'My second blog post',
	content: 'Some paragraph text',
	url: '#',
})} -->

<!-- // Component that represents a blog post
function BlogPost({ title, date, author, children }) {
  return (
    <article>
      <h3>{title}</h3>
      <p>Published on <i>{date}</i> by <b>{author}</b></p>
      <hr />
      <p>{children}</p>
    </article>
  )
}
 
const element = (
  <div className='container'>
    <BlogPost
      title='Welcome to the world of React'
      date={new Date().toDateString()}
      author='John Doe'>
      Lorem ipsum, dolor sit amet consectetur adipisicing elit.
      Consequatur error ad quos vero reprehenderit excepturi officiis
      vitae iste soluta et.
    </BlogPost>
  </div>
)
 
ReactDOM.render(element, document.querySelector('#root')) -->

React Files Zip

React Node ZIP

Project

Project

  1. Generate some boilerplate for a basic React application.
    • Go into your workspace/projects directory using the terminal.
    • cd ~/Documents/FullStack/Workspace
    • mkdir rststore
    • npx create-react-app@latest frontend –use-npm
    • code .
    • cd frontend
    • npm start
    • Open public/index.html and clean up the file. Remove all the comments and change the title and meta content.
    • Delete all the files in the src folder. Create and add basic boilerplate code to App.js and index.js.

2. Chakra UI Installation and Setup

  • npm i @chakra-ui/react @emotion/react @emotion/styled framer-motion
  • npm install react-icons –save
  • Edit index.js file. Import ChakraProvider component and wrap the App component with it.

3. Create Header and Footer components

  • Create a folder called src/components in the src folder and add all components in that.

4. Create HomeScreen product listings

  • Create the HomeScreen component (all display/screen components will go in the /screens folder), along with the product and ratings components.

5. Install and Implement React Router

  • npm install react-router-dom
  • Complete all the React Router setup on the App page.
  • Modify Product cards, Header links etc. Use React Routers Link component instead.

6. Design and build the ProductScreen component.

  1. Setting up the backend
    • Close the React server.
    • Create a folder named backend outside the frontend folder in the root of our project.
    • npm init in the root. (not inside the backend or frontend folders, but outside in the root directory)
    • During npm init setup the main will be server.js
    • npm install express (in the root folder)
    • Create a file backend/server.js in the backend folder and a folder data and copy products.js to this folder.
    • Create some routes to serve the data from the backend
    • Create a script for start in package.json
    • Create 2 basic routes for ‘/’ and ‘/api/products’
    • Convert products.js export statement to commonjs format.
    • Create another route to fetch single product by id.
  1. Fetching data from our backend using React
    • Inside the frontend folder, run npm install axios
    • Modify the HomeScreen component to fetch and store data in the component.
    • To fix the issue of our backend address for now, we’ll add a proxy to the frontend’s package.json. Add this “proxy”: “http://127.0.0.1:5000”, to frontend/package.json
    • Make sure both frontend and backend are running in two terminals and test it out.
    • Modify the ProductScreen component to also make a request to our backend to fetch data.
    • Delete the projects.js file from our frontend’s src folder as we no longer need it.

9. More backend setup

  • In the root directory: run
  • npm install -D nodemon concurrently. ‘-D’ is a dev dependency, meaning we only need these modules during development.
  • These above packages will help us auto restart our server when we change our code, so we don’t have to do it manually.
  • Modify scripts in package.json (root folder) to add some scripts to use our npm command directly to work them.

10. Setup environment variables

  • npm install dotenv
  • Do the dotenv setup in server.js file and create a .env file in the root folder.

11. Convert imports to ES Modules

  • Add “type”: “module” to package.json file. Change all import and export statements to ES module style.
  • Note: You will have to add .js extension while using ES modules in the backend.

12. Install and setup MongoDB

  • After installation, setup MongoDB Compass
  • Use this as the connection string: mongodb://localhost:27017/rststore
  • Add the following in the .env
    MONGO_URI = mongodb://localhost:27017/rststore

13. Connect to the database

  • Install mongoose: npm install mongoose (in the root folder)
  • Create a folder named config in the backend folder and create a file named backend/config/db.js inside it.
  • Do all the mongoDB connection setup
  • Import db.js into server.js and run the connectDB function.
  • Start the server and check if any error.

14. Improve console log messages.

  • Run this command in the root folder: npm install colors
  • Add stylings to server and db console messages.

15. Create database models for data

  • Create a models folder inside the backend folder.
  • Create all our data model schemas.

16. Prepare sample data for the backend data seeding

  • Delete all the _id key-values from the products.js as MongoDB
    will automatically create it for us.
  • Create data/users.js file and fill it with a few user objects.
  • npm install bcryptjs – for password hashing
  • Use bcryptjs for the password fields to encrypt the password. (temporary)

17. Create database seeder for quick sample data generation (optional)

  • Create backend/seeder.js file inside the backend folder.
  • Add seeding logic and create import and destroy scripts.

18. Fetching products from the database

  • Create a folder named backend/routes in the backend folder.
  • Create a file named backend/routes/productRoutes.js
  • npm install express-async-handler – we will wrap our callbacks with this function so that we can do error handler in a better way.
  • Move the products and single product fetch routes to this file and add all the logic for now.
  • Test the routes in Postman

19. Do Postman setup to work with our API (optional)Custom error handling. Run the following in the root folder.

20. Custom error handling. Run the following in the root folder.

  • npm install express-async-handler
  • Create a folder named backend/middleware in the backend folder
  • Create an errorMiddleware.js and add logic to handle errors.

21. Introduction to Redux

  • The Redux Pattern
  • Download the Redux DevTools brower extension.
  • Go to the frontend folder. cd frontend
  • npm install redux react-redux redux-thunk redux-devtools-extension
  • In the src folder, create a file named store.js
  • Import Provider and store into the index.js and do all the setup.

22. Create our first reducer

  • In frontend/src create a folder called reducers – (frontend/src/reducers).
  • Create a file (our reducer) named productReducer.js inside the reducers folder and add all the reducer logic.
  • Next, import productListReducer to store.js and add it to the combineReducers({}) function’s argument object as a new key/value.
  • Create a folder called constants in the frontend/src folder and inside it create the productConstants.js file to store all our action names.
  • Create a folder called actions in the frontend/src folder and inside it create the productActions.js file to store all our action functions. We will dispatch actions to our reducer.
  • All these steps, we do for each resource of our app. So, whether it’s products, or users or some other model/feature, this is the format/pattern we will follow for Redux. We create the constant, the reducer the action and then we fire it off in the component.
  • Next, we now want to fire this action off in our HomeScreen components where we need this products data.

  1. Getting Redux State in the Home Screen
    • Clean up the file. Remove axios import, the [products, setProducts] state variables and remove everything from inside useEffect. We don’t need these anymore.
    • Import useDispatch and useSelector from ‘react-redux’. Also import listProducts from ‘../actions/productActions’.
    • The first hook will be used to dispatch/call an action, and the other is use to select parts of the state. Here we will need the productList part of the state.
    • Create the dispatch object using the useDispatch hook and call it in useEffect to fire the listProducts action.
    • To select products from our state, we need to use the useSelector hook. This hook will take in an arrow function. This function gets state and then we can select which part of the state do we want.
    • Add a conditional to display a loading messageerror message or our product list.

24. Create Message and Loader components.

  • Use the Spinner and Alert components from ChakraUI to add these.

25. Single product details screen Reducer and Action

  • Again, we will follow the same pattern/steps as earlier.
  • Start off by adding the required constants. Since this is for the single product screen, we will add the constants once again to the productConstants.js
  • Create a new reducer named productDetailsReducer in productReducers.js.
  • Whenever we create a new reducer, we have to add it to our store. So, import productDetailsReducer in the store.js file and add a new piece of state named productDetails.
  • Next, step will be to create an action. Add a new action named listProductDetails to the actions file.
  • Next, in the ProductScreen.js, get rid of axios and clean up useEffect. Import useDispatchuseSelector and the listProductDetails action that we just created.
  • Create the dispatch object and dispatch the listProductDetails action in the useEffect hook. You will now be able to see the state in Redux Devtools.
  • Use useSelector hook and select the productDetails piece of state. De-structure the correct values and use them in the JSX to display the product details, error and loading components.

26. Cart and Quantity

  • Add a quantity select box with it’s logic to only contain the number of items in stock.
  • The add to cart button should redirect to the a cart page/screen with the product id and quantity as a query string.

27. Cart Screen and Route

  • Create screens/CartScreen.js file in the screens folder.
  • Import this new CartScreen.js component in the App.js file and create a route for the Cart screen<Route path=’/cart/:id?’ component={CartScreen} />
  • The :id? question mark here means that this id is optional in the route/address. Because if we directly go to the cart page we will not have any id.

28. Cart Functionality

  • Create constants/cartConstants.js and add CART_ADD_ITEM and CART_REMOVE_ITEM constant varaibles to it.
  • Create reducers/cartReducer.js and add the reducer logic.
  • Import cartReducer.js in store.js and add the cartReducer function to the combineReducers argument object.
  • Create actions/cartActions.js. Do the below steps for the building the cart actions.
  • Import axios. We need axios to make a request to /api/products/:id to get the data/fields for that particular product.
  • Import CART_ADD_ITEM from actions/cartActions.js.
  • Then create the addToCart function which will get a (id, qty). We will get both these from the URL params.
  • We will need to use thunk as we are making an async request. So we will return an async function from it. This async function will get (dispatch, getState)dispatch is used for dispatching as usual, but getState will allow us to get our entire state tree. So anything we want like productListproductDetailscart, we can get it using getState.
  • After dispatching, we also want to store this in localStorage.
  • getState().cart.cartItems will give us back a JavaScript object and we can only store strings in the browser localStorage. Hence we have to stringify it. And when we want to take it out and read, we will have to parse it using JSON.parse
  • So we saved it to localStorage but where do we get it to actually fill the state, whenever we reload. We do that in the store.js.
  • We will first see if there is anything in cartItems in the localStorage. If it’s there, then we will add it to the initial state, so always loaded on the app’s first load. If nothing is present in the localStorage then we will just add an empty array.

29. Completing CartScreen.js and creating ‘add to cart’ functionality

  • Build the add to cart functionality.
  • Finish the CartScreen.js component.
  • Add functionality to the Remove Item from cart button. Follow the steps below:
  • Add CART_REMOVE_ITEM to the cartReducer.js file.
  • Create an action named removeFromCart in the cartActions.js file.
  • Fire this action in the removeFromCartHandler function in the CartScreen component.

30. Clean up the backend routes by extracting their logic into controllers

  • In the backend folder, create a folder called controller and create a file called productController.js inside it.
  • Extract all the logic to the productController.js from the routes file. The routes file should now only be for routing and all logic will go in to the controllers.
  • In productRoutes.js instead of using the method router.use(), instead use router.route() and add the route inside and then chain the appropriate methods get, post, put, delete etc. to it. This way we can define different controller logic to the same route. We will see this in sometime.