JavaScript Basic Part: 3

 

Loops DOM Manipulation Events Error Handling  and  Async Basics  The Complete Guide






Welcome to the final part of our JavaScript Basics series. In Part 1 we covered Variables Data Types Operators Type Conversion Scope and Hoisting. In Part 2 we covered Functions Arrays Objects Closures Destructuring and the Spread/Rest operators. This final part goes beyond Loops DOM Manipulation and Events to also cover Switch Statements Error Handling with try/catch JSON and an introduction to Promises and async/await  rounding out a genuinely complete beginner to intermediate foundation.

Table of Contents

1. Understanding Loops

2. Types of Loops in JavaScript

3. Loop Control: break and continue

4. The Switch Statement

5. Understanding the DOM

6. DOM Manipulation Techniques

7. Understanding Events

8. Error Handling with try/catch

9. Working with JSON

10. Introduction to Promises and async/await

11. Practical Example: Putting It All Together

12. Frequently Asked Questions

13. Practice Exercises


1. Understanding Loops

A loop repeats a block of code multiple times without manually rewriting it essential for processing arrays generating repeated elements, and handling repetitive logic.

for (let i = 1; i <= 5; i++) 

{

console.log(`This is loop number ${i}`);

}

2. Types of Loops in JavaScript

The for Loop

for (let i = 0; i < 5; i++) {

console.log(i);

}

// 0, 1, 2, 3, 4

Three parts

initialization                                                                                                                                        condition                                                                                                                                                increment.

The while Loop

let count = 0;

while (count < 5)

 {

console.log(count);

count++;

}

Used when the number of iterations is not known in advance. Always ensure the condition eventually becomes false to avoid an infinite loop.

The do...while Loop

let num = 1;

do {

console.log(num);

num++;

} while (num <= 5);

Runs the block at least once, even if the condition is false from the start.

The for...of Loop (Arrays)

const fruits = ["Apple", "Banana", "Mango"];

for (const fruit of fruits) {

console.log(fruit);

}

The for...in Loop (Objects)

const car = { brand: "Honda", model: "Civic", year: 2023 };

for (const key in car) {

console.log(`${key}: ${car[key]}`);

}

3. Loop Control: break and continue

// break — stops the loop entirely

for (let i = 1; i <= 10; i++)

 {

if (i = 5) break;

console.log(i);

}

// 1, 2, 3, 4

// continue skips just this iteration

for (let i = 1; i <= 5; i++) {

if (i = 3) continue;

console.log(i);

}

// 1, 2, 4, 5

4. The Switch Statement

An alternative to long if...else if chains ideal when comparing one variable against many possible  fixed values.

const day = "Monday";

switch (day) {

case "Monday":

console.log("Start of the work week");

break;

case "Friday":

console.log("Almost the weekend!");

break;

case "Sunday":

console.log("Rest day");

break;

default:

console.log("Just another day");

}


The break keyword is critical without it execution falls through into the next case which is a common beginner bug.

5. Understanding the DOM

DOM stands for Document Object Model. When a browser loads HTML it builds a live tree like structure of objects representing the page  and JavaScript can read and modify this structure in real time without reloading the page.

<body>

<h1 id="title">Welcome</h1>

<p class="description">This is a

paragraph.</p>

</body>

6. DOM Manipulation Techniques

Selecting Elements

const title = document.getElementById("title");

const items = document.getElementsByClassName("description");

const heading = document.querySelector("#title");

const allParagraphs = document.querySelectorAll("p");

querySelector returns the first match;

querySelectorAll returns all matches.

Changing Content

title.textContent = "Welcome to My Website!";

title.innerHTML = "Welcome <strong>Everyone</strong>!";

Changing Styles

title.style.color = "blue";

title.style.fontSize = "32px";

Changing Attributes

const image = document.querySelector("img");

image.setAttribute("src", "new-image.jpg");

image.setAttribute("alt", "Description");

Managing CSS Classes

title.classList.add("highlight");

title.classList.remove("highlight");

title.classList.toggle("active");

Creating and Removing Elements

const newParagraph = document.createElement("p");

newParagraph.textContent = "Added dynamically with JavaScript!";

document.body.appendChild(newParagraph);

document.querySelector(".description").remove( );

7. Understanding Events

An event is any action that occurs in the browser  a click a keystroke a scroll or a page load  that JavaScript can listen for and respond to.

Adding Event Listeners

const button = document.querySelector("#myButton");

button.addEventListener("click", () => {

console.log("Button clicked!");

});

Common Event Types

Event Triggered When click An element is clicked mouseover /mouseout Mouse enters/leaves an element

key down  

A key is pressed submit A form is submitted change An inputs value changes load A page or resource finishes loading scroll The page or an element is scrolled.

The Event Object

const input = document.querySelector("#username");

