JavaScript Exercises

JavaScript Exercises

1. Introduction to JavaScript

  • What is JavaScript, and how does it differ from HTML and CSS?
  • Write a JavaScript program that prints "Hello, World!" in the console.
  • Explain the different ways to include JavaScript in an HTML file.
// Example:
console.log("Hello, World!");
            

2. JavaScript Variables

  • What are the three ways to declare variables in JavaScript?
  • What is the difference between var, let, and const?
  • Declare a variable x with a value of 10, then change it to 20.
  • Try changing a const variable and observe what happens.
// Example:
let x = 10;
x = 20; // Works

const PI = 3.14159;
PI = 3.14; // Error: Assignment to constant variable
            

3. JavaScript Data Types

  • What are the two main categories of data types in JavaScript?
  • Identify the data types of the following values:
    let name = "Alice";   
    let age = 25;   
    let isStudent = true;   
    let address = null;   
    let value;   
    let bigNumber = 12345678901234567890n;
                        
  • Create an object person with properties: name, age, and city.
  • Create an array fruits containing "Apple", "Banana", "Mango" and print the second item.
  • Write a function named greet that returns "Hello, welcome!"
// Example:
let person = { name: "John", age: 30, city: "New York" };
console.log(person.name);

let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[1]); // Output: Banana

function greet() {
    return "Hello, welcome!";
}
console.log(greet());
            

4. JavaScript Comments

  • What are the two types of comments in JavaScript?
  • Write a single-line comment explaining the code below:
    let num = 100; // This stores the number 100 in the variable 'num'
                        
  • Write a multi-line comment explaining the difference between let and const.
// Single-line comment
let age = 25; // This variable stores age

/* 
   Multi-line comment
   let allows reassignment, while const does not.
   Example:
   let x = 10; 
   x = 20; // Works
   const y = 30;
   y = 40; // Error
*/
            

5. Challenge Questions

  • Create a variable counter, initialize it with 0, and increase its value by 1 three times.
  • Swap two numbers without using a third variable.
  • Create an object car with properties brand, model, year, then add a new property color.
  • Write a function that takes a number as input and returns "Even" if the number is even and "Odd" if it is odd.
// Example:
let counter = 0;
counter++;
counter++;
counter++;
console.log(counter); // Output: 3

// Swap two numbers
let a = 5, b = 10;
[a, b] = [b, a];
console.log(a, b); // Output: 10 5

// Even or Odd function
function checkEvenOdd(num) {
    return num % 2 === 0 ? "Even" : "Odd";
}
console.log(checkEvenOdd(7)); // Output: Odd
            

Practice these exercises to strengthen your JavaScript fundamentals! 🚀