├── Loops exercises ├── Function Exercises ├── Introduction to JavaScript Exercises ├── Control Structures and Data Handling exercises ├── Advanced Function Exercises ├── Introduction to JavaScript └── introsamples ├── Modules Exercsises Code ├── Conditional Statements ├── intro exercises ├── HTTP methods exercises ├── Promises Exercises ├── Features Modern Exercises ├── working with APIs exercises ├── event handling exercises ├── error exercises └── async await exercises /Loops exercises: -------------------------------------------------------------------------------- 1 | for (let i = 1; i <= 10; i++) { 2 | console.log(i); 3 | } 4 | let i = 10; 5 | while (i > 0) { 6 | console.log(i); 7 | i--; 8 | } 9 | 10 | let number; 11 | do { 12 | number = parseInt(prompt("Enter a number (0 to stop):"), 10); 13 | console.log("You entered:", number); 14 | } while (number !== 0); 15 | 16 | for (let i = 0; i < 5; i++) { 17 | let line = ''; 18 | for (let j = 0; j < 5; j++) { 19 | line += '* '; 20 | } 21 | console.log(line); 22 | } 23 | 24 | for (let i = 1; i <= 100; i++) { 25 | if (i % 10 === 0) { 26 | console.log("Breaking at:", i); 27 | break; 28 | } 29 | console.log(i); 30 | } 31 | -------------------------------------------------------------------------------- /Function Exercises: -------------------------------------------------------------------------------- 1 | function greet() { 2 | console.log("Hello, World!"); 3 | } 4 | greet(); // Function invocation 5 | 6 | function add(a, b) { 7 | return a + b; 8 | } 9 | console.log(add(5, 3)); // Outputs 8 10 | 11 | function multiply(a = 1, b = 1) { 12 | return a * b; 13 | } 14 | console.log(multiply(4)); // Outputs 4 15 | console.log(multiply(4, 5)); // Outputs 20 16 | 17 | function showNumber() { 18 | let num = 10; // Local variable 19 | console.log(num); // Accessible here 20 | } 21 | showNumber(); 22 | console.log(num); // Error: num is not defined 23 | 24 | const square = function(num) { 25 | return num * num; 26 | }; 27 | console.log(square(4)); // Outputs 16 28 | 29 | -------------------------------------------------------------------------------- /Introduction to JavaScript Exercises: -------------------------------------------------------------------------------- 1 | console.log("Hello, JavaScript!"); 2 | 3 | let a = 5; 4 | let b = 6; 5 | let c = a + b; 6 | console.log(c); 7 | 8 | let number1 = 42; 9 | let string = "JavaScript"; 10 | let boolean = true; 11 | let nothing = null; 12 | let undefinedVariable; 13 | console.log(typeof number1); // "number" 14 | console.log(typeof string); // "string" 15 | console.log(typeof boolean); // "boolean" 16 | console.log(typeof nothing); // "object" (quirk in JavaScript) 17 | console.log(typeof undefinedVariable); // "undefined" 18 | 19 | let number = 24; 20 | if (number % 2 === 0) { 21 | console.log("The number is even"); 22 | } 23 | 24 | let firstName = "John"; 25 | let lastName = "Doe"; 26 | let fullName = firstName + " " + lastName; 27 | console.log(fullName); 28 | -------------------------------------------------------------------------------- /Control Structures and Data Handling exercises: -------------------------------------------------------------------------------- 1 | console.log("Hello, JavaScript!"); 2 | 3 | let a = 5; 4 | let b = 6; 5 | let c = a + b; 6 | console.log(c); 7 | 8 | let number1 = 42; 9 | let string = "JavaScript"; 10 | let boolean = true; 11 | let nothing = null; 12 | let undefinedVariable; 13 | console.log(typeof number1); // "number" 14 | console.log(typeof string); // "string" 15 | console.log(typeof boolean); // "boolean" 16 | console.log(typeof nothing); // "object" (quirk in JavaScript) 17 | console.log(typeof undefinedVariable); // "undefined" 18 | 19 | let number = 24; 20 | if (number % 2 === 0) { 21 | console.log("The number is even"); 22 | } 23 | 24 | let firstName = "John"; 25 | let lastName = "Doe"; 26 | let fullName = firstName + " " + lastName; 27 | console.log(fullName); 28 | -------------------------------------------------------------------------------- /Advanced Function Exercises: -------------------------------------------------------------------------------- 1 | let displayMessage1 = function() { 2 | console.log("Hello, JavaScript!"); 3 | }; 4 | displayMessage1(); // Invocation of the anonymous function 5 | 6 | let displayMessage2 = () => { 7 | console.log("Hello, JavaScript!"); 8 | }; 9 | displayMessage2(); 10 | 11 | function createCounter() { 12 | let count = 0; 13 | return function() { 14 | count += 1; 15 | console.log(count); 16 | }; 17 | } 18 | let myCounter = createCounter(); 19 | myCounter(); // Outputs 1 20 | myCounter(); // Outputs 2 21 | 22 | (function() { 23 | console.log("IIFE executed!"); 24 | })(); 25 | 26 | let doubleNumbers = numbers => numbers.map(number => number * 2); 27 | console.log(doubleNumbers([1, 2, 3])); // Outputs [2, 4, 6] 28 | -------------------------------------------------------------------------------- /Introduction to JavaScript/introsamples: -------------------------------------------------------------------------------- 1 | let message = "Hello, World!"; // Declares a variable that can be changed 2 | const PI = 3.14159; // Declares a constant whose value cannot be changed 3 | //var age = 30; // Declares a variable with function scope 4 | 5 | let name = "Alice"; 6 | let age = 25; 7 | let isStudent = true; 8 | let address = null; 9 | let definition; 10 | console.log(typeof name); // Outputs "string" 11 | console.log(typeof age); // Outputs "number" 12 | console.log(typeof isStudent); // Outputs "boolean" 13 | console.log(typeof address); // Outputs "object" because `null` is treated as an object 14 | console.log(typeof definition); // Outputs "undefined" 15 | 16 | let score = 85; 17 | if (score >= 90) { 18 | console.log("Excellent"); 19 | } else if (score >= 80) { 20 | console.log("Good"); 21 | } else { 22 | console.log("Needs Improvement"); 23 | } 24 | 25 | let user = "Alice"; 26 | let greeting = "Hello, " + user + "! Welcome to JavaScript."; // Using the + operator 27 | console.log(greeting); 28 | console.log(`Hello, ${user}! Welcome to JavaScript.`); // Using template literals 29 | -------------------------------------------------------------------------------- /Modules Exercsises Code: -------------------------------------------------------------------------------- 1 | // Import the area function from rectangle.js 2 | import { area } from './rectangle.js'; 3 | 4 | // Use the area function 5 | const width = 5; 6 | const height = 10; 7 | const calculatedArea = area(width, height); 8 | console.log('Area:', calculatedArea); 9 | 10 | // main.js 11 | import User from '/User.js'; 12 | // Create a new instance of the User class 13 | const user = new User('John', 30); 14 | // Call the greet method 15 | console.log(user.greet()); // Output: Hello, my name is John and I am 30 years old. 16 | 17 | import { add as addition, subtract as subtraction } from './utilities.js'; 18 | console.log("Addition result:", addition(10, 5)); // Outputs: Addition result: 15 19 | console.log("Subtraction result:", subtraction(10, 5)); // Outputs: Subtraction result: 5 20 | 21 | 22 | ///FIles 23 | // Define and export the area function 24 | export function area(width, height) { 25 | return width * height; 26 | } 27 | 28 | 29 | export function add(x, y) { 30 | return x + y; 31 | } 32 | export function subtract(x, y) { 33 | return x - y; 34 | } 35 | 36 | export default class User { 37 | constructor(name, age) { 38 | this.name = name; 39 | this.age = age; 40 | } 41 | greet() { 42 | return `Hello, my name is ${this.name} and I am ${this.age} years old.`; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Conditional Statements: -------------------------------------------------------------------------------- 1 | let age = 20; 2 | if (age >= 18) { 3 | console.log("You are eligible to vote."); 4 | } else { 5 | console.log("You are not eligible to vote yet."); 6 | } 7 | 8 | let score = 85; 9 | if (score >= 90) { 10 | console.log("A"); 11 | } else if (score >= 80) { 12 | console.log("B"); 13 | } else if (score >= 70) { 14 | console.log("C"); 15 | } else if (score >= 60) { 16 | console.log("D"); 17 | } else { 18 | console.log("F"); 19 | } 20 | 21 | let weather = prompt("Enter the weather (sunny, rainy, snowy):"); 22 | switch (weather.toLowerCase()) { 23 | case "sunny": 24 | console.log("Let's go for a walk!"); 25 | break; 26 | case "rainy": 27 | console.log("Bring an umbrella!"); 28 | break; 29 | case "snowy": 30 | console.log("Time to build a snowman!"); 31 | break; 32 | default: 33 | console.log("That's not a valid weather type!"); 34 | } 35 | 36 | let number = 7; 37 | if (number % 2 === 0) { 38 | console.log("The number is even."); 39 | } else { 40 | console.log("The number is odd."); 41 | } 42 | 43 | let year = 2024; 44 | if (year % 4 === 0) { 45 | if (year % 100 === 0) { 46 | if (year % 400 === 0) { 47 | console.log(`${year} is a leap year.`); 48 | } else { 49 | console.log(`${year} is not a leap year.`); 50 | } 51 | } else { 52 | console.log(`${year} is a leap year.`); 53 | } 54 | } else { 55 | console.log(`${year} is not a leap year.`); 56 | } 57 | -------------------------------------------------------------------------------- /intro exercises: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JavaScript Practice 6 | 7 | 8 | 9 |

