JavaScript Guide for Beginners

1. Setting Up JavaScript

How to Run JavaScript:

Example HTML with JavaScript:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Basics</title>
</head>
<body>
    <h1>Hello, JavaScript!</h1>
    <script>
        console.log("Welcome to JavaScript!");
    </script>
</body>
</html>

2. Variables and Constants

Examples:

let username = "Alice";
const age = 25;
// age = 26; // Error: const variables cannot be reassigned
var isAdmin = true;

console.log(username, age, isAdmin);

3. Data Types

Primitive Types:

Non-Primitive:

Example:

let name = "John"; // String
let age = 30;      // Number
let isLoggedIn = true; // Boolean
let user = null;   // Null
let items = ["apple", "banana", "cherry"]; // Array
let person = { name: "Alice", age: 25 }; // Object

console.log(name, age, isLoggedIn, user, items, person);

4. Operators

Example:

let a = 10, b = 20;
console.log(a + b); // 30
console.log(a > b); // false
console.log(true && false); // false

5. Conditional Statements

If-Else:

let score = 85;

if (score >= 90) {
    console.log("Excellent");
} else if (score >= 50) {
    console.log("Good");
} else {
    console.log("Fail");
}

Switch:

let grade = "A";

switch (grade) {
    case "A":
        console.log("Great job!");
        break;
    case "B":
        console.log("Good effort!");
        break;
    default:
        console.log("Keep trying!");
}

6. Loops

For Loop:

for (let i = 1; i <= 5; i++) {
    console.log("Count:", i);
}

While Loop:

let count = 0;
while (count < 3) {
    console.log("Count:", count);
    count++;
}

For...of (Arrays):

let fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
    console.log(fruit);
}

For...in (Objects):

let person = { name: "Alice", age: 25 };
for (let key in person) {
    console.log(key, ":", person[key]);
}

7. Functions

Basic Functions:

function greet(name) {
    return `Hello, ${name}!`;
}
console.log(greet("John"));

Arrow Functions:

const add = (a, b) => a + b;
console.log(add(5, 10)); // 15

Default Parameters:

function sayHi(name = "Guest") {
    console.log(`Hi, ${name}!`);
}
sayHi(); // Hi, Guest!

8. Arrays

Methods to Know:

Example:

let numbers = [1, 2, 3, 4];
numbers.push(5); // Add at end
numbers.pop();   // Remove last element
numbers = numbers.filter(n => n > 2); // [3, 4]

console.log(numbers);

9. Objects

Example:

let car = {
    brand: "Tesla",
    model : "Model X",
    year: 2023,
    getDetails() {
        return `${this.brand} ${this.model}, Year: ${this.year}`;
    }
};
console.log(car.getDetails());

10. DOM Manipulation

Select Elements:

let title = document.getElementById("title");
let buttons = document.querySelectorAll(".btn");

Modify Content:

title.textContent = "Updated Title!";

Event Handling:

document.getElementById("btn").addEventListener("click", () => {
    alert("Button clicked!");
});

11. ES6 Features

Template Literals:

let name = "Alice";
console.log(`Hello, ${name}!`);

Destructuring:

let user = { name: "John", age: 30 };
let { name, age } = user;
console.log(name, age);

Spread/Rest Operator:

let arr = [1, 2, 3];
let newArr = [...arr, 4, 5];
console.log(newArr);

12. Asynchronous JavaScript

Callback Example:

setTimeout(() => {
    console.log("This runs after 2 seconds");
}, 2000);

Promise Example:

fetch("https://jsonplaceholder.typicode.com/posts")
    .then(response => response.json())
    .then(data => console.log(data));

Async/Await:

async function fetchData() {
    let response = await fetch("https://jsonplaceholder.typicode.com/posts");
    let data = await response.json();
    console.log(data);
}
fetchData();

JavaScript Practice Challenges

These programming exercises are organized by difficulty levels, helping you solidify your JavaScript knowledge and progress step by step.

Beginner Level

1. Variables and Data Types

Write a program to swap two numbers without using a third variable.

Create a program to calculate the area of a rectangle given its length and width.

2. Control Flow

Write a program to check whether a given number is even or odd.

Create a program to find the largest of three numbers.

3. Loops

Print all numbers from 1 to 100. Replace:

Write a program to generate the Fibonacci sequence up to n terms.

4. Strings

Reverse a string without using built-in methods.

Count the number of vowels in a given string.

5. Arrays

Write a program to find the maximum and minimum values in an array.

Remove duplicate values from an array.

Intermediate Level

1. Functions and Recursion

Create a function to check if a string is a palindrome.

Write a recursive function to calculate the factorial of a number.

2. Objects

Create an object representing a student and add a method to calculate the average grade.

Merge two objects and handle cases where they have conflicting keys.

3. Higher-Order Functions

Use map() to create a new array with all elements squared.

Use filter() to extract numbers greater than 50 from an array.

4. DOM Manipulation

Build a counter app with three buttons to increment, decrement, and reset the counter.

Create a to-do list app where users can add items, mark items as complete, and delete items.

5. Asynchronous Programming

Fetch data from an API and log the response to the console.

Implement a countdown timer using setTimeout.

Advanced Level

1. Closures

Create a function that keeps track of how many times it has been called and returns the count.

Write a curried function that allows adding numbers one at a time.

2. Promises and Async/Await

Write a program to fetch data from multiple APIs simultaneously using Promise.all.

Simulate an API call with a delay using setTimeout and Promise.

3. Error Handling

Create a function to perform division between two numbers and handle divide-by-zero errors gracefully.

4. Data Structures

Implement a stack or queue using JavaScript arrays.

Write a function to sort an array of objects by a specific property (e.g., age).

5. Advanced DOM Manipulation

Build a dynamic table from a JSON array, where users can sort columns and search rows.

Create a simple calculator app with a fully interactive UI for addition, subtraction, multiplication, and division.