input.addEventListener("input", (event) =>

{

console.log("Current value:", event.target.value);

});

Preventing Default Behavior

const form = document.querySelector("#myForm");

form.addEventListener("submit", (event) =>

{

event.preventDefault();

console.log("Handled with JavaScript

instead of reloading the page");

});

8. Error Handling with try/catch

Real applications need to handle unexpected failures gracefully instead of crashing entirely.

try {

let result = riskyFunction(); // may not exist / may throw

console.log(result);

} catch (error) {

console.log("Something went wrong:", error.message);

} finally {

console.log("This always runs, error or

not");

}


You can also manually throw custom errors

function checkAge(age) {

if (age < 18) {

throw new Error("Must be 18 or older");

}

return "Access granted";

}

try {

console.log(checkAge(15));

} catch (error) {

console.log(error.message); // Must be 18

or older

}

This pattern is essential for form validation API calls and any code where things can realistically fail.

9. Working with JSON

JSON (JavaScript Object Notation) is the standard format for exchanging data between a browser and a server.

// Converting a JS object to a JSON string (for sending data)

const user = { name: "Aman", age: 28 };

const jsonString = JSON.stringify(user);

console.log(jsonString); //

{"name":"Aman","age":28};

// Converting a JSON string back to a JS object (for receiving data)

const parsedUser = JSON.parse(jsonString);

console.log(parsedUser.name); // Aman


Virtually every API you will interact with as a developer sends and receives data in JSON format making this a critical practical skill.

10. Introduction to Promises and async/await

Modern JavaScript often deals with tasks that take time  like fetching data from a server. Promises help manage this without freezing the rest of your page.

Basic Promise

const fetchData = new Promise((resolve, reject) => {

const success = true;

if (success) {

resolve("Data fetched successfully!");

} else {

reject("Failed to fetch data");

}

})

fetchData

.then((message) => console.log(message))

.catch((error) => console.log(error));

async/await (Modern, Cleaner Syntax)

async function getUserData( ) {

try {

const response = await

fetch("https://api.example.com/user");

const data = await response.json();

console.log(data);

} catch (error) {

console.log("Error fetching data:", error);

}

}

async/await is simply a more readable way to work with Promises and its the standard approach used in modern JavaScript codebases for handling API calls.

11. Practical Example: Putting It All Together

A simple real world style dynamic task list combining loops DOM manipulation events and error handling.

<ul id="taskList"></ul>

<input type="text" id="taskInput" placeholder="Enter a task" />

<button id="addTaskBtn">Add Task</button>

const taskInput = document.querySelector("#taskInput");

const addTaskBtn = document.querySelector("#addTaskBtn");

const taskList = document.querySelector("#taskList");

addTaskBtn.addEventListener("click", () =>

{

try {

const taskText = taskInput.value.trim();

if (taskText === "") {

throw new Error("Task cannot be

empty");

}

const listItem = document.createElement("li");

listItem.textContent = taskText;

taskList.appendChild(listItem);

taskInput.value = "";

} catch (error) {

alert(error.message);

}

});

This snippet reflects patterns used in real production apps  to do lists comment sections shopping carts and form driven interfaces.

12. Frequently Asked Questions

Q: When should I use a for loop vs. forEach?

Use for when you need break / continue control or need to loop backward use forEach for simple readable iteration over arrays.

Q: Whats the difference between innerHTML and textContent?

textContent treats content as plain text (safer) while innerHTML parses it as HTML only use innerHTML with trusted content to avoid security risks like XSS.

Q: Why use async/await instead of .then()?

async/await reads like synchronous code making it easier to follow especially when chaining multiple asynchronous operations together.

Q: Do I need to learn Promises as a beginner?

Yes  nearly all real-world JavaScript involves fetching data from APIs and Promises/async await are the standard tools for that.

13. Practice Exercises

1. Write a for loop that prints all even numbers from 1 to 20.

2. Build a switch statement that prints a message based on a grade letter (A B C D F).

3. Select an element by ID and change its text content and background color.

4. Create a button that adds a new list item to a page each time its clicked.

5. Write a try/catch block that throws a custom error if a user entered number is negative.

6. Write a simple async function that simulates fetching data using setTimeout and a Promise .



Conclusion

JavaScript Basics series covering:

Part 1: Variables Data Types Operators Type Conversion Scope Hoisting

Part 2: Functions Arrays Objects Closures the this keyword Destructuring Spread/Rest

 Part 3: Loops Switch Statements DOM Manipulation Events Error Handling JSON Promises & async/await

In this post covers what most developers use daily in real projects  and prepares you well for frameworks like React Vue or Node.js. From here the best next step is building small real projects a  to do list  a calculator or a simple weather app using a public API.

Consistency beats intensity code a little every day and these concepts will become second nature faster than you expect.

Post a Comment

ON

Previous Post Next Post