Original content

10 | 14 |

First paragraph.

15 |

Second paragraph.

16 | 17 | 21 | 22 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /HTTP methods exercises: -------------------------------------------------------------------------------- 1 | fetch('https://jsonplaceholder.typicode.com/posts/1') 2 | .then(response => response.json()) 3 | .then(data => console.log(data)) 4 | .catch(error => console.error('Failed to fetch:', error)); 5 | 6 | fetch('https://jsonplaceholder.typicode.com/posts', { 7 | method: 'POST', 8 | headers: { 9 | 'Content-Type': 'application/json' 10 | }, 11 | body: JSON.stringify({ 12 | title: 'foo', 13 | body: 'bar', 14 | userId: 1 15 | }) 16 | }) 17 | .then(response => response.json()) 18 | .then(data => console.log('Created:', data)) 19 | .catch(error => console.error('Error posting data:', error)); 20 | 21 | fetch('https://jsonplaceholder.typicode.com/posts/1', { 22 | method: 'PUT', 23 | headers: { 24 | 'Content-Type': 'application/json' 25 | }, 26 | body: JSON.stringify({ 27 | id: 1, 28 | title: 'Updated Title', 29 | body: 'Updated body', 30 | userId: 1 31 | }) 32 | }) 33 | .then(response => response.json()) 34 | .then(data => console.log('Updated:', data)) 35 | .catch(error => console.error('Error updating data:', error)); 36 | 37 | fetch('https://jsonplaceholder.typicode.com/posts/1', { 38 | method: 'PATCH', 39 | headers: { 40 | 'Content-Type': 'application/json' 41 | }, 42 | body: JSON.stringify({ 43 | title: 'Patched Title' 44 | }) 45 | }) 46 | .then(response => response.json()) 47 | .then(data => console.log('Patched:', data)) 48 | .catch(error => console.error('Error patching data:', error)); 49 | 50 | fetch('https://jsonplaceholder.typicode.com/posts/1', { 51 | method: 'DELETE' 52 | }) 53 | .then(() => console.log('Deleted successfully')) 54 | .catch(error => console.error('Error deleting data:', error)); 55 | -------------------------------------------------------------------------------- /Promises Exercises: -------------------------------------------------------------------------------- 1 | let helloPromise = new Promise((resolve, reject) => { 2 | setTimeout(() => { 3 | resolve("Hello, Promise!"); 4 | }, 2000); 5 | }); 6 | helloPromise.then(message => { 7 | console.log(message); // Outputs "Hello, Promise!" after 2 seconds 8 | }); 9 | 10 | let errorPromise = new Promise((resolve, reject) => { 11 | setTimeout(() => { 12 | reject(new Error("Something went wrong!")); 13 | }, 1000); 14 | }); 15 | errorPromise 16 | .then(result => { 17 | console.log(result); 18 | }) 19 | .catch(error => { 20 | console.error(error.message); // Outputs "Something went wrong!" after 1 second 21 | }); 22 | 23 | new Promise(resolve => resolve(1)) 24 | .then(result => { 25 | console.log(result); // Outputs 1 26 | return result * 2; 27 | }) 28 | .then(result => { 29 | console.log(result); // Outputs 2 30 | return result * 2; 31 | }) 32 | .then(result => { 33 | console.log(result); // Outputs 4 34 | return result * 2; 35 | }); 36 | 37 | let promise1 = Promise.resolve(3); 38 | let promise2 = 42; 39 | let promise3 = new Promise((resolve, reject) => { 40 | setTimeout(resolve, 100, 'foo'); 41 | }); 42 | Promise.all([promise1, promise2, promise3]).then(values => { 43 | console.log(values); // Outputs [3, 42, "foo"] 44 | }); 45 | 46 | let promises = [ 47 | Promise.resolve(10), 48 | Promise.reject(new Error("Failure")), 49 | Promise.resolve(30) 50 | ]; 51 | Promise.allSettled(promises).then(results => { 52 | results.forEach((result, index) => { 53 | console.log(`Promise ${index + 1}:`, result.status); 54 | }); 55 | }); 56 | -------------------------------------------------------------------------------- /Features Modern Exercises: -------------------------------------------------------------------------------- 1 | const user = { name: "John", age: 30 }; 2 | // Use template literals to create a formatted string 3 | const greeting = `Hello, my name is ${user.name} and I am ${user.age} years old.`; 4 | console.log(greeting); // Outputs: Hello, my name is John and I am 30 years old. 5 | 6 | const numbers = [1, 2, 3, 4, 5]; 7 | // Traditional function expression 8 | const doubled = numbers.map(function(number) { 9 | return number * 2; 10 | }); 11 | // Converted to arrow function 12 | const doubledArrow = numbers.map(number => number * 2); 13 | console.log(doubledArrow); // Outputs: [2, 4, 6, 8, 10] 14 | 15 | let mutable = "I can change"; 16 | const immutable = "I cannot change"; 17 | console.log(mutable); // Outputs: I can change 18 | console.log(immutable); // Outputs: I cannot change 19 | mutable = "Changed value"; 20 | console.log(mutable); // Outputs: Changed value 21 | // Uncommenting the line below will throw an error 22 | // immutable = "Try changing"; // TypeError: Assignment to constant variable. 23 | 24 | const person = { 25 | firstName: "Jane", 26 | lastName: "Doe", 27 | age: 28, 28 | occupation: "Engineer" 29 | }; 30 | // Destructure the object 31 | const { firstName, lastName, age } = person; 32 | console.log(`${firstName} ${lastName} is ${age} years old.`); // Outputs: Jane Doe is 28 years old. 33 | 34 | async function fetchData() { 35 | try { 36 | const response = await fetch('https://jsonplaceholder.typicode.com/posts/1'); 37 | const data = await response.json(); 38 | console.log(data); 39 | } catch (error) { 40 | console.error("Error fetching data:", error); 41 | } 42 | } 43 | fetchData(); 44 | 45 | -------------------------------------------------------------------------------- /working with APIs exercises: -------------------------------------------------------------------------------- 1 | fetch('https://jsonplaceholder.typicode.com/posts/1') 2 | .then(response => response.json()) 3 | .then(json => console.log(json)) 4 | .catch(error => console.error('Error fetching data:', error)); 5 | 6 | fetch('https://jsonplaceholder.typicode.com/users') 7 | .then(response => response.json()) 8 | .then(users => { 9 | const userList = document.getElementById('userList'); 10 | users.forEach(user => { 11 | const li = document.createElement('li'); 12 | li.textContent = user.name; 13 | userList.appendChild(li); 14 | }); 15 | }) 16 | .catch(error => console.error('Error loading user data:', error)); 17 | 18 | fetch('https://jsonplaceholder.typicode.com/posts/2') 19 | .then(response => { 20 | if (!response.ok) { 21 | throw new Error('Network response was not ok ' + response.statusText); 22 | } 23 | return response.json(); 24 | }) 25 | .then(json => console.log(json)) 26 | .catch(error => console.error('Failed to fetch:', error)); 27 | 28 | fetch('https://jsonplaceholder.typicode.com/posts', { 29 | method: 'POST', 30 | headers: { 31 | 'Content-Type': 'application/json' 32 | }, 33 | body: JSON.stringify({ 34 | title: 'foo', 35 | body: 'bar', 36 | userId: 1 37 | }) 38 | }) 39 | .then(response => response.json()) 40 | .then(json => console.log('Post created:', json)) 41 | .catch(error => console.error('Error posting data:', error)); 42 | 43 | async function fetchPost() { 44 | try { 45 | const response = await fetch('https://jsonplaceholder.typicode.com/posts/3'); 46 | if (!response.ok) { 47 | throw new Error('Failed to fetch: ' + response.statusText); 48 | } 49 | const post = await response.json(); 50 | console.log(post); 51 | } catch (error) { 52 | console.error(error); 53 | } 54 | } 55 | fetchPost(); 56 | 57 | -------------------------------------------------------------------------------- /event handling exercises: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JavaScript Practice 6 | 7 | 8 | 9 | 10 | 11 |
12 | Click the box or the button! 13 | 14 |
15 | Go to Example.com 16 | 17 | 18 | 23 | 24 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /error exercises: -------------------------------------------------------------------------------- 1 | function parseJSON(jsonString) { 2 | try { 3 | let jsonObj = JSON.parse(jsonString); 4 | console.log("JSON parsed successfully:", jsonObj); 5 | } catch (error) { 6 | console.error("Failed to parse JSON:", error); 7 | } 8 | } 9 | parseJSON('{"name":"John", "age":30}'); // Valid JSON 10 | parseJSON('{"name": "John", "age": 30'); // Invalid JSON 11 | function loadData(url) { 12 | try { 13 | // Simulate loading data 14 | console.log(`Loading data from ${url}`); 15 | throw new Error("Network error"); 16 | } catch (error) { 17 | console.error("An error occurred:", error.message); 18 | } finally { 19 | console.log("Cleanup actions completed"); 20 | } 21 | } 22 | loadData("https://api.example.com/data"); 23 | 24 | function verifyAge(age) { 25 | try { 26 | if (age < 18) { 27 | throw new Error("You must be 18 years or older."); 28 | } 29 | console.log("Age verified:", age); 30 | } catch (error) { 31 | console.error("Verification failed:", error.message); 32 | } 33 | } 34 | verifyAge(21); // Passes verification 35 | verifyAge(16); // Fails verification 36 | 37 | function processFile(data) { 38 | try { 39 | console.log("Processing data..."); 40 | try { 41 | let result = JSON.parse(data); 42 | console.log("Data processed:", result); 43 | } catch (parseError) { 44 | throw new Error("Data parsing failed."); 45 | } 46 | } catch (error) { 47 | console.error("Error:", error.message); 48 | } 49 | } 50 | processFile('{"valid": "json"}'); 51 | processFile('invalid json'); 52 | 53 | async function fetchData(url) { 54 | try { 55 | let response = await fetch(url); 56 | let data = await response.json(); 57 | console.log("Data fetched successfully:", data); 58 | } catch (error) { 59 | console.error("Failed to fetch data:", error); 60 | } 61 | } 62 | fetchData("http://127.0.0.1:5500/data.json"); 63 | 64 | -------------------------------------------------------------------------------- /async await exercises: -------------------------------------------------------------------------------- 1 | function delay(ms) { 2 | return new Promise(resolve => setTimeout(resolve, ms)); 3 | } 4 | async function performTask() { 5 | console.log("Task started"); 6 | await delay(2000); // Wait for 2 seconds 7 | console.log("Task completed after a delay"); 8 | } 9 | performTask(); 10 | 11 | async function fetchData(url) { 12 | try { 13 | const response = await fetch(url); 14 | const data = await response.json(); 15 | console.log("Data retrieved:", data); 16 | } catch (error) { 17 | console.error("An error occurred:", error); 18 | } finally { 19 | console.log("Fetch attempt finished."); 20 | } 21 | } 22 | fetchData("https://api.example.com/data"); 23 | 24 | // Simulated asynchronous functions 25 | function doFirstThing() { 26 | return new Promise((resolve) => { 27 | setTimeout(() => { 28 | resolve('First result'); 29 | }, 1000); 30 | }); 31 | } 32 | 33 | function doSecondThing(data) { 34 | return new Promise((resolve) => { 35 | setTimeout(() => { 36 | resolve(`Second result based on ${data}`); 37 | }, 1000); 38 | }); 39 | } 40 | 41 | function doThirdThing(data) { 42 | return new Promise((resolve) => { 43 | setTimeout(() => { 44 | resolve(`Third result based on ${data}`); 45 | }, 1000); 46 | }); 47 | } 48 | 49 | // Async function chaining 50 | async function chainOperations() { 51 | try { 52 | const firstResult = await doFirstThing(); 53 | const secondResult = await doSecondThing(firstResult); 54 | const finalResult = await doThirdThing(secondResult); 55 | console.log("Final result:", finalResult); 56 | } catch (error) { 57 | console.error("An error occurred:", error); 58 | } 59 | } 60 | 61 | chainOperations(); 62 | 63 | 64 | async function processArray(array) { 65 | const promises = array.map(async item => { 66 | await delay(1000); // Simulate a delay 67 | return item * 2; 68 | }); 69 | const results = await Promise.all(promises); 70 | console.log("Processed results:", results); 71 | } 72 | processArray([1, 2, 3, 4]); 73 | 74 | async function getUser(userId) { 75 | const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`); 76 | const user = await response.json(); 77 | console.log("User data:", user); 78 | } 79 | getUser(1); 80 | --------------------------------------------------------------------------------