Object-Oriented Programming in JavaScript
JavaScript follows an object-oriented paradigm similar to Java, treating entities as objects to model real-world logic.
Class Definition and Instantiation
The class syntax provides a structured way to define blueprints for objects.
<!DOCTYPE html>
<html>
<body>
<script>
class User {
constructor(id, username) {
this.id = id;
this.username = username;
}
displayInfo() {
console.log(`ID: ${this.id}, Name: ${this.username}`);
}
login() {
console.log("User logged in.");
}
}
const currentUser = new User(101, "Alice");
currentUser.displayInfo();
currentUser.login();
</script>
</body>
</html>
Object Literals
A more concise approach for creating single instances involves using object literal notation.
<!DOCTYPE html>
<html>
<body>
<script>
const product = {
itemId: "A50",
price: 99.99,
tags: ["electronics", "gadget"],
applyDiscount: function() {
console.log("Discount applied.");
}
};
console.log(`${product.itemId}, ${product.price}, ${product.tags[0]}`);
product.applyDiscount();
</script>
</body>
</html>
Inheritance
The extends keyword facilitates inheritance, allowing child classes to acquire properties and methods from a parent class. Object serves as the root parent class.
<!DOCTYPE html>
<html>
<body>
<script>
class Entity {
constructor(name) {
this.name = name;
}
getType() {
return "Generic Entity";
}
}
class Animal extends Entity {
constructor(name, species) {
super(name);
this.species = species;
}
describe() {
console.log(`${this.name} is a ${this.species}`);
}
}
const pet = new Animal("Buddy", "Dog");
pet.describe();
console.log(pet.getType());
</script>
</body>
</html>
Built-in JavaScript Objects
Number Object
The Number object provides utilities for parsing numeric values from strings.
<!DOCTYPE html>
<html>
<body>
<script>
// Converts a string representation of a float to a floating-point number
console.log(Number.parseFloat("3.1415"));
// Parses a string into an integer (stops at first non-numeric character)
console.log(Number.parseInt("123abc"));
console.log(Number.parseInt("456"));
</script>
</body>
</html>
Math Object
The Math object offers standard mathematical constants and functions.
<!DOCTYPE html>
<html>
<body>
<script>
// Rounding up to the nearest integer
console.log(Math.ceil(4.2)); // 5
// Rounding down to the nearest integer
console.log(Math.floor(4.9)); // 4
// Standard rounding
console.log(Math.round(4.5)); // 5
// Random number between 0 (inclusive) and 1 (exclusive)
console.log(Math.random());
// Power function
console.log(Math.pow(3, 2)); // 9
</script>
</body>
</html>
Date Object
The Date object handles date and time storage and manipulation.
<!DOCTYPE html>
<html>
<body>
<script>
// Current date
const now = new Date();
console.log(now.toString());
// Date from specific timestamp
const epochTime = new Date(0);
console.log(epochTime.toString());
// Date from specific components (Month is 0-indexed: 2 is March)
const future = new Date(2025, 2, 15, 12, 30, 0);
console.log(future.getFullYear());
console.log(future.getMonth());
console.log(future.getDate());
console.log(future.toLocaleString());
</script>
</body>
</html>
String Object
The String object provides methods for sequence manipulation and text processing.
<!DOCTYPE html>
<html>
<body>
<script>
const text = "Developer";
// Property: length
console.log(text.length);
// Method: charAt(index)
console.log(text.charAt(0));
// Method: indexOf(substring)
console.log(text.indexOf("e"));
// Method: substring(start, end)
console.log(text.substring(0, 4));
// Method: split(separator)
const rawData = "red,green,blue";
const colors = rawData.split(",");
colors.forEach(c => console.log(c));
// Method: replace(old, new)
const note = "Error: System failure.";
const corrected = note.replace("Error", "Warning");
console.log(corrected);
</script>
</body>
</html>
RegExp Object
Regular Expressions define patterns for searching and validating strings.
<!DOCTYPE html>
<html>
<body>
<script>
// Email validation pattern
// Rule: alphanumeric characters, dots, or hyphens followed by @ domain
const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
console.log(emailPattern.test("user@example.com"));
// Zip code validation (5 digits)
const zipPattern = /^\d{5}$/;
console.log(zipPattern.test("90210"));
</script>
</body>
</html>
Array Object
The Array object manages ordered lists of data with various manipulation methods.
<!DOCTYPE html>
<html>
<body>
<script>
const numbers = [10, 20, 30, 40];
// Add to end
numbers.push(50);
console.log(numbers.join(", "));
// Remove from end
numbers.pop();
console.log(numbers.join(", "));
// Remove from start
numbers.shift();
console.log(numbers.join(", "));
// Check existence
console.log(numbers.includes(20));
// Reverse order
numbers.reverse();
console.log(numbers.join(", "));
// Sort elements
numbers.sort();
console.log(numbers.join(", "));
</script>
</body>
</html>
Set Object
Set stores unique values of any type, maintaining insertion order.
<!DOCTYPE html>
<html>
<body>
<script>
const uniqueItems = new Set();
uniqueItems.add("apple");
uniqueItems.add("banana");
uniqueItems.add("apple"); // Duplicate ignored
console.log(uniqueItems.size);
// Iteration
const iterator = uniqueItems.keys();
console.log(iterator.next().value);
// Deletion
uniqueItems.delete("banana");
console.log(uniqueItems.has("banana"));
</script>
</body>
</html>
Map Object
Map holds key-value pairs where keys can be any type and are unique.
<!DOCTYPE html>
<html>
<body>
<script>
const config = new Map();
config.set("theme", "dark");
config.set(1, "numeric key");
config.set("theme", "light"); // Updates existing key
console.log(config.size);
console.log(config.get("theme"));
// Iteration
const entryIterator = config.entries();
console.log(entryIterator.next().value);
// Deletion
config.delete(1);
console.log(config.has(1));
</script>
</body>
</html>
JSON
JavaScript Object Notation is a lightweight data-interchange format. Native methods exist to convert between JS objects and JSON strings.
<!DOCTYPE html>
<html>
<body>
<script>
const userProfile = {
userId: 55,
role: "admin",
active: true
};
// Serialization: Object to JSON string
const jsonString = JSON.stringify(userProfile);
console.log(jsonString);
// Deserialization: JSON string to Object
const parsedData = JSON.parse(jsonString);
console.log(parsedData.role);
</script>
</body>
</html>
Form Validation Example
Validating user input before submission using event listeners and Regular Expressions.
<!DOCTYPE html>
<html>
<body>
<form id="loginForm" autocomplete="off">
<input type="text" id="username" placeholder="Username"><br>
<input type="password" id="password" placeholder="Password"><br>
<button type="submit">Login</button>
</form>
<script>
document.getElementById("loginForm").onsubmit = function() {
const user = document.getElementById("username").value;
const pass = document.getElementById("password").value;
// Validate username: Alphanumeric, 4-12 chars
const userReg = /^[a-zA-Z0-9]{4,12}$/;
if (!userReg.test(user)) {
alert("Invalid username format.");
return false;
}
// Validate password: At least 6 chars
const passReg = /^.{6,}$/;
if (!passReg.test(pass)) {
alert("Password must be at least 6 characters.");
return false;
}
return true;
};
</script>
</body>
</html>
Browser Object Model (BOM)
Window Object
The window object represents the browser window and provides timers and event handlers for page lifecycle.
<!DOCTYPE html>
<html>
<head>
<script>
// One-time timer
const timeoutId = setTimeout(() => {
alert("Time is up!");
}, 2000);
// clearTimout(timeoutId); // Uncomment to cancel
// Repeating timer
const intervalId = setInterval(() => {
console.log("Tick...");
}, 1000);
// clearInteral(intervalId); // Uncomment to cancel
// Page load event
window.onload = function() {
console.log("All resources loaded.");
};
</script>
</head>
<body>
<div id="content">Loading...</div>
</body>
</html>
Location Object
The location object manages the URL of the current page. Assigning a value to href triggers a navigation.
<!DOCTYPE html>
<html>
<body>
<p>Redirecting in <span id="timer">5</span> seconds...</p>
<script>
let seconds = 5;
const timerElement = document.getElementById("timer");
const countdown = setInterval(() => {
seconds--;
timerElement.innerText = seconds;
if (seconds === 0) {
clearInterval(countdown);
location.href = "https://www.example.com";
}
}, 1000);
</script>
</body>
</html>
Dynamic Advertisement Banner
Using timers to toggle the visibility of an element.
<!DOCTYPE html>
<html>
<body>
<!-- Image hidden initially via inline style -->
<img id="promoBanner" src="promo.jpg" style="display: none;" width="100%">
<script>
// Show banner after 2 seconds
setTimeout(() => {
const banner = document.getElementById("promoBanner");
banner.style.display = "block";
// Hide banner after another 3 seconds
setTimeout(() => {
banner.style.display = "none";
}, 3000);
}, 2000);
</script>
</body>
</html>
DOM Manipulation Utilities
Encapsulating common DOM selection operations into reusable functions improves code readability and maintainability.
<!DOCTYPE html>
<html>
<body>
<div id="container">Content</div>
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<script>
// Helper functions
const selectId = (id) => document.getElementById(id);
const selectClass = (cls) => document.getElementsByClassName(cls);
const selectTag = (tag) => document.getElementsByTagName(tag);
// Usage
const mainDiv = selectId("container");
console.log(mainDiv.innerText);
const boxes = selectClass("box");
console.log(boxes.length);
</script>
</body>
</html>