JavaScript Basics - Variables, Loops, Arrays, Functions, Events, DOM Interactions, Alert/Confirm/Prompt, Rollover Images
1. Introduction to JavaScript
JavaScript is a high-level, interpreted programming language that is one of the core technologies of the World Wide Web. It enables interactive web pages and is an essential part of web applications. Unlike HTML (which structures content) and CSS (which styles content), JavaScript adds dynamic behavior and interactivity to websites. It runs directly in the user's web browser, allowing for immediate feedback and dynamic updates without needing to reload the entire page.
Initially developed by Netscape Communications, JavaScript was first released in 1995. It has since become a standard language for web development, with implementations in all major web browsers. Its versatility extends beyond the browser with environments like Node.js, allowing for server-side development as well.
2. Variables in JavaScript
Variables are fundamental building blocks in programming. They are containers for storing data values. In JavaScript, you can declare variables using the `var`, `let`, or `const` keywords.
2.1 Declaring Variables
The `let` keyword declares a block-scoped variable. Variables declared with `let` can be reassigned new values.
let name = "Alice"; let age = 30; let isStudent = false;
The `const` keyword declares a block-scoped variable whose value cannot be reassigned after initialization. It's used for values that should remain constant throughout the program.
const PI = 3.14159; const APP_NAME = "MyWebApp";
The `var` keyword also declares variables, but it has function scope or global scope, and can lead to hoisting issues. It's generally recommended to use `let` and `const` in modern JavaScript.
var greeting = "Hello";
2.2 Data Types
JavaScript supports several primitive data types:
- String: Represents a sequence of characters (e.g., "Hello World").
- Number: Represents numeric values (integers and floating-point numbers, e.g., 10, 3.14).
- Boolean: Represents a truth value (either
trueorfalse). - Undefined: Represents a variable that has been declared but not yet assigned a value.
- Null: Represents the intentional absence of any object value.
- Symbol: A unique and immutable primitive value. (Introduced in ES6)
- BigInt: Represents whole numbers larger than the maximum safe integer. (Introduced in ES2020)
JavaScript also has a complex data type:
- Object: A collection of properties, where each property is a key-value pair.
2.3 Variable Naming Rules
Variable names must:
- Start with a letter, an underscore (_), or a dollar sign ($).
- Subsequent characters can be letters, numbers, underscores, or dollar signs.
- Be case-sensitive (
myVariableis different frommyvariable). - Cannot be a reserved JavaScript keyword (e.g.,
if,for,while).
3. Loops in JavaScript
Loops are used to execute a block of code repeatedly. They are essential for iterating over data structures like arrays or performing repetitive tasks.
3.1 For Loop
The for loop is the most common type of loop. It's used when you know how many times you want to execute a statement or a block of statements.
for (initialization; condition; final-expression) {
// code to be executed
}
Example: Printing numbers from 1 to 5.
for (let i = 1; i <= 5; i++) {
console.log(i); // Outputs 1, 2, 3, 4, 5
}
- initialization: Executes once before the loop starts (e.g.,
let i = 1). - condition: Evaluated before each iteration. If true, the loop continues; if false, the loop terminates (e.g.,
i <= 5). - final-expression: Executes at the end of each iteration (e.g.,
i++, which incrementsi).
3.2 While Loop
The while loop executes a block of code as long as a specified condition is true.
while (condition) {
// code to be executed
}
Example:
let count = 0;
while (count < 3) {
console.log("Count is: " + count);
count++; // Important to increment to avoid an infinite loop
}
// Outputs:
// Count is: 0
// Count is: 1
// Count is: 2
A while loop is useful when you don't know in advance how many times the loop needs to run.
3.3 Do-While Loop
The do-while loop is similar to the while loop, but it executes the block of code once before checking the condition. This guarantees that the loop body will run at least once.
do {
// code to be executed
} while (condition);
Example:
let j = 5;
do {
console.log("j is: " + j);
j++;
} while (j < 3);
// Outputs:
// j is: 5
Notice that "j is: 5" is printed even though the condition (j < 3) is false initially.
3.4 For...in Loop
The for...in loop iterates over the properties of an object.
for (variable in object) {
// code to be executed for each property
}
Example:
const person = { firstName: "John", lastName: "Doe", age: 30 };
for (let key in person) {
console.log(key + ": " + person[key]);
}
// Outputs:
// firstName: John
// lastName: Doe
// age: 30
3.5 For...of Loop
The for...of loop iterates over the values of an iterable object (like Arrays, Strings, Maps, Sets, etc.).
for (variable of iterable) {
// code to be executed for each value
}
Example:
const colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}
// Outputs:
// red
// green
// blue
for: Use when you know the number of iterations.while: Use when the number of iterations depends on a condition.do-while: Likewhile, but guarantees at least one execution.for...in: For looping through object properties (keys).for...of: For looping through values of iterable objects (like arrays).
4. Arrays in JavaScript
An array is a special variable, which can hold more than one value at a time. It's a type of object used to store ordered collections of data.
4.1 Creating Arrays
Arrays can be created using array literals (square brackets) or the Array constructor.
// Using array literal (most common) let fruits = ["Apple", "Banana", "Cherry"]; // Using Array constructor let numbers = new Array(1, 2, 3, 4, 5);
4.2 Accessing Array Elements
Array elements are accessed by their index, which starts at 0.
let firstFruit = fruits[0]; // "Apple" let secondFruit = fruits[1]; // "Banana" let lastFruit = fruits[fruits.length - 1]; // "Cherry" (length - 1 gives the last index)
4.3 Array Properties and Methods
Arrays have useful properties and methods:
length: Returns the number of elements in the array.push(): Adds one or more elements to the end of an array and returns the new length.pop(): Removes the last element from an array and returns that element.unshift(): Adds one or more elements to the beginning of an array and returns the new length.shift(): Removes the first element from an array and returns that element.splice(): Changes the contents of an array by removing or replacing existing elements and/or adding new elements.slice(): Returns a shallow copy of a portion of an array into a new array object.indexOf(): Returns the first index at which a given element can be found in the array, or -1 if it is not present.join(): Joins all elements of an array into a string.forEach(): Executes a provided function once for each array element.
Example using methods:
let colors = ["red", "green"];
colors.push("blue"); // colors is now ["red", "green", "blue"]
let removedColor = colors.pop(); // removedColor is "blue", colors is now ["red", "green"]
colors.unshift("yellow"); // colors is now ["yellow", "red", "green"]
let firstColor = colors.shift(); // firstColor is "yellow", colors is now ["red", "green"]
colors.forEach(function(color, index) {
console.log("Color at index " + index + ": " + color);
});
4.4 Multidimensional Arrays
Arrays can contain other arrays, creating multidimensional arrays.
let matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; console.log(matrix[1][2]); // Outputs 6 (second row, third column)
5. Functions in JavaScript
Functions are blocks of reusable code designed to perform a particular task. They help in breaking down programs into smaller, modular pieces, making the code more organized and readable.
5.1 Declaring Functions
Functions can be declared using the function keyword.
function functionName(parameter1, parameter2, ...) {
// code to be executed
return value; // Optional
}
Example: A function to add two numbers.
function addNumbers(num1, num2) {
let sum = num1 + num2;
return sum;
}
5.2 Calling Functions
To execute a function, you "call" it by using its name followed by parentheses, passing any required arguments.
let result = addNumbers(5, 10); // result will be 15 console.log(result);
5.3 Function Expressions
Functions can also be assigned to variables. This is known as a function expression.
const multiplyNumbers = function(x, y) {
return x * y;
};
let product = multiplyNumbers(4, 6); // product will be 24
5.4 Arrow Functions (ES6)
Arrow functions provide a more concise syntax for writing function expressions.
// With parameters
const subtractNumbers = (a, b) => {
return a - b;
};
// With a single parameter, parentheses are optional
const square = num => {
return num * num;
};
// If the function body contains only a single expression, the curly braces and 'return' keyword can be omitted
const cube = num => num * num * num;
let difference = subtractNumbers(20, 7); // 13
let squaredValue = square(9); // 81
let cubedValue = cube(3); // 27
5.5 Scope of Functions
Variables declared inside a function are local to that function (local scope), meaning they can only be accessed from within that function. Variables declared outside any function are global.
6. Events in JavaScript
Events are actions that happen in the web page, such as a user clicking a button, typing a character, or moving the mouse. JavaScript allows you to respond to these events.
6.1 Common Events
Some common events include:
click: Occurs when an element is clicked.mouseover: Occurs when the mouse pointer moves over an element.mouseout: Occurs when the mouse pointer moves out of an element.keydown: Occurs when a key is pressed down.keyup: Occurs when a key is released.submit: Occurs when a form is submitted.load: Occurs when the page or an element (like an image) has finished loading.change: Occurs when the value of an input element (like a checkbox, radio button, or select box) is changed.
6.2 Event Handling
Event handling involves attaching a function (an event handler) to an element that will be executed when a specific event occurs on that element.
6.2.1 Inline Event Handlers (Not Recommended)
You can add event handlers directly in HTML attributes. This is generally discouraged for larger applications as it mixes HTML and JavaScript logic.
<button onclick="alert('Button clicked!')">Click Me</button>
6.2.2 Using JavaScript Event Listeners
The modern and recommended way is to use JavaScript's `addEventListener()` method. This keeps your HTML clean and your JavaScript organized.
<button id="myButton">Click Me</button>
<script>
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
alert('Button was clicked using addEventListener!');
});
</script>
The `addEventListener()` method takes two main arguments: the event type (e.g., `'click'`) and the function to execute when the event occurs.
6.3 Event Object
When an event occurs, the browser creates an event object that contains information about the event (e.g., mouse coordinates, which key was pressed). This object is automatically passed to the event handler function.
const link = document.getElementById('myLink');
link.addEventListener('click', function(event) {
event.preventDefault(); // Prevents the default action of the event (e.g., following a link)
console.log('Link clicked at coordinates:', event.clientX, event.clientY);
});
7. DOM Interactions
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page structure as a tree of objects (nodes). JavaScript can interact with the DOM to dynamically change the content, structure, and style of a web page.
7.1 Selecting Elements
You need to select an element from the HTML document before you can interact with it.
document.getElementById('id'): Selects a single element by its unique ID.document.querySelector('selector'): Selects the first element that matches a CSS selector (e.g.,'#myId','.myClass','p').document.querySelectorAll('selector'): Selects all elements that match a CSS selector, returning a NodeList.document.getElementsByClassName('className'): Selects all elements with a specific class name.document.getElementsByTagName('tagName'): Selects all elements with a specific tag name.
Example:
const header = document.getElementById('main-header');
const firstParagraph = document.querySelector('p');
const allListItems = document.querySelectorAll('ul li');
7.2 Modifying Elements
Once an element is selected, you can change its content, attributes, and styles.
- Changing Text Content:
element.textContent: Sets or gets the text content of an element and its descendants.element.innerHTML: Sets or gets the HTML content within an element. Be cautious with user-provided input here to prevent XSS attacks.
- Changing Attributes:
element.setAttribute('attribute', 'value'): Sets an attribute.element.getAttribute('attribute'): Gets an attribute's value.- Direct property access (e.g.,
img.src,a.href).
- Changing Styles:
element.style.property = 'value': Modifies inline styles (e.g.,header.style.color = 'blue';).- Adding/removing CSS classes:
element.classList.add('className'),element.classList.remove('className'),element.classList.toggle('className'). This is often preferred for managing styles.
Example:
const welcomeMessage = document.getElementById('welcome');
welcomeMessage.textContent = "Welcome to our dynamic page!";
const logoImage = document.querySelector('.logo');
logoImage.src = 'new-logo.png';
logoImage.alt = 'New Company Logo';
const mainSection = document.getElementById('main-content');
mainSection.classList.add('highlight');
7.3 Creating and Appending Elements
You can create new HTML elements and add them to the page.
// 1. Create the element
const newParagraph = document.createElement('p');
// 2. Set its content or attributes
newParagraph.textContent = "This is a dynamically added paragraph.";
// 3. Append it to an existing element in the DOM
const container = document.getElementById('content-container');
container.appendChild(newParagraph);
7.4 Removing Elements
You can remove elements from the DOM.
const elementToRemove = document.getElementById('old-section');
if (elementToRemove) {
elementToRemove.remove(); // Modern way
// Or: elementToRemove.parentNode.removeChild(elementToRemove); // Older way
}
8. Alert, Confirm, and Prompt Dialogs
These are simple built-in JavaScript functions that create modal dialog boxes in the browser to interact with the user.
8.1 alert()
Displays an alert box with a specified message and an OK button. It's used to show information or warnings to the user.
alert("This is an important message!");
The script execution pauses until the user clicks OK.
8.2 confirm()
Displays a dialog box with a specified message, a Cancel button, and an OK button. It's used to ask the user for confirmation.
let userResponse = confirm("Are you sure you want to proceed?");
if (userResponse) {
console.log("User clicked OK.");
} else {
console.log("User clicked Cancel.");
}
confirm() returns true if the user clicks OK and false if the user clicks Cancel. Script execution pauses until the user responds.
8.3 prompt()
Displays a dialog box that prompts the user for input. It includes a message, an input field, and OK/Cancel buttons.
let userName = prompt("Please enter your name:", "Guest"); // "Guest" is the default value
if (userName !== null && userName !== "") {
console.log("Hello, " + userName + "!");
} else {
console.log("User did not enter a name or clicked Cancel.");
}
prompt() returns the string entered by the user if they click OK, or null if they click Cancel. Script execution pauses.
Note: While these dialogs are simple, they block the user interface and are often considered intrusive. For more sophisticated user interactions, custom modal dialogs built with HTML, CSS, and JavaScript are preferred.
9. Rollover Images
Rollover images are a common web design technique where an image changes its appearance when the user's mouse pointer hovers over it. This is typically achieved using JavaScript to swap between two different image sources.
9.1 Concept
You have two versions of an image:
- The default image (normal state).
- The rollover image (hover state).
JavaScript listens for the `mouseover` event (when the mouse enters the image area) and changes the image's `src` attribute to the rollover image. It also listens for the `mouseout` event (when the mouse leaves the image area) and changes the `src` back to the default image.
9.2 Implementation Steps
9.2.1 HTML Structure
You'll need an `` tag, typically with an `id` for easy selection, and `src` and `alt` attributes.
<img id="myImage" src="image_normal.jpg" alt="My Image">
9.2.2 Preloading Images (Optional but Recommended)
To ensure a smooth transition without any delay the first time the mouse hovers, it's good practice to preload the rollover image into memory.
<script> const normalImageSrc = 'image_normal.jpg'; const rolloverImageSrc = 'image_hover.jpg'; // Preload the rollover image const rolloverImage = new Image(); rolloverImage.src = rolloverImageSrc; </script>
9.2.3 JavaScript Event Handlers
Use `addEventListener` to attach functions to `mouseover` and `mouseout` events.
<script>
const normalImageSrc = 'image_normal.jpg';
const rolloverImageSrc = 'image_hover.jpg';
const rolloverImage = new Image();
rolloverImage.src = rolloverImageSrc;
const imageElement = document.getElementById('myImage');
// Mouseover event: change image to rollover state
imageElement.addEventListener('mouseover', function() {
imageElement.src = rolloverImageSrc;
});
// Mouseout event: change image back to normal state
imageElement.addEventListener('mouseout', function() {
imageElement.src = normalImageSrc;
});
</script>
9.3 Alternative: CSS Hover Effect
For simple image rollovers, CSS provides a much simpler and often more performant solution using the `:hover` pseudo-class. JavaScript is typically used when the change needs to be more complex or triggered by events other than just hovering.
<style>
#myImage {
content: url('image_normal.jpg'); /* Sets the default image */
transition: content 0.3s ease; /* Smooth transition */
}
#myImage:hover {
content: url('image_hover.jpg'); /* Changes image on hover */
}
</style>
<img id="myImage" src="image_normal.jpg" alt="My Image">
Note: The CSS `content` property with `url()` is the modern way to achieve this effect directly with CSS for `` tags. Older methods involved using background images or pseudo-elements.
- CSS :hover: Use for simple image swaps. It's more efficient and requires less code.
- JavaScript: Use when the rollover logic is more complex, involves multiple images, requires preloading specific assets, or is tied to other JavaScript interactions.