DEV Community

Tamilselvan K
Tamilselvan K

Posted on

Day-30 What I Learned Today in JavaScript: Nested Loops, setAttribute, and Modulo

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}`);
  }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Row 1, Col 1
Row 1, Col 2
Row 1, Col 3
Row 2, Col 1
...
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Example:

const link = document.createElement("a");
link.setAttribute("href", "https://example.com");
link.setAttribute("target", "_blank");
link.textContent = "Visit Example";
document.body.appendChild(link);
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Example:

console.log(10 % 3); // 1
console.log(15 % 5); // 0
Enter fullscreen mode Exit fullscreen mode

Common Use Cases:

  • Check if a number is even or odd:
if (num % 2 === 0) {
  console.log("Even");
} else {
  console.log("Odd");
}
Enter fullscreen mode Exit fullscreen mode
  • 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.