JavaScript Basics: Interactive Web
JavaScript (JS) is a programming language that enables interactive web pages. It is an essential part of web applications.
1. Variables
Variables are containers for storing data values.
const: For values that will not change. (Recommended default)let: For values that might change later.
const maxScore = 100;
let currentScore = 0;
console.log(maxScore); // Output to console
2. Functions
A function is a block of code designed to perform a particular task.
function greet(name) {
return "Hello, " + name;
}
const message = greet("Alice");
console.log(message); // "Hello, Alice"
3. DOM Manipulation & Events
The DOM (Document Object Model) allows JS to access and change HTML elements.
Selecting Elements
const button = document.querySelector("#my-btn");
const text = document.querySelector(".text-content");
Event Listeners
Execute code when a user interacts with an element (e.g., clicks).
button.addEventListener("click", function() {
text.style.color = "red";
text.innerText = "Button Clicked!";
});
4. Conditionals
Perform different actions based on different conditions.
let age = 18;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}