Today, I explored some foundational but powerful concepts in JavaScript. Let’s break them down with examples to make them stick!
1. Nested for
Loops
A nested loop is simply a loop inside another loop. You’ll often use these when working with grids, tables, or multi-dimensional data (like 2D arrays).
Example: Print a 3x3 grid of numbers
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`Row ${i}, Col ${j}`);
}
}
Output:
Row 1, Col 1
Row 1, Col 2
Row 1, Col 3
Row 2, Col 1
...
Why it’s useful: You can loop through tables, matrices, or repeat tasks in a structured pattern.
2. setAttribute
– Setting HTML Element Attributes
In JavaScript, we can use setAttribute
to modify or assign new attributes to HTML elements.
Syntax:
element.setAttribute(attributeName, value);
Example:
const link = document.createElement("a");
link.setAttribute("href", "https://example.com");
link.setAttribute("target", "_blank");
link.textContent = "Visit Example";
document.body.appendChild(link);
This creates a clickable link that opens in a new tab.
3. Modulo Operator (%
)
The modulo operator gives you the remainder of a division.
Syntax:
let result = a % b;
Example:
console.log(10 % 3); // 1
console.log(15 % 5); // 0
Common Use Cases:
- Check if a number is even or odd:
if (num % 2 === 0) {
console.log("Even");
} else {
console.log("Odd");
}
- Looping in patterns (e.g., alternate row colors, repeating indexes, etc.)
Wrap-Up
- Nested loops help when working with grids or repeating structures.
-
setAttribute
allows you to dynamically modify elements in the DOM. - The modulo operator is great for patterns, conditions, and logic involving remainders.
Top comments (1)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.