JavaScript Loops and Array Methods Explained

🚀 Types of Loops in JavaScript and Array Methods (Part:2) 👉 A loop is used to execute a block of code repeatedly until a condition is met. Example: Instead of writing this ❌ console.log("Hello"); console.log("Hello"); console.log("Hello"); You can use a loop ✅ for (let i = 0; i < 3; i++) { console.log("Hello"); } ⚙️ How a loop works A loop has 3 parts: 1️⃣ Initialization → starting point 2️⃣ Condition → when to stop 3️⃣ Increment/Decrement → how it moves JavaScript provides multiple ways to loop through data: 1️⃣ for loop (most common) for (let i = 0; i < 5; i++) { console.log(i); } ✔️ Best when you know how many times to run ✔️ Full control over loop 2️⃣ while loop let i = 0; while (i < 5) { console.log(i); i++; } ✔️ Runs while condition is true ✔️ Useful when iterations are unknown. 3️⃣ do...while loop let i = 0; do { console.log(i); i++; } while (i < 5); ✔️ Runs at least once, even if condition is false. 4️⃣ for...of loop let arr = [10, 20, 30]; for (let value of arr) { console.log(value); } ✔️ Best for arrays ✔️ Gives values directly 5️⃣ for...in loop let obj = { name: "Javascript", age: 20 }; for (let key in obj) { console.log(key); } ✔️ Used for objects ✔️ Gives keys 6️⃣ forEach() (array method) let arr = [10, 20, 30]; arr.forEach((value) => { console.log(value); }); ✔️ Clean and readable ✔️ Only works with arrays 🚀 JavaScript Array Methods (push, pop, shift, unshift) Arrays are powerful… but these 4 methods make them super useful 🔥 🧠 Let’s say we have: let arr = [10, 20, 30]; 1️⃣ push() → Add at the end arr.push(40); console.log(arr); // [10, 20, 30, 40] 👉 Adds element to the end of array 2️⃣ pop() → Remove from the end arr.pop(); console.log(arr); // [10, 20, 30] 👉 Removes the last element 3️⃣ shift() → Remove from the start arr.shift(); console.log(arr); // [20, 30] 👉 Removes the first element 4️⃣ unshift() → Add at the start arr.unshift(5); console.log(arr); // [5, 20, 30] 👉 Adds element to the beginning Looping through Arrays: 1️⃣ for loop (classic way) for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } ✔️ Full control over loop ✔️ Can use break and continue ✔️ Works with any logic 2️⃣ forEach() (modern way) arr.forEach((value, index) => { console.log(value); }); 👉 Automatically loops through array ✔️ Cleaner and more readable ✔️ Less code ❌ Cannot break or stop early #JavaScript #Frontend #WebDevelopment #Coding #LearnInPublic

To view or add a comment, sign in

Explore content categories