Create Simple JavaScript Programs
Learning Objectives
- Understand JavaScript fundamentals
- Add interactivity to web pages
- Manipulate page elements dynamically
- Handle user interactions
Assignment Overview
In this assignment, you will create several simple JavaScript programs to demonstrate your understanding of fundamental JavaScript concepts. You'll write code that manipulates variables, uses control structures, implements functions, and interacts with the Document Object Model (DOM). These exercises will help reinforce the JavaScript basics covered in our session and provide practical examples of how JavaScript can be used to add interactivity to web pages.
George Polya's 4-Step Problem Solving Method
Step 1: Understand the Problem
We need to create simple JavaScript programs that demonstrate:
- Basic syntax and variable usage
- Operators and expressions
- Control structures (conditionals and loops)
- Functions and scope
- Basic DOM manipulation
Each program should be self-contained, demonstrate a specific concept, and be well-commented to explain how it works.
Step 2: Devise a Plan
We'll create several JavaScript programs, each focusing on a specific concept:
- Program 1: Variables and Basic Operations
- Declare variables of different types
- Perform basic arithmetic operations
- Display results using console.log()
- Program 2: Conditional Statements
- Create a simple age checker
- Use if/else statements to generate different messages
- Display results using alerts or console.log()
- Program 3: Loops
- Create a simple counter using a for loop
- Implement a while loop for a guessing game
- Display results
- Program 4: Functions
- Create functions to calculate area and perimeter
- Implement a function with return values
- Use function parameters
- Program 5: DOM Manipulation
- Create HTML elements
- Change content and styles using JavaScript
- Respond to user events
Step 3: Execute the Plan
Let's implement each program step by step:
Solution: Creating Simple JavaScript Programs
Program 1: Variables and Basic Operations
File: variables_and_operations.html
This program demonstrates different variable types in JavaScript and basic arithmetic operations. It shows how to declare variables, assign values to them, and perform calculations.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Variables and Basic Operations</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 20px;
}
.result {
background-color: #f4f4f4;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>JavaScript Variables and Basic Operations</h1>
<div id="output"></div>
<script>
// Get reference to the output div
const outputDiv = document.getElementById('output');
// Function to display results in the output div
function displayResult(description, result) {
const resultElement = document.createElement('div');
resultElement.className = 'result';
resultElement.innerHTML = `${description}: ${result}`;
outputDiv.appendChild(resultElement);
// Also log to console for debugging
console.log(`${description}: ${result}`);
}
// PART 1: VARIABLE DECLARATIONS
// String variables
let firstName = "John";
let lastName = "Doe";
// Number variables
let age = 25;
let temperature = 98.6;
// Boolean variables
let isStudent = true;
let hasJob = false;
// Array variable
let hobbies = ["reading", "coding", "hiking"];
// Object variable
let person = {
name: "John",
age: 25,
city: "New York"
};
// Display variable values
displayResult("First Name (String)", firstName);
displayResult("Last Name (String)", lastName);
displayResult("Age (Number - Integer)", age);
displayResult("Temperature (Number - Float)", temperature);
displayResult("Is Student (Boolean)", isStudent);
displayResult("Has Job (Boolean)", hasJob);
displayResult("Hobbies (Array)", hobbies.join(", "));
displayResult("Person (Object)", JSON.stringify(person));
// PART 2: BASIC OPERATIONS
// String operations
let fullName = firstName + " " + lastName;
displayResult("Full Name (String Concatenation)", fullName);
// String template literals (ES6 feature)
let greeting = `Hello, my name is ${firstName} ${lastName}`;
displayResult("Greeting (Template Literal)", greeting);
// Arithmetic operations
let sum = 10 + 5;
let difference = 20 - 7;
let product = 6 * 8;
let quotient = 50 / 10;
let remainder = 17 % 3;
displayResult("Sum (10 + 5)", sum);
displayResult("Difference (20 - 7)", difference);
displayResult("Product (6 * 8)", product);
displayResult("Quotient (50 / 10)", quotient);
displayResult("Remainder (17 % 3)", remainder);
// Increment and decrement
let counter = 5;
let postIncrement = counter++; // Assigns first, then increments
displayResult("Post-increment (counter++)", postIncrement);
displayResult("Counter after post-increment", counter);
counter = 5; // Reset counter
let preIncrement = ++counter; // Increments first, then assigns
displayResult("Pre-increment (++counter)", preIncrement);
displayResult("Counter after pre-increment", counter);
// Compound assignment operators
let number = 10;
number += 5; // Same as: number = number + 5
displayResult("Compound addition (10 += 5)", number);
number = 10; // Reset number
number *= 3; // Same as: number = number * 3
displayResult("Compound multiplication (10 *= 3)", number);
// Type conversion
let numString = "42";
let num = Number(numString);
displayResult("String '42' converted to Number", num);
let numToString = 123;
let str = String(numToString);
displayResult("Number 123 converted to String", str);
let booleanValue = Boolean(1);
displayResult("Number 1 converted to Boolean", booleanValue);
</script>
</body>
</html>
Explanation:
- We create variables of different types: strings, numbers, booleans, arrays, and objects.
- We demonstrate string concatenation using the + operator and template literals.
- We show basic arithmetic operations: addition, subtraction, multiplication, division, and modulus.
- We explain the difference between pre-increment (++counter) and post-increment (counter++).
- We demonstrate compound assignment operators (+=, *=).
- We show how to convert between different data types using Number(), String(), and Boolean().
Program 2: Conditional Statements
File: conditional_statements.html
This program demonstrates different types of conditional statements in JavaScript. It shows how to use if/else statements, else if chains, and the ternary operator to make decisions in code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Conditional Statements</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 20px;
}
.result {
background-color: #f4f4f4;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
}
.section {
margin-top: 30px;
border-top: 1px solid #ddd;
padding-top: 20px;
}
input, button {
padding: 8px;
margin: 5px 0;
}
</style>
</head>
<body>
<h1>JavaScript Conditional Statements</h1>
<!-- Age Checker -->
<div class="section">
<h2>Age Checker</h2>
<p>Enter your age to see if you're eligible for different activities:</p>
<input type="number" id="ageInput" placeholder="Enter your age">
<button id="checkAgeBtn">Check Age</button>
<div id="ageResult" class="result">Results will appear here...</div>
</div>
<!-- Grade Calculator -->
<div class="section">
<h2>Grade Calculator</h2>
<p>Enter your score (0-100) to see your grade:</p>
<input type="number" id="scoreInput" placeholder="Enter your score" min="0" max="100">
<button id="calculateGradeBtn">Calculate Grade</button>
<div id="gradeResult" class="result">Results will appear here...</div>
</div>
<!-- Day of Week -->
<div class="section">
<h2>Day of the Week</h2>
<p>Enter a number (1-7) to see what day of the week it is:</p>
<input type="number" id="dayInput" placeholder="Enter day (1-7)" min="1" max="7">
<button id="checkDayBtn">Check Day</button>
<div id="dayResult" class="result">Results will appear here...</div>
</div>
<!-- Weather Recommendation -->
<div class="section">
<h2>Weather Recommendation</h2>
<p>Enter the temperature to get a clothing recommendation:</p>
<input type="number" id="tempInput" placeholder="Enter temperature (°F)">
<button id="getTempRecommendationBtn">Get Recommendation</button>
<div id="tempResult" class="result">Results will appear here...</div>
</div>
<script>
// Age Checker
document.getElementById('checkAgeBtn').addEventListener('click', function() {
const age = parseInt(document.getElementById('ageInput').value);
const resultElement = document.getElementById('ageResult');
// Check if input is valid
if (isNaN(age)) {
resultElement.textContent = "Please enter a valid age.";
return;
}
let message = `Your age is ${age}. `;
// Using if-else statements to check age eligibility
if (age < 0) {
message += "Invalid age. Please enter a positive number.";
} else if (age < 13) {
message += "You're a child. You need parental guidance for many activities.";
} else if (age < 18) {
message += "You're a teenager. You can watch PG-13 movies, but cannot vote yet.";
} else if (age < 21) {
message += "You're a young adult. You can vote, but cannot purchase alcohol in the US.";
} else if (age < 65) {
message += "You're an adult. You have full legal rights and responsibilities.";
} else {
message += "You're a senior citizen. You may be eligible for retirement benefits.";
}
resultElement.textContent = message;
});
// Grade Calculator
document.getElementById('calculateGradeBtn').addEventListener('click', function() {
const score = parseInt(document.getElementById('scoreInput').value);
const resultElement = document.getElementById('gradeResult');
// Check if input is valid
if (isNaN(score) || score < 0 || score > 100) {
resultElement.textContent = "Please enter a valid score between 0 and 100.";
return;
}
let grade;
// Using else-if ladder for grade calculation
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
} else {
grade = 'F';
}
// Using ternary operator for pass/fail status
const status = score >= 60 ? "Passing" : "Failing";
resultElement.textContent = `Your score of ${score} gives you a grade of ${grade}. This is a ${status} grade.`;
});
// Day of Week
document.getElementById('checkDayBtn').addEventListener('click', function() {
const dayNum = parseInt(document.getElementById('dayInput').value);
const resultElement = document.getElementById('dayResult');
// Check if input is valid
if (isNaN(dayNum) || dayNum < 1 || dayNum > 7) {
resultElement.textContent = "Please enter a number between 1 and 7.";
return;
}
let day;
// Using switch statement for day of week
switch (dayNum) {
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
case 7:
day = "Sunday";
break;
default:
day = "Invalid day";
}
// Using logical AND for weekend check
const isWeekend = (dayNum === 6 || dayNum === 7);
const dayType = isWeekend ? "weekend" : "weekday";
resultElement.textContent = `Day ${dayNum} is ${day}. It's a ${dayType}.`;
});
// Weather Recommendation
document.getElementById('getTempRecommendationBtn').addEventListener('click', function() {
const temp = parseInt(document.getElementById('tempInput').value);
const resultElement = document.getElementById('tempResult');
// Check if input is valid
if (isNaN(temp)) {
resultElement.textContent = "Please enter a valid temperature.";
return;
}
let recommendation;
// Nested if statements for clothing recommendation
if (temp < 32) {
recommendation = "It's freezing! Wear a heavy winter coat, hat, scarf, and gloves.";
} else if (temp < 50) {
recommendation = "It's cold. A warm jacket is recommended.";
if (temp < 40) {
recommendation += " You might also need a hat and gloves.";
}
} else if (temp < 70) {
recommendation = "It's cool. A light jacket or sweater should be fine.";
if (temp >= 60) {
recommendation += " You might be comfortable with just long sleeves.";
}
} else if (temp < 85) {
recommendation = "It's warm. Short sleeves are appropriate.";
} else {
recommendation = "It's hot! Wear light, breathable clothing.";
if (temp > 95) {
recommendation += " Stay hydrated and try to stay in the shade or indoors.";
}
}
resultElement.textContent = `Temperature: ${temp}°F. ${recommendation}`;
});
</script>
</body>
</html>
Explanation:
- We implement four different interactive examples of conditional statements.
- The Age Checker uses a simple if-else if-else ladder to categorize users based on age.
- The Grade Calculator converts numerical scores to letter grades using conditionals.
- The Day of Week example demonstrates the switch statement, an alternative to if-else for multi-choice scenarios.
- The Weather Recommendation shows nested if statements, where additional conditions are checked inside other conditions.
- We also demonstrate the ternary operator (?:) as a shorthand for simple if-else conditions.
Program 3: Loops
File: loops.html
This program demonstrates different types of loops in JavaScript. It shows how to use for loops, while loops, do-while loops, and for...of loops to iterate through data and perform repetitive tasks.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Loops</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 20px;
}
.section {
margin-bottom: 30px;
padding: 15px;
background-color: #f9f9f9;
border-radius: 5px;
}
.output {
background-color: #f4f4f4;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
white-space: pre-wrap;
font-family: monospace;
}
input, button {
padding: 8px;
margin: 5px 0;
}
table {
border-collapse: collapse;
width: 100%;
margin-top: 10px;
}
table, th, td {
border: 1px solid #ddd;
}
th, td {
padding: 10px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h1>JavaScript Loops</h1>
<!-- For Loop - Number Counter -->
<div class="section">
<h2>For Loop - Number Counter</h2>
<p>Generate a sequence of numbers from start to end with a specified step:</p>
<div>
<input type="number" id="startNum" placeholder="Start" value="1">
<input type="number" id="endNum" placeholder="End" value="10">
<input type="number" id="stepNum" placeholder="Step" value="1">
<button id="generateSequenceBtn">Generate Sequence</button>
</div>
<div id="sequenceOutput" class="output">Results will appear here...</div>
</div>
<!-- While Loop - Guess the Number Game -->
<div class="section">
<h2>While Loop - Guess the Number Game</h2>
<p>The computer will try to guess a number between 1 and 100.</p>
<div>
<input type="number" id="targetNumber" placeholder="Enter a target number (1-100)" min="1" max="100" value="50">
<button id="startGuessingBtn">Start Guessing</button>
</div>
<div id="guessOutput" class="output">Results will appear here...</div>
</div>
<!-- Do-While Loop - Password Validator -->
<div class="section">
<h2>Do-While Loop - Password Validator</h2>
<p>Enter passwords until you create a valid one (at least 8 characters with a number).</p>
<div>
<input type="text" id="passwordInput" placeholder="Enter a password">
<button id="validatePasswordBtn">Validate Password</button>
</div>
<div id="passwordOutput" class="output">Results will appear here...</div>
</div>
<!-- For...of Loop - Array Processing -->
<div class="section">
<h2>For...of Loop - Array Processing</h2>
<p>Enter comma-separated items to process:</p>
<div>
<input type="text" id="arrayItems" placeholder="Enter items (e.g., apple, banana, orange)" value="apple, banana, orange, grape, kiwi">
<button id="processArrayBtn">Process Array</button>
</div>
<div id="arrayOutput" class="output">Results will appear here...</div>
</div>
<!-- Nested Loops - Multiplication Table -->
<div class="section">
<h2>Nested Loops - Multiplication Table</h2>
<p>Generate a multiplication table:</p>
<div>
<input type="number" id="tableSize" placeholder="Size of table" value="10" min="1" max="20">
<button id="generateTableBtn">Generate Table</button>
</div>
<div id="tableOutput">Results will appear here...</div>
</div>
<script>
// For Loop - Number Counter
document.getElementById('generateSequenceBtn').addEventListener('click', function() {
const start = parseInt(document.getElementById('startNum').value);
const end = parseInt(document.getElementById('endNum').value);
const step = parseInt(document.getElementById('stepNum').value);
const outputElement = document.getElementById('sequenceOutput');
// Input validation
if (isNaN(start) || isNaN(end) || isNaN(step)) {
outputElement.textContent = "Please enter valid numbers.";
return;
}
if (step <= 0) {
outputElement.textContent = "Step must be a positive number.";
return;
}
let result = "";
let count = 0;
// For loop to generate sequence
for (let i = start; i <= end; i += step) {
result += i + " ";
count++;
// Add line break every 10 numbers for readability
if (count % 10 === 0) {
result += "\n";
}
}
outputElement.textContent = result || "No numbers in sequence.";
});
// While Loop - Guess the Number Game
document.getElementById('startGuessingBtn').addEventListener('click', function() {
const targetNumber = parseInt(document.getElementById('targetNumber').value);
const outputElement = document.getElementById('guessOutput');
// Input validation
if (isNaN(targetNumber) || targetNumber < 1 || targetNumber > 100) {
outputElement.textContent = "Please enter a valid number between 1 and 100.";
return;
}
outputElement.textContent = "Starting guessing process...\n";
// Binary search algorithm
let min = 1;
let max = 100;
let guess;
let attempts = 0;
// While loop for guessing
while (min <= max) {
guess = Math.floor((min + max) / 2);
attempts++;
outputElement.textContent += `Attempt ${attempts}: Computer guesses ${guess}\n`;
if (guess === targetNumber) {
outputElement.textContent += `Found it! The number is ${guess}. It took ${attempts} attempts.`;
break;
} else if (guess < targetNumber) {
outputElement.textContent += `Too low. Trying higher...\n`;
min = guess + 1;
} else {
outputElement.textContent += `Too high. Trying lower...\n`;
max = guess - 1;
}
// Safety check to prevent infinite loops
if (attempts >= 10) {
outputElement.textContent += "Maximum attempts reached.";
break;
}
}
});
// Do-While Loop - Password Validator
document.getElementById('validatePasswordBtn').addEventListener('click', function() {
const passwordInput = document.getElementById('passwordInput');
const outputElement = document.getElementById('passwordOutput');
let password = passwordInput.value;
let isValid = false;
let attempts = 0;
let result = "";
// Do-while loop for password validation
do {
attempts++;
result += `Attempt ${attempts}: Testing password "${password}"\n`;
// Check password length
if (password.length < 8) {
result += "✘ Password is too short. It must be at least 8 characters.\n";
} else {
result += "✓ Password length is good.\n";
}
// Check if password contains a number
if (!/\d/.test(password)) {
result += "✘ Password must contain at least one number.\n";
} else {
result += "✓ Password contains a number.\n";
}
// Determine if password is valid
isValid = password.length >= 8 && /\d/.test(password);
if (isValid) {
result += `Success! Password "${password}" is valid.\n`;
} else {
result += "Please try another password.\n\n";
// In a real application, we would prompt for a new password
// For demonstration, we'll modify the password to make it valid
if (attempts === 1) {
// Simulate user entering a new password
if (password.length < 8) {
password = password + "123"; // Add digits to make it longer
} else {
password = password + "1"; // Add a digit
}
}
}
// Prevent infinite loops in demonstration
if (attempts >= 2) {
break;
}
} while (!isValid);
outputElement.textContent = result;
// Update the input field with the final password
passwordInput.value = password;
});
// For...of Loop - Array Processing
document.getElementById('processArrayBtn').addEventListener('click', function() {
const itemsInput = document.getElementById('arrayItems').value;
const outputElement = document.getElementById('arrayOutput');
// Parse input into an array
const items = itemsInput.split(',').map(item => item.trim()).filter(item => item);
if (items.length === 0) {
outputElement.textContent = "Please enter at least one item.";
return;
}
let result = `Processing ${items.length} items:\n\n`;
// For...of loop to process array items
for (const item of items) {
result += `Item: ${item}\n`;
result += `- Length: ${item.length} characters\n`;
result += `- Uppercase: ${item.toUpperCase()}\n`;
result += `- First letter: ${item[0]}\n\n`;
}
// Additional array statistics
const lengthSum = items.reduce((sum, item) => sum + item.length, 0);
const averageLength = (lengthSum / items.length).toFixed(2);
result += `Array Statistics:\n`;
result += `- Total items: ${items.length}\n`;
result += `- Average item length: ${averageLength} characters\n`;
result += `- Shortest item: ${items.reduce((min, item) => item.length < min.length ? item : min, items[0])}\n`;
result += `- Longest item: ${items.reduce((max, item) => item.length > max.length ? item : max, items[0])}\n`;
outputElement.textContent = result;
});
// Nested Loops - Multiplication Table
document.getElementById('generateTableBtn').addEventListener('click', function() {
const size = parseInt(document.getElementById('tableSize').value);
const outputElement = document.getElementById('tableOutput');
// Input validation
if (isNaN(size) || size < 1 || size > 20) {
outputElement.textContent = "Please enter a valid size between 1 and 20.";
return;
}
// Create table element
const table = document.createElement('table');
const headerRow = document.createElement('tr');
// Add empty cell in top-left corner
const cornerCell = document.createElement('th');
headerRow.appendChild(cornerCell);
// Create header row
for (let i = 1; i <= size; i++) {
const headerCell = document.createElement('th');
headerCell.textContent = i;
headerRow.appendChild(headerCell);
}
table.appendChild(headerRow);
// Nested loops to create table rows and cells
for (let i = 1; i <= size; i++) {
const row = document.createElement('tr');
// Create row header
const rowHeader = document.createElement('th');
rowHeader.textContent = i;
row.appendChild(rowHeader);
// Create data cells with multiplication results
for (let j = 1; j <= size; j++) {
const cell = document.createElement('td');
cell.textContent = i * j;
row.appendChild(cell);
}
table.appendChild(row);
}
// Clear previous content and append table
outputElement.innerHTML = '';
outputElement.appendChild(table);
});
</script>
</body>
</html>
Explanation:
- We demonstrate five different loop types with practical examples:
- The for loop is used to generate a sequence of numbers with a specified step.
- The while loop is used in a number guessing game that uses a binary search algorithm.
- The do-while loop validates passwords, ensuring at least one iteration even if the condition is initially false.
- The for...of loop processes each item in an array of strings, demonstrating how to work with collections.
- Nested loops create a multiplication table, showing how loops can be used inside other loops.
Program 4: Functions
File: functions.html
This program demonstrates different types of functions in JavaScript. It shows how to declare functions, use parameters and return values, and create both regular and arrow functions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Functions</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 20px;
}
.section {
margin-bottom: 30px;
padding: 15px;
background-color: #f9f9f9;
border-radius: 5px;
}
.output {
background-color: #f4f4f4;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
font-family: monospace;
}
input, button {
padding: 8px;
margin: 5px 0;
}
.form-row {
margin-bottom: 10px;
}
</style>
</head>
<body>
<h1>JavaScript Functions</h1>
<!-- Basic Functions -->
<div class="section">
<h2>Basic Functions</h2>
<p>Simple function demonstration:</p>
<button id="greetBtn">Greet</button>
<div id="greetOutput" class="output">Results will appear here...</div>
</div>
<!-- Functions with Parameters -->
<div class="section">
<h2>Functions with Parameters</h2>
<p>Area and perimeter calculator:</p>
<div class="form-row">
<label for="shapeSelect">Shape:</label>
<select id="shapeSelect">
<option value="rectangle">Rectangle</option>
<option value="circle">Circle</option>
<option value="triangle">Triangle</option>
</select>
</div>
<div id="rectangleParams">
<div class="form-row">
<input type="number" id="rectWidth" placeholder="Width" value="5">
<input type="number" id="rectHeight" placeholder="Height" value="3">
</div>
</div>
<div id="circleParams" style="display: none;">
<div class="form-row">
<input type="number" id="circleRadius" placeholder="Radius" value="4">
</div>
</div>
<div id="triangleParams" style="display: none;">
<div class="form-row">
<input type="number" id="triSideA" placeholder="Side A" value="3">
<input type="number" id="triSideB" placeholder="Side B" value="4">
<input type="number" id="triSideC" placeholder="Side C" value="5">
</div>
</div>
<button id="calculateBtn">Calculate</button>
<div id="calcOutput" class="output">Results will appear here...</div>
</div>
<!-- Return Values and Function Expressions -->
<div class="section">
<h2>Return Values and Function Expressions</h2>
<p>Temperature converter:</p>
<div class="form-row">
<input type="number" id="tempInput" placeholder="Temperature" value="32">
<select id="conversionType">
<option value="CtoF">Celsius to Fahrenheit</option>
<option value="FtoC">Fahrenheit to Celsius</option>
</select>
</div>
<button id="convertBtn">Convert</button>
<div id="tempOutput" class="output">Results will appear here...</div>
</div>
<!-- Arrow Functions and Higher-Order Functions -->
<div class="section">
<h2>Arrow Functions and Higher-Order Functions</h2>
<p>Array processing with arrow functions:</p>
<div class="form-row">
<input type="text" id="numberListInput" placeholder="Enter numbers separated by commas" value="5, 10, 15, 20, 25">
</div>
<div class="form-row">
<select id="arrayOperation">
<option value="double">Double each number</option>
<option value="square">Square each number</option>
<option value="filter">Filter even numbers</option>
<option value="sum">Calculate sum</option>
<option value="all">Perform all operations</option>
</select>
</div>
<button id="processArrayBtn">Process Array</button>
<div id="arrayOutput" class="output">Results will appear here...</div>
</div>
<script>
// Show/hide shape parameters based on selection
document.getElementById('shapeSelect').addEventListener('change', function() {
const shape = this.value;
const rectangleParams = document.getElementById('rectangleParams');
const circleParams = document.getElementById('circleParams');
const triangleParams = document.getElementById('triangleParams');
rectangleParams.style.display = 'none';
circleParams.style.display = 'none';
triangleParams.style.display = 'none';
switch(shape) {
case 'rectangle':
rectangleParams.style.display = 'block';
break;
case 'circle':
circleParams.style.display = 'block';
break;
case 'triangle':
triangleParams.style.display = 'block';
break;
}
});
// Basic Functions
document.getElementById('greetBtn').addEventListener('click', function() {
const outputElement = document.getElementById('greetOutput');
// Function declaration
function greet() {
return "Hello, World!";
}
// Function with parameters
function greetPerson(name) {
return `Hello, ${name}!`;
}
// Function with default parameters (ES6 feature)
function greetPersonWithTime(name = "World", time = "day") {
return `Good ${time}, ${name}!`;
}
// Call the functions
const result1 = greet();
const result2 = greetPerson("JavaScript");
const result3 = greetPersonWithTime("Learner", "evening");
const result4 = greetPersonWithTime(); // Using default parameters
// Display results
outputElement.innerHTML = `${result1}
${result2}
${result3}
${result4}`;
});
// Functions with Parameters - Shape Calculator
document.getElementById('calculateBtn').addEventListener('click', function() {
const shape = document.getElementById('shapeSelect').value;
const outputElement = document.getElementById('calcOutput');
let area, perimeter;
// Rectangle functions
function rectangleArea(width, height) {
return width * height;
}
function rectanglePerimeter(width, height) {
return 2 * (width + height);
}
// Circle functions
function circleArea(radius) {
return Math.PI * radius * radius;
}
function circleCircumference(radius) {
return 2 * Math.PI * radius;
}
// Triangle functions
function triangleArea(a, b, c) {
// Heron's formula
const s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
function trianglePerimeter(a, b, c) {
return a + b + c;
}
// Calculate based on shape
switch(shape) {
case 'rectangle':
const width = parseFloat(document.getElementById('rectWidth').value);
const height = parseFloat(document.getElementById('rectHeight').value);
if (isNaN(width) || isNaN(height) || width <= 0 || height <= 0) {
outputElement.textContent = "Please enter valid positive numbers for width and height.";
return;
}
area = rectangleArea(width, height);
perimeter = rectanglePerimeter(width, height);
outputElement.innerHTML = `Rectangle:
Width: ${width}, Height: ${height}
Area: ${area.toFixed(2)} square units
Perimeter: ${perimeter.toFixed(2)} units`;
break;
case 'circle':
const radius = parseFloat(document.getElementById('circleRadius').value);
if (isNaN(radius) || radius <= 0) {
outputElement.textContent = "Please enter a valid positive radius.";
return;
}
area = circleArea(radius);
perimeter = circleCircumference(radius); // Technically circumference for circles
outputElement.innerHTML = `Circle:
Radius: ${radius}
Area: ${area.toFixed(2)} square units
Circumference: ${perimeter.toFixed(2)} units`;
break;
case 'triangle':
const sideA = parseFloat(document.getElementById('triSideA').value);
const sideB = parseFloat(document.getElementById('triSideB').value);
const sideC = parseFloat(document.getElementById('triSideC').value);
if (isNaN(sideA) || isNaN(sideB) || isNaN(sideC) ||
sideA <= 0 || sideB <= 0 || sideC <= 0) {
outputElement.textContent = "Please enter valid positive numbers for all sides.";
return;
}
// Check if triangle is valid (sum of any two sides must be greater than the third side)
if (sideA + sideB <= sideC || sideA + sideC <= sideB || sideB + sideC <= sideA) {
outputElement.textContent = "These sides cannot form a valid triangle. The sum of any two sides must be greater than the third side.";
return;
}
area = triangleArea(sideA, sideB, sideC);
perimeter = trianglePerimeter(sideA, sideB, sideC);
outputElement.innerHTML = `Triangle:
Sides: a=${sideA}, b=${sideB}, c=${sideC}
Area: ${area.toFixed(2)} square units
Perimeter: ${perimeter.toFixed(2)} units`;
break;
}
});
// Return Values and Function Expressions - Temperature Converter
document.getElementById('convertBtn').addEventListener('click', function() {
const temp = parseFloat(document.getElementById('tempInput').value);
const conversionType = document.getElementById('conversionType').value;
const outputElement = document.getElementById('tempOutput');
if (isNaN(temp)) {
outputElement.textContent = "Please enter a valid temperature.";
return;
}
// Function expression for Celsius to Fahrenheit
const celsiusToFahrenheit = function(celsius) {
return (celsius * 9/5) + 32;
};
// Arrow function for Fahrenheit to Celsius
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
let result, fromUnit, toUnit;
if (conversionType === 'CtoF') {
result = celsiusToFahrenheit(temp);
fromUnit = '°C';
toUnit = '°F';
} else {
result = fahrenheitToCelsius(temp);
fromUnit = '°F';
toUnit = '°C';
}
outputElement.textContent = `${temp}${fromUnit} = ${result.toFixed(2)}${toUnit}`;
});
// Arrow Functions and Higher-Order Functions - Array Processing
document.getElementById('processArrayBtn').addEventListener('click', function() {
const numbersInput = document.getElementById('numberListInput').value;
const operation = document.getElementById('arrayOperation').value;
const outputElement = document.getElementById('arrayOutput');
// Parse input into array of numbers
const numbers = numbersInput.split(',')
.map(num => num.trim())
.filter(num => num !== '')
.map(num => parseFloat(num))
.filter(num => !isNaN(num));
if (numbers.length === 0) {
outputElement.textContent = "Please enter valid numbers separated by commas.";
return;
}
// Arrow function for doubling numbers
const double = numbers => numbers.map(num => num * 2);
// Arrow function for squaring numbers
const square = numbers => numbers.map(num => num * num);
// Arrow function for filtering even numbers
const filterEven = numbers => numbers.filter(num => num % 2 === 0);
// Arrow function for calculating sum
const sum = numbers => numbers.reduce((total, num) => total + num, 0);
// Higher-order function to format and display results
const formatResults = (operation, originalArray, resultArray) => {
return `${operation}:
Original: [${originalArray.join(', ')}]
Result: [${Array.isArray(resultArray) ? resultArray.join(', ') : resultArray}]`;
};
let result = "";
// Perform selected operation
switch(operation) {
case 'double':
result = formatResults("Double Each Number", numbers, double(numbers));
break;
case 'square':
result = formatResults("Square Each Number", numbers, square(numbers));
break;
case 'filter':
result = formatResults("Filter Even Numbers", numbers, filterEven(numbers));
break;
case 'sum':
result = formatResults("Calculate Sum", numbers, sum(numbers));
break;
case 'all':
result = `${formatResults("Double Each Number", numbers, double(numbers))}
${formatResults("Square Each Number", numbers, square(numbers))}
${formatResults("Filter Even Numbers", numbers, filterEven(numbers))}
${formatResults("Calculate Sum", numbers, sum(numbers))}`;
break;
}
outputElement.innerHTML = result;
});
</script>
</body>
</html>
Explanation:
- We demonstrate four different aspects of JavaScript functions:
- Basic Functions: Simple function declarations, functions with parameters, and functions with default parameters.
- Functions with Parameters: A geometry calculator that uses functions to calculate area and perimeter for different shapes.
- Return Values and Function Expressions: A temperature converter using both traditional function expressions and arrow functions.
- Arrow Functions and Higher-Order Functions: Array processing using modern JavaScript features like map, filter, and reduce.
Program 5: DOM Manipulation
File: dom_manipulation.html
This program demonstrates how to manipulate the Document Object Model (DOM) using JavaScript. It shows how to select elements, modify content, change styles, create new elements, and respond to events.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Manipulation</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 20px;
color: #333;
}
.container {
max-width: 800px;
margin: 0 auto;
}
.section {
margin-bottom: 30px;
padding: 20px;
background-color: #f9f9f9;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
h1, h2, h3 {
color: #444;
}
.box {
width: 100px;
height: 100px;
margin: 10px;
display: inline-block;
background-color: #ccc;
text-align: center;
line-height: 100px;
cursor: pointer;
transition: all 0.3s ease;
}
button {
padding: 8px 15px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin: 5px;
transition: background-color 0.3s;
}
button:hover {
background-color: #45a049;
}
input, select {
padding: 8px;
margin: 5px 0;
width: 100%;
box-sizing: border-box;
border: 1px solid #ddd;
border-radius: 4px;
}
.task-item {
padding: 10px;
margin: 5px 0;
background-color: #f4f4f4;
border-radius: 4px;
display: flex;
justify-content: space-between;
align-items: center;
}
.task-item button {
padding: 5px 10px;
margin: 0 5px;
}
.completed {
text-decoration: line-through;
opacity: 0.7;
}
.highlight {
background-color: yellow;
font-weight: bold;
}
.gallery {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 10px;
}
.image-container {
width: 150px;
height: 150px;
overflow: hidden;
border-radius: 5px;
position: relative;
}
.image-container img {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.3s;
}
.image-container:hover img {
transform: scale(1.1);
}
.delete-btn {
position: absolute;
top: 5px;
right: 5px;
background-color: rgba(255,0,0,0.7);
color: white;
border: none;
border-radius: 50%;
width: 25px;
height: 25px;
font-size: 12px;
cursor: pointer;
display: none;
}
.image-container:hover .delete-btn {
display: block;
}
</style>
</head>
<body>
<div class="container">
<h1>DOM Manipulation with JavaScript</h1>
<!-- Section 1: Element Selection and Content Manipulation -->
<div class="section">
<h2>Element Selection and Content Manipulation</h2>
<div id="content-demo">
<p id="target-paragraph">This is a paragraph that we'll modify with JavaScript.</p>
<p class="info-text">This paragraph has a class.</p>
<p class="info-text">This is another paragraph with the same class.</p>
</div>
<div class="controls">
<button id="change-text-btn">Change Text</button>
<button id="add-html-btn">Add HTML</button>
<button id="highlight-btn">Highlight Class Elements</button>
<button id="reset-content-btn">Reset</button>
</div>
</div>
<!-- Section 2: Style Manipulation -->
<div class="section">
<h2>Style Manipulation</h2>
<div id="style-demo">
<div class="box" id="box1">Box 1</div>
<div class="box" id="box2">Box 2</div>
<div class="box" id="box3">Box 3</div>
</div>
<div class="controls">
<h3>Change Box 1:</h3>
<button id="change-color-btn">Random Color</button>
<button id="change-size-btn">Change Size</button>
<button id="rotate-btn">Rotate</button>
<h3>Change All Boxes:</h3>
<button id="random-all-btn">Random All</button>
<button id="reset-style-btn">Reset</button>
</div>
</div>
<!-- Section 3: Creating and Removing Elements -->
<div class="section">
<h2>Creating and Removing Elements</h2>
<div id="todo-app">
<h3>To-Do List</h3>
<div class="input-group">
<input type="text" id="task-input" placeholder="Enter a new task...">
<button id="add-task-btn">Add Task</button>
</div>
<div id="task-list">
<!-- Tasks will be added here by JavaScript -->
</div>
</div>
</div>
<!-- Section 4: Event Handling -->
<div class="section">
<h2>Event Handling</h2>
<div id="event-demo">
<h3>Interactive Form</h3>
<form id="user-form">
<div class="form-group">
<label for="name-input">Name:</label>
<input type="text" id="name-input" placeholder="Enter your name">
<span id="name-error" class="error"></span>
</div>
<div class="form-group">
<label for="email-input">Email:</label>
<input type="email" id="email-input" placeholder="Enter your email">
<span id="email-error" class="error"></span>
</div>
<div class="form-group">
<label for="color-select">Favorite Color:</label>
<select id="color-select">
<option value="">Select a color</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="purple">Purple</option>
<option value="orange">Orange</option>
</select>
</div>
<button type="submit" id="submit-btn">Submit</button>
</form>
<div id="form-preview" style="margin-top: 20px; display: none;">
<h4>Preview:</h4>
<p>Name: <span id="preview-name"></span></p>
<p>Email: <span id="preview-email"></span></p>
<p>Favorite Color: <span id="preview-color"></span></p>
</div>
</div>
</div>
<!-- Section 5: Dynamic Image Gallery -->
<div class="section">
<h2>Dynamic Image Gallery</h2>
<div id="gallery-app">
<h3>Image Gallery</h3>
<div class="input-group">
<input type="text" id="image-url-input" placeholder="Enter image URL (or leave empty for placeholder)">
<input type="text" id="image-title-input" placeholder="Enter image title">
<button id="add-image-btn">Add Image</button>
</div>
<div class="gallery" id="image-gallery">
<!-- Images will be added here by JavaScript -->
</div>
</div>
</div>
</div>
<script>
// Section 1: Element Selection and Content Manipulation
document.getElementById('change-text-btn').addEventListener('click', function() {
// Select an element by ID and change its text content
const paragraph = document.getElementById('target-paragraph');
paragraph.textContent = 'The text has been changed by JavaScript!';
});
document.getElementById('add-html-btn').addEventListener('click', function() {
// Select an element by ID and change its HTML content
const paragraph = document.getElementById('target-paragraph');
paragraph.innerHTML = 'This paragraph now contains bold and italic text!';
});
document.getElementById('highlight-btn').addEventListener('click', function() {
// Select elements by class name
const infoTexts = document.getElementsByClassName('info-text');
// Loop through all elements with the class
for (let i = 0; i < infoTexts.length; i++) {
infoTexts[i].classList.toggle('highlight');
}
});
document.getElementById('reset-content-btn').addEventListener('click', function() {
// Reset the content section to its original state
document.getElementById('target-paragraph').textContent = 'This is a paragraph that we\'ll modify with JavaScript.';
const infoTexts = document.getElementsByClassName('info-text');
for (let i = 0; i < infoTexts.length; i++) {
infoTexts[i].textContent = i === 0 ? 'This paragraph has a class.' : 'This is another paragraph with the same class.';
infoTexts[i].classList.remove('highlight');
}
});
// Section 2: Style Manipulation
document.getElementById('change-color-btn').addEventListener('click', function() {
// Change background color of box1
const box = document.getElementById('box1');
const randomColor = getRandomColor();
box.style.backgroundColor = randomColor;
});
document.getElementById('change-size-btn').addEventListener('click', function() {
// Change size of box1
const box = document.getElementById('box1');
const currentWidth = parseInt(box.style.width || '100');
if (currentWidth >= 150) {
box.style.width = '100px';
box.style.height = '100px';
} else {
box.style.width = (currentWidth + 20) + 'px';
box.style.height = (currentWidth + 20) + 'px';
}
});
document.getElementById('rotate-btn').addEventListener('click', function() {
// Rotate box1
const box = document.getElementById('box1');
const currentRotation = box.style.transform || 'rotate(0deg)';
const rotationMatch = currentRotation.match(/rotate\((\d+)deg\)/);
const rotation = rotationMatch ? parseInt(rotationMatch[1]) : 0;
box.style.transform = `rotate(${rotation + 45}deg)`;
});
document.getElementById('random-all-btn').addEventListener('click', function() {
// Change all boxes to random colors
const boxes = document.getElementsByClassName('box');
for (let i = 0; i < boxes.length; i++) {
boxes[i].style.backgroundColor = getRandomColor();
}
});
document.getElementById('reset-style-btn').addEventListener('click', function() {
// Reset all boxes to original state
const boxes = document.getElementsByClassName('box');
for (let i = 0; i < boxes.length; i++) {
boxes[i].style = ''; // Clear all inline styles
}
});
// Helper function to generate random color
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
// Section 3: Creating and Removing Elements - To-Do List
document.getElementById('add-task-btn').addEventListener('click', addTask);
document.getElementById('task-input').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
addTask();
}
});
function addTask() {
const taskInput = document.getElementById('task-input');
const taskText = taskInput.value.trim();
if (taskText === '') {
alert('Please enter a task!');
return;
}
// Create new task element
const taskList = document.getElementById('task-list');
const taskItem = document.createElement('div');
taskItem.className = 'task-item';
// Create text element
const taskTextElement = document.createElement('span');
taskTextElement.textContent = taskText;
// Create buttons
const buttonsDiv = document.createElement('div');
const completeBtn = document.createElement('button');
completeBtn.textContent = '✓';
completeBtn.title = 'Mark as complete';
completeBtn.addEventListener('click', function() {
taskTextElement.classList.toggle('completed');
});
const deleteBtn = document.createElement('button');
deleteBtn.textContent = '✕';
deleteBtn.title = 'Delete task';
deleteBtn.style.backgroundColor = '#ff4444';
deleteBtn.addEventListener('click', function() {
taskList.removeChild(taskItem);
});
// Append elements
buttonsDiv.appendChild(completeBtn);
buttonsDiv.appendChild(deleteBtn);
taskItem.appendChild(taskTextElement);
taskItem.appendChild(buttonsDiv);
taskList.appendChild(taskItem);
// Clear the input
taskInput.value = '';
taskInput.focus();
}
// Section 4: Event Handling - Interactive Form
const nameInput = document.getElementById('name-input');
const emailInput = document.getElementById('email-input');
const colorSelect = document.getElementById('color-select');
const nameError = document.getElementById('name-error');
const emailError = document.getElementById('email-error');
const previewDiv = document.getElementById('form-preview');
const previewName = document.getElementById('preview-name');
const previewEmail = document.getElementById('preview-email');
const previewColor = document.getElementById('preview-color');
// Live preview updates
nameInput.addEventListener('input', updatePreview);
emailInput.addEventListener('input', updatePreview);
colorSelect.addEventListener('change', updatePreview);
function updatePreview() {
if (nameInput.value || emailInput.value || colorSelect.value) {
previewDiv.style.display = 'block';
previewName.textContent = nameInput.value || 'Not provided';
previewEmail.textContent = emailInput.value || 'Not provided';
if (colorSelect.value) {
previewColor.textContent = colorSelect.options[colorSelect.selectedIndex].text;
previewColor.style.color = colorSelect.value;
} else {
previewColor.textContent = 'Not selected';
previewColor.style.color = '';
}
} else {
previewDiv.style.display = 'none';
}
}
// Form validation
document.getElementById('user-form').addEventListener('submit', function(e) {
e.preventDefault(); // Prevent form submission
let isValid = true;
// Validate name
if (nameInput.value.trim() === '') {
nameError.textContent = 'Name is required';
isValid = false;
} else {
nameError.textContent = '';
}
// Validate email
if (emailInput.value.trim() === '') {
emailError.textContent = 'Email is required';
isValid = false;
} else if (!isValidEmail(emailInput.value)) {
emailError.textContent = 'Please enter a valid email address';
isValid = false;
} else {
emailError.textContent = '';
}
if (isValid) {
alert(`Form submitted successfully!\nName: ${nameInput.value}\nEmail: ${emailInput.value}\nFavorite Color: ${colorSelect.options[colorSelect.selectedIndex].text}`);
this.reset();
previewDiv.style.display = 'none';
}
});
function isValidEmail(email) {
// Simple email validation regex
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
// Section 5: Dynamic Image Gallery
document.getElementById('add-image-btn').addEventListener('click', function() {
const urlInput = document.getElementById('image-url-input');
const titleInput = document.getElementById('image-title-input');
const imageUrl = urlInput.value.trim() || 'https://via.placeholder.com/150';
const imageTitle = titleInput.value.trim() || 'Image ' + (document.getElementById('image-gallery').children.length + 1);
addImageToGallery(imageUrl, imageTitle);
// Clear inputs
urlInput.value = '';
titleInput.value = '';
});
function addImageToGallery(url, title) {
const gallery = document.getElementById('image-gallery');
// Create container
const container = document.createElement('div');
container.className = 'image-container';
// Create image
const img = document.createElement('img');
img.src = url;
img.alt = title;
img.title = title;
// Create delete button
const deleteBtn = document.createElement('button');
deleteBtn.className = 'delete-btn';
deleteBtn.textContent = '✕';
deleteBtn.addEventListener('click', function(e) {
e.stopPropagation(); // Prevent container click when delete button is clicked
gallery.removeChild(container);
});
// Append elements
container.appendChild(img);
container.appendChild(deleteBtn);
gallery.appendChild(container);
// Add click event for image details
container.addEventListener('click', function() {
alert(`Image: ${title}\nURL: ${url}`);
});
}
// Add some initial images to the gallery
addImageToGallery('https://via.placeholder.com/150/0088cc/ffffff?text=Image+1', 'Sample Image 1');
addImageToGallery('https://via.placeholder.com/150/cc0088/ffffff?text=Image+2', 'Sample Image 2');
</script>
</body>
</html>
Explanation of DOM Manipulation Program:
- Element Selection and Content Manipulation: Demonstrates how to select elements by ID and class, and how to modify their content using textContent and innerHTML.
- Style Manipulation: Shows how to change element styles dynamically, including colors, dimensions, and transformations.
- Creating and Removing Elements: Implements a to-do list application that dynamically creates and removes DOM elements based on user input.
- Event Handling: Creates an interactive form with validation and live preview, demonstrating various event types (click, input, submit) and how to handle them.
- Dynamic Image Gallery: Combines all the previous concepts to build a more complex application that allows users to add and remove images from a gallery.
Each section demonstrates important DOM manipulation techniques that are essential for creating interactive web applications.
Step 4: Look Back and Review
We've successfully created five JavaScript programs that demonstrate the fundamental concepts covered in our session:
- Program 1 (Variables and Operations): Shows how to work with different variable types and perform basic operations.
- Program 2 (Conditional Statements): Demonstrates how to make decisions in code using if/else statements, switch statements, and the ternary operator.
- Program 3 (Loops): Illustrates different types of loops (for, while, do-while, for...of) and how to use them for repetitive tasks.
- Program 4 (Functions): Shows how to create and use functions, including parameters, return values, and modern arrow functions.
- Program 5 (DOM Manipulation): Demonstrates how to interact with HTML elements, modify content, change styles, and respond to user events.
Each program is well-commented and includes practical examples that reinforce the concepts being taught. They also provide a foundation for more advanced JavaScript programming in the future.
Understanding JavaScript Basics
What is JavaScript?
graph TD
A[Web Development] --> B[HTML]
A --> C[CSS]
A --> D[JavaScript]
B --> B1[Structure]
C --> C1[Presentation]
D --> D1[Behavior]
D1 --> E1[User Interaction]
D1 --> E2[DOM Manipulation]
D1 --> E3[Data Processing]
D1 --> E4[Asynchronous Operations]
style A fill:#f9f,stroke:#333,stroke-width:2px
style B fill:#bbf,stroke:#333,stroke-width:1px
style C fill:#bbf,stroke:#333,stroke-width:1px
style D fill:#f9a,stroke:#333,stroke-width:1px
JavaScript is a high-level, interpreted programming language that allows you to implement complex features on web pages. While HTML provides the structure and CSS handles the presentation, JavaScript adds interactivity and dynamic behavior to websites.
Key characteristics of JavaScript:
- Client-Side Execution: JavaScript runs in the user's browser, allowing for dynamic content without server round-trips.
- Event-Driven Programming: JavaScript responds to user actions (clicks, keypresses, etc.) through event handlers.
- DOM Manipulation: JavaScript can access and modify the Document Object Model, changing content and styles dynamically.
- Versatility: JavaScript can now run on servers (Node.js), mobile apps, desktop applications, and more.
Core JavaScript Concepts
1. Variables and Data Types
Variables are containers for storing data values. JavaScript has several data types:
- Primitive Types:
- String: Text values like "Hello World"
- Number: Numeric values like 42 or 3.14
- Boolean: true or false values
- undefined: A variable that has been declared but not assigned a value
- null: Represents the intentional absence of any value
- Symbol: Unique and immutable primitive values (ES6)
- BigInt: For integers larger than the Number type can handle (ES2020)
- Reference Types:
- Object: Collections of key-value pairs
- Array: Ordered collections of values
- Function: Blocks of reusable code
- Date: Represents dates and times
- RegExp: Regular expressions for pattern matching
2. Operators
Operators perform operations on variables and values:
- Arithmetic Operators: +, -, *, /, %, **, ++, --
- Assignment Operators: =, +=, -=, *=, /=, %=
- Comparison Operators: ==, ===, !=, !==, >, <, >=, <=
- Logical Operators: &&, ||, !
- String Operators: + (concatenation), += (concatenation assignment)
- Conditional (Ternary) Operator: condition ? exprIfTrue : exprIfFalse
3. Control Structures
Control structures determine the flow of program execution:
- Conditional Statements: if/else, switch, ternary operator
- Loops: for, while, do-while, for...of, for...in
- Error Handling: try/catch/finally
4. Functions
Functions are blocks of reusable code that perform specific tasks:
- Function Declaration:
function name(parameters) { /* code */ } - Function Expression:
const name = function(parameters) { /* code */ }; - Arrow Function (ES6):
const name = (parameters) => { /* code */ }; - Parameters and Arguments: Values passed to functions
- Return Values: Data that functions send back
- Scope: Variable accessibility within functions
5. DOM Manipulation
The Document Object Model (DOM) is a programming interface for HTML documents:
- Element Selection:
document.getElementById(),document.querySelector(), etc. - Content Manipulation:
element.textContent,element.innerHTML - Attribute Manipulation:
element.setAttribute(),element.getAttribute() - Style Manipulation:
element.style.property,element.classList - Creating Elements:
document.createElement(),element.appendChild() - Removing Elements:
element.removeChild(),element.remove() - Event Handling:
element.addEventListener()
How JavaScript Executes
Here's how JavaScript executes in a browser:
- Loading: The browser loads the HTML document and parses it into the DOM.
- Parsing: When the browser encounters a
<script>tag, it pauses DOM construction to parse and execute the JavaScript code. - Compilation: Modern JavaScript engines use Just-In-Time (JIT) compilation, which combines interpretation and compilation for better performance.
- Execution: The JavaScript code runs, manipulating the DOM and responding to events as needed.
- Event Loop: JavaScript uses an event-driven model with a single thread. The event loop continuously checks for events and executes their handlers.
JavaScript Best Practices
1. Use Proper Variable Declarations
- Use
constfor values that shouldn't change (recommended default) - Use
letfor variables that need to be reassigned - Avoid
vardue to scoping issues - Choose descriptive variable names that indicate purpose
// Bad
var x = 5;
// Good
const maxAttempts = 5;
let currentAttempt = 0;
2. Follow Consistent Formatting
- Use consistent indentation (2 or 4 spaces)
- Add appropriate spacing around operators
- End statements with semicolons
- Use consistent brace style
- Consider using a linter like ESLint to enforce style guidelines
// Bad
if(condition){console.log('true');}
else{
console.log('false')
}
// Good
if (condition) {
console.log('true');
} else {
console.log('false');
}
3. Use Strict Equality
- Use
===and!==instead of==and!= - Strict equality compares both value and type, preventing unexpected type conversions
// Bad - evaluates to true due to type coercion
if (5 == "5") {
console.log("Equal");
}
// Good - evaluates to false as they're different types
if (5 === "5") {
console.log("This won't execute");
} else {
console.log("Not equal");
}
4. Use Meaningful Comments
- Comment on why, not what (the code shows what, comments explain why)
- Use JSDoc comments for functions to document parameters and return values
- Keep comments up-to-date with code changes
// Bad
// Add 1 to count
count += 1;
// Good
// Increment the counter to track number of form submissions
count += 1;
/**
* Calculates the area of a rectangle
* @param {number} width - The width of the rectangle
* @param {number} height - The height of the rectangle
* @returns {number} The area of the rectangle
*/
function calculateArea(width, height) {
return width * height;
}
5. Handle Errors Properly
- Use try/catch blocks for error-prone code
- Provide specific error messages
- Avoid swallowing errors without handling them
// Bad
function parseJSON(data) {
return JSON.parse(data); // Will throw error if data is invalid
}
// Good
function parseJSON(data) {
try {
return JSON.parse(data);
} catch (error) {
console.error("Failed to parse JSON data:", error);
return null; // Return a default value
}
}
6. Modularize Your Code
- Break complex functions into smaller, reusable functions
- Keep functions focused on a single task
- Use descriptive function names that indicate what they do
// Bad
function processUserData(user) {
// 50 lines of code doing many different things
}
// Good
function processUserData(user) {
validateUserInput(user);
saveUserToDatabase(user);
sendWelcomeEmail(user);
}
Debugging JavaScript
1. Using console.log()
The simplest debugging technique is to use console.log() to print values to the browser console:
// Check variable values
console.log("User ID:", userId);
// Log objects
console.log("User Object:", userObj);
// Use descriptive labels
console.log("Before loop:", counter);
for (let i = 0; i < 3; i++) {
console.log("Loop iteration:", i);
}
console.log("After loop:", counter);
Variations of console methods:
console.error()- For error messages (appears in red)console.warn()- For warning messages (appears in yellow)console.info()- For informational messagesconsole.table()- For displaying tabular data
2. Using Browser DevTools
Modern browsers include powerful developer tools for debugging:
- Breakpoints: Pause execution at specific lines of code
- Step Through: Execute code one statement at a time
- Watch Variables: Monitor specific variables during execution
- Call Stack: View the execution path that led to the current point
To access DevTools:
- Chrome/Edge: F12 or Ctrl+Shift+I (Cmd+Option+I on Mac)
- Firefox: F12 or Ctrl+Shift+I
- Safari: Cmd+Option+I (Enable Developer menu in Preferences first)
3. Using debugger Statement
The debugger statement creates a breakpoint in your code:
function calculateTotal(items) {
let total = 0;
for (let i = 0; i < items.length; i++) {
debugger; // Execution will pause here when DevTools is open
total += items[i].price * items[i].quantity;
}
return total;
}
When DevTools is open, execution will pause at the debugger statement, allowing you to inspect variables and step through code.
4. Common JavaScript Errors
| Error Type | Description | Example |
|---|---|---|
| SyntaxError | Invalid JavaScript syntax | if (x === 5 { (missing closing parenthesis) |
| ReferenceError | Reference to an undefined variable | console.log(undefinedVar); |
| TypeError | Value is not of the expected type | null.toString(); |
| RangeError | Value is outside the allowed range | new Array(-1); |
| Logic Error | Code doesn't produce the expected result | if (x = 5) (assignment instead of comparison) |
Further Learning Resources
- MDN Web Docs: JavaScript - Comprehensive documentation and tutorials
- JavaScript.info - Modern JavaScript tutorial
- W3Schools JavaScript Tutorial - Beginner-friendly tutorials with examples
- Eloquent JavaScript - Free online book
- Codecademy: Introduction to JavaScript - Interactive JavaScript course
- You Don't Know JS - Book series for deeper JavaScript understanding
Homework Assignment
Primary Task: Create Simple JavaScript Programs
Create five simple JavaScript programs that demonstrate your understanding of the concepts covered in this lesson:
Program 1: Number Analyzer
Create a program that takes a number as input and displays:
- Whether it's positive, negative, or zero
- Whether it's even or odd
- Its square and cube
- Its square root (if applicable)
Program 2: String Manipulator
Create a program that takes a string as input and displays:
- The string's length
- The string in all uppercase and all lowercase
- The string reversed
- Whether the string is a palindrome (reads the same forward and backward)
Program 3: Array Processor
Create a program that generates an array of 10 random numbers between 1 and 100, then displays:
- The original array
- The array sorted in ascending order
- The minimum and maximum values
- The sum and average of all numbers
- Only the even numbers in the array
Program 4: Simple Calculator
Create a calculator that can perform basic arithmetic operations (addition, subtraction, multiplication, division) on two numbers. The program should:
- Take two numbers as input
- Allow the user to select an operation
- Display the result
- Handle potential errors (like division by zero)
Program 5: Interactive Form Validator
Create a registration form with the following fields:
- Username (must be at least 5 characters)
- Email (must be a valid email format)
- Password (must be at least 8 characters with at least one number)
- Confirm Password (must match the password)
The form should validate inputs in real-time and display appropriate error messages.
Submission Guidelines
- Create a separate HTML file for each program
- Include appropriate comments explaining your code
- Ensure all programs work correctly before submission
- Package all files into a ZIP archive
- Be prepared to explain how your programs work in the next session
Grading Criteria
- Functionality (40%): Programs work as described and handle edge cases
- Code Quality (30%): Well-structured, properly formatted, and well-commented code
- Application of Concepts (20%): Proper use of variables, control structures, functions, and DOM manipulation
- User Experience (10%): Clear interface with appropriate feedback to users
Bonus Challenges (Optional)
- Local Storage: Save form data or calculator history to localStorage
- Advanced Validation: Add more sophisticated validation rules to the form
- Styling Enhancement: Add CSS to make your programs visually appealing
- Advanced Calculator: Add more operations (square root, exponentiation, etc.)
- Responsive Design: Make your programs work well on different screen sizes