Now that you understand the fundamentals of JavaScript—like variables, functions, and control flow—it's time to bring your code to life. This section focuses on how JavaScript interacts with the browser, manipulates web content, handles events, and uses objects and arrays effectively.
1. The Document Object Model (DOM)
The DOM is a representation of your web page as a tree of objects. JavaScript can use the DOM to access and modify elements, attributes, and content in real time.
Selecting Elements
document.getElementById("title");
document.querySelector(".button");
document.querySelectorAll("p");
Changing Content
let title = document.getElementById("title");
title.textContent = "Updated Title";
Changing Styles
title.style.color = "blue";
title.style.fontSize = "28px";
2. Creating and Removing Elements
Creating Elements
let newDiv = document.createElement("div");
newDiv.textContent = "Hello World";
document.body.appendChild(newDiv);
Removing Elements
let removeMe = document.getElementById("old");
removeMe.remove();
3. Handling Events
JavaScript allows you to respond to user actions like clicks, key presses, or mouse movement.
Common Event Types
click
mouseover
keydown
submit
Adding an Event Listener
const button = document.querySelector("button");
button.addEventListener("click", function () {
alert("Button clicked!");
});
Using Arrow Function
button.addEventListener("click", () => {
console.log("Clicked!");
});
4. JavaScript Objects
Objects in JavaScript allow you to store related data and functions (methods) in a single structure.
Object Example
const user = {
name: "Jane",
age: 30,
greet: function () {
return "Hi, I'm " + this.name;
}
};
console.log(user.greet()); // Hi, I'm Jane
Accessing Properties
console.log(user.name); // Jane
user.age = 31;
Adding New Properties
user.email = "jane@example.com";
5. Working with Arrays
Arrays hold ordered lists of data. You can use them to group related values.
Creating Arrays
const fruits = ["apple", "banana", "cherry"];
Array Methods
push()
: Add item to endpop()
: Remove last itemshift()
: Remove first itemunshift()
: Add item to beginningforEach()
: Run a function for each itemmap()
: Create a new array by transforming each itemfilter()
: Return a new array based on condition
Example:
fruits.push("orange");
fruits.forEach(fruit => console.log(fruit));
Filtering Arrays
let numbers = [1, 2, 3, 4, 5];
let evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]
6. Form Validation with JavaScript
One of JavaScript’s most practical uses is validating user input in forms before it's submitted.
Example:
document.querySelector("form").addEventListener("submit", function (e) {
let emailInput = document.getElementById("email");
if (!emailInput.value.includes("@")) {
e.preventDefault();
alert("Please enter a valid email address.");
}
});
7. Working with the Browser
Alerts and Prompts
alert("This is an alert!");
let name = prompt("What is your name?");
confirm("Do you want to continue?");
Timing Functions
setTimeout(() => {
console.log("Delayed log");
}, 2000);
setInterval(() => {
console.log("This logs every 3 seconds");
}, 3000);
8. Local Storage (Storing Data in the Browser)
Local storage allows you to store small amounts of data in the user’s browser, even after they close the page.
localStorage.setItem("username", "Alice");
let savedName = localStorage.getItem("username");
console.log(savedName); // "Alice"
localStorage.removeItem("username");
9. Best Practices for Clean JavaScript Code
- Use
const
andlet
overvar
. - Break your code into small functions.
- Use meaningful variable and function names.
- Keep HTML, CSS, and JavaScript separate for clarity and maintainability.
- Use modern syntax: arrow functions, template literals, etc.
Template Literal Example:
let name = "Tom";
console.log(`Hello, ${name}!`);
10. What's Next?
You’ve just unlocked the power of JavaScript beyond the basics. You can now manipulate web content, handle user interaction, store data, and make your pages interactive and intelligent. From here, you can move on to:
- AJAX and Fetch API (load data without refreshing)
- Working with APIs and JSON
- Frameworks like React, Vue, or Angular
- Project-based learning: Build a to-do app, calculator, or mini game
Keep experimenting, building, and breaking things. JavaScript is a language best learned by doing. Happy coding!