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:
String: "Hello"
Number: 42
Boolean: true / false
Undefined: Variable not initialized
Null: Explicitly nothing
Symbol: Unique values (advanced use case)
Non-Primitive:
Objects: Key-value pairs
Arrays: Ordered list of elements
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
Arithmetic:+, -, *, /,
%
Comparison:>, <, >=,
<=, ==, ===
Logical:&&, ||, !
Assignment:=, +=, -=, *=
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
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");
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.
let a = 5, b = 10;
a = a + b; // a now becomes 15
b = a - b; // b becomes 5
a = a - b; // a becomes 10
console.log(a, b); // Outputs: 10, 5
Create a program to calculate the area of a rectangle given its length and width.
Write a program to check whether a given number is even or odd.
function isEven(num) {
return num % 2 === 0;
}
console.log(isEven(4)); // Outputs: true
Create a program to find the largest of three numbers.
function findLargest(a, b, c) {
return Math.max(a, b, c);
}
console.log(findLargest(1, 5, 3)); // Outputs: 5
3. Loops
Print all numbers from 1 to 100. Replace:
Multiples of 3 with "Fizz"
Multiples of 5 with "Buzz"
Multiples of both with "FizzBuzz"
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
}
Write a program to generate the Fibonacci sequence up to n terms.
function fibonacci(n) {
let fib = [0, 1];
for (let i = 2; i < n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib;
}
console.log(fibonacci(10)); // Outputs: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
4. Strings
Reverse a string without using built-in methods.
function reverseString(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
console.log(reverseString("hello")); // Outputs: "olleh"
Create a to-do list app where users can add items, mark items as complete, and delete items.
let todos = [];
function addTodo(todo) {
todos.push({ text: todo, completed: false });
}
function toggleComplete(index) {
todos[index].completed = !todos[index].completed;
}
function deleteTodo(index) {
todos.splice(index, 1);
}
5. Asynchronous Programming
Fetch data from an API and log the response to the console.
Create a simple calculator app with a fully interactive UI for addition, subtraction, multiplication,
and
division.
function calculate(a, b, operation) {
switch (operation) {
case "add":
return a + b;
case "subtract":
return a - b;
case "multiply":
return a * b;
case "divide":
return b !== 0 ? a / b : "Error: Cannot divide by zero";
}
}
console.log(calculate(10, 5, "add")); // Outputs: 15