Introduction to JavaScript
JavaScript is a versatile client-side scripting language that runs directly in web browsers. Every modern browser includes a JavaScript engine for executing code. Unlike compiled languages, JavaScript is interpreted, allowing browsers to execute it immediately without a compilation step. Its primary role is to enhance user interaction with HTML pages, creating dynamic experiences and improving overall user engagement.
Historical Context:
- 1995: Netscape developed LiveScript, later renamed JavaScript with Sun Microsystems' involvement
- 1996: Microsoft created JScript as their JavaScript implementation
- 1997: ECMA (European Computer Manufacturers Association) established ECMAScript as the standard for client-side scripting languages
Quick Start Guide
Implementation Steps:
- Create an HTML file
- Add a script tag within the document
- Write JavaScript code inside the script tag
- Test in a web browser
Basic HTML Structure:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Introduction</title>
</head>
<body>
<button id="actionBtn">Click Me</button>
</body>
</html>
Internal Script Method:
<script>
document.getElementById("actionBtn").addEventListener("click", function() {
alert("Button was clicked!");
});
</script>
External Script Method:
Create a JavaScript file (app.js):
document.getElementById("actionBtn").addEventListener("click", function() {
alert("Button was clicked!");
});
Link it in HTML:
<script src="scripts/app.js"></script>
Development Environment Setup
Recommended Tools:
- Node.js: JavaScript runtime environment for development
- VS Code: Powerful IDE for frontend development
JavaScript Fundamentals Summary
- Client-side scripting language for web interactivity
- Core Components: ECMAScript, DOM, BOM
- Integration Methods: Internal <script> tags and external file references
Core JavaScript Syntax
Comments
Single-line comment:
// This is a comment
Multi-line comment:
/*
This comment spans
multiple lines
*/
Input and Output Statements
- User Input: prompt("Enter your name")
- Alert Box: alert("Message")
- Console Output: console.log("Debug info")
- Page Output: document.write("Content")
Variables and Constants
JavaScript is dynamically typed, meaning variables can hold different data types.
Block-scoped Variables:
let userName = "Alice";
let userAge = 25;
console.log(`${userName} is ${userAge} years old`);
Global Variables:
{
let localVar = "local";
globalVar = "global";
}
console.log(globalVar); // Accessible
Constants:
const MAX_LOGIN_ATTEMPTS = 3;
// MAX_LOGIN_ATTEMPTS = 5; // Error: Cannot reassign
Data Types and Type Checking
Primitive Data Types:
- Boolean: true/false
- Number: Integers and floats
- String: Text data
- BigInt: Large integers
- Null: Intentional absence
- Undefined: Uninitialized variables
Type Checking:
let value = 42;
console.log(typeof value); // "number"
Operators
Arithmetic Operators:
let result = (10 + 5) * 2 - 3 / 1; // Basic arithmetic
Assignment Operators:
let count = 0;
count += 5; // count = count + 5
Comparison Operators:
let isEqual = (5 === "5"); // false (strict equality)
let isLooseEqual = (5 == "5"); // true (loose equality)
Logical Operators:
let canDrive = (age >= 16) && (hasLicense === true);
Ternary Operator:
let message = (score >= 60) ? "Passed" : "Failed";
Control Flow and Loops
Conditional Statements:
let month = 7;
if (month >= 3 && month <= 5) {
console.log("Spring");
} else if (month >= 6 && month <= 8) {
console.log("Summer");
} else {
console.log("Other season");
}
Switch Statement:
let dayOfWeek = 3;
switch(dayOfWeek) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid day");
}
For Loop:
for (let i = 1; i <= 10; i++) {
console.log(`Count: ${i}`);
}
While Loop:
let counter = 5;
while (counter > 0) {
console.log(`Remaining: ${counter}`);
counter--;
}
Arrays
JavaScript arrays are flexible collections that can hold mixed data types.
Array Declaration:
let mixedArray = ["text", 42, true, null];
let numbers = [1, 2, 3, 4, 5];
Array Operations:
// Access elements
let first = numbers[0]; // 1
let last = numbers[numbers.length - 1]; // 5
// Array spread operator
let copy = [...numbers];
let combined = [...numbers, 6, 7, 8];
Functions
Functions encapsulate reusable code blocks.
Function Declaration:
function calculateArea(width, height) {
return width * height;
}
Rest Parameters:
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
Arrow Functions:
const multiply = (a, b) => a * b;
const greet = name => `Hello, ${name}!`;
DOM Manipulation
Introduction to DOM
The Document Object Model (DOM) represents HTML documents as a tree structure of objects, enabling programmatic access and modification of document content.
Selecting Elements
Common Selection Methods:
// By ID
let header = document.getElementById("main-header");
// By tag name
let paragraphs = document.getElementsByTagName("p");
// By class name
let items = document.getElementsByClassName("list-item");
// By CSS selector
let button = document.querySelector("#submit-btn");
let allButtons = document.querySelectorAll("button");
// Parent element access
let parent = element.parentElement;
Element Manipulation
Creating and Adding Elements:
// Create new element
let newItem = document.createElement("li");
newItem.textContent = "New list item";
// Append to parent
let list = document.getElementById("my-list");
list.appendChild(newItem);
Removing Elements:
// Remove element
parent.removeChild(childElement);
// Modern approach
element.remove();
Replacing Elements:
let oldItem = document.querySelector("li:first-child");
let replacement = document.createElement("li");
replacement.textContent = "Replacement item";
list.replaceChild(replacement, oldItem);
Attribute Operations
// Set attributes
element.setAttribute("data-id", "123");
// Get attributes
let id = element.getAttribute("data-id");
// Remove attributes
element.removeAttribute("data-id");
// Style manipulation
element.style.color = "blue";
element.classList.add("active");
element.classList.toggle("hidden");
Text Content Manipulation
// Plain text (HTML ignored)
element.textContent = "Plain text content";
// HTML content (HTML parsed)
element.innerHTML = "<strong>Formatted content</strong>";
Event Handling
Event Overview
Events are actions or occurrences that happen in the browser, which can be detected and responded to using JavaScript.
Common Events:
- Click: onclick
- Double Click: ondblclick
- Focus: onfocus
- Blur: onblur
- Change: onchange
- Submit: onsubmit
- Load: onload
Event Binding Methods
HTML Attribute Method:
<button onclick="handleClick()">Click Me</button>
DOM Property Method:
document.getElementById("myButton").onclick = function() {
console.log("Button clicked!");
};
addEventListener Method (Recommmended):
element.addEventListener("click", function(event) {
console.log("Event handled with addEventListener");
});
Practical Example: Dynamic Data Table
Project Overview
Create an interactive data management system where users can add and delete records from a table dynamically.
Add Functionality Implementation
// Add record handler
document.getElementById("addRecord").addEventListener("click", function() {
// Get input values
let name = document.getElementById("nameInput").value;
let age = document.getElementById("ageInput").value;
let role = document.getElementById("roleInput").value;
// Validate inputs
if (!name || !age || !role) {
alert("Please fill all fields");
return;
}
// Create new row
let tableBody = document.querySelector("#dataTable tbody");
let newRow = document.createElement("tr");
// Create cells
newRow.innerHTML = `
<td>${name}</td>
<td>${age}</td>
<td>${role}</td>
<td>
<button class="delete-btn" onclick="removeRow(this)">
Remove
</button>
</td>
`;
// Add row to table
tableBody.appendChild(newRow);
// Clear inputs
document.getElementById("nameInput").value = "";
document.getElementById("ageInput").value = "";
document.getElementById("roleInput").value = "";
});
Delete Functionality Implementation
function removeRow(button) {
if (confirm("Are you sure you want to delete this record?")) {
let row = button.closest("tr");
row.style.opacity = "0";
setTimeout(() => {
row.remove();
}, 300);
}
}
Complete HTML Structure:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic Data Manager</title>
<style>
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.form-group {
margin: 10px 0;
}
input {
padding: 8px;
margin: 5px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 12px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
.delete-btn {
background-color: #ff4444;
color: white;
border: none;
padding: 5px 10px;
cursor: pointer;
}
tr {
transition: opacity 0.3s;
}
</style>
</head>
<body>
<div class="container">
<h2>Employee Management System</h2>
<div class="form-group">
<input type="text" id="nameInput" placeholder="Employee Name">
<input type="number" id="ageInput" placeholder="Age">
<input type="text" id="roleInput" placeholder="Role">
<button id="addRecord">Add Employee</button>
</div>
<table id="dataTable">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Role</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Doe</td>
<td>30</td>
<td>Developer</td>
<td>
<button class="delete-btn" onclick="removeRow(this)">
Remove
</button>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>