🔁 Understanding Loops in JavaScript — A Quick Guide Loops are fundamental in JavaScript when you need to execute a block of code multiple times. Choosing the right loop can make your code more readable and efficient. Here are the most common types of loops in JavaScript 👇 1️⃣ "for" Loop – Best when you know how many times the loop should run. for (let i = 0; i < 5; i++) { console.log("Iteration:", i); } 2️⃣ "while" Loop – Runs as long as the condition remains true. let i = 0; while (i < 5) { console.log("Count:", i); i++; } 3️⃣ "do...while" Loop – Executes at least once before checking the condition. let i = 0; do { console.log("Value:", i); i++; } while (i < 5); 4️⃣ "for...of" Loop – Perfect for iterating over iterable objects like arrays, strings, or maps. const fruits = ["Apple", "Banana", "Mango"]; for (const fruit of fruits) { console.log(fruit); } 5️⃣ "for...in" Loop – Used to iterate over object keys. const user = { name: "Sujit", role: "Frontend Developer" }; for (let key in user) { console.log(key, user[key]); } 💡 Quick Tip: Use "for...of" for arrays and "for...in" for objects to keep your code clean and readable. Mastering loops helps you handle data structures, API responses, and complex logic more efficiently. #javascript #webdevelopment #frontend #codingtips #programming
JavaScript Loops: A Quick Guide
More Relevant Posts
-
🔁 Understanding Loops in JavaScript — A Quick Guide Loops are fundamental in JavaScript when you need to execute a block of code multiple times. Choosing the right loop can make your code more readable and efficient. Here are the most common types of loops in JavaScript 👇 1️⃣ "for" Loop – Best when you know how many times the loop should run. for (let i = 0; i < 5; i++) { console.log("Iteration:", i); } 2️⃣ "while" Loop – Runs as long as the condition remains true. let i = 0; while (i < 5) { console.log("Count:", i); i++; } 3️⃣ "do...while" Loop – Executes at least once before checking the condition. let i = 0; do { console.log("Value:", i); i++; } while (i < 5); 4️⃣ "for...of" Loop – Perfect for iterating over iterable objects like arrays, strings, or maps. const fruits = ["Apple", "Banana", "Mango"]; for (const fruit of fruits) { console.log(fruit); } 5️⃣ "for...in" Loop – Used to iterate over object keys. const user = { name: "Sujit", role: "Frontend Developer" }; for (let key in user) { console.log(key, user[key]); } 💡 Quick Tip: Use "for...of" for arrays and "for...in" for objects to keep your code clean and readable. Mastering loops helps you handle data structures, API responses, and complex logic more efficiently. #javascript #webdevelopment #frontend #codingtips #programming
To view or add a comment, sign in
-
💡 Pass by Value vs Pass by Reference in JavaScript (Simple Explanation) If you're learning JavaScript, understanding how data is passed is crucial 👇 🔹 Pass by Value (Primitives) When you assign or pass a primitive type (number, string, boolean, null, undefined, symbol, bigint), JavaScript creates a copy. let a = 10; let b = a; b = 20; console.log(a); // 10 console.log(b); // 20 👉 Changing b does NOT affect a because it's a copy. 🔹 Pass by Reference (Objects) When you work with objects, arrays, functions or date objects, JavaScript passes a reference (memory address). let obj1 = { name: "Ali" }; let obj2 = obj1; obj2.name = "Ahmed"; console.log(obj1.name); // Ahmed console.log(obj2.name); // Ahmed 👉 Changing obj2 ALSO affects obj1 because both point to the same object. 🔥 Key Takeaway Primitives → 📦 Copy (Independent) Objects → 🔗 Reference (Shared) 💭 Pro Tip To avoid accidental changes in objects, use: Spread operator {...obj} Object.assign() Understanding this concept can save you from hidden bugs in real-world applications 🚀 #JavaScript #WebDevelopment #Frontend #Programming #CodingTips
To view or add a comment, sign in
-
JavaScript prototypes clicked for me the moment I stopped thinking about copying and started thinking about linking. Here's the mental model that made it stick 👇 🔹 The core idea Every object in JavaScript has a hidden link to another object — its prototype. When you access a property, JS doesn't just look at the object itself. It walks the chain: Check the object Not found? Check its prototype Still not found? Check the prototype's prototype Keep going until null That's the prototype chain. Simple as that. 🔹 See it in action jsconst user = { name: "Aman" }; const admin = { isAdmin: true }; admin.__proto__ = user; console.log(admin.name); // "Aman" ✅ admin doesn't have name — but JS finds it one level up. 🔹 Why constructor functions use this jsfunction User(name) { this.name = name; } User.prototype.sayHi = function () { console.log(`Hi, I am ${this.name}`); }; Every User instance shares one sayHi method. Not copied — linked. That's free memory efficiency, built into the language. 🔹 Two things worth keeping straight prototype → a property on constructor functions __proto__ → the actual link on any object The modern, cleaner way to set that link: jsconst obj = Object.create(user); 🔹 Why bother understanding this? Because it shows up everywhere — class syntax, frameworks, unexpected undefined bugs, performance decisions. Prototypes aren't a quirk. They are the inheritance model. One line to remember: JS doesn't copy properties. It searches a chain of linked objects. #JavaScript #Frontend #WebDevelopment #Programming
To view or add a comment, sign in
-
🚨 JavaScript Gotcha: Objects as Keys?! Take a look at this 👇 const a = {}; const b = { key: 'b' }; const c = { key: 'c' }; a[b] = 123; a[c] = 456; console.log(a[b]); // ❓ 👉 What would you expect? 123 or 456? 💡 Actual Output: 456 🤯 Why does this happen? In JavaScript, object keys are always strings or symbols. So when you use an object as a key: a[b] → a["[object Object]"] a[c] → a["[object Object]"] Both b and c are converted into the same string: "[object Object]" ⚠️ That means: a[b] = 123 sets " [object Object] " → 123 a[c] = 456 overwrites it → 456 So finally: console.log(a[b]); // 456 🧠 Key Takeaways ✅ JavaScript implicitly stringifies object keys ✅ Different objects can collide into the same key ❌ Using objects as keys in plain objects is unsafe 🔥 Pro Tip If you want to use objects as keys, use a Map instead: const map = new Map(); map.set(b, 123); map.set(c, 456); console.log(map.get(b)); // 123 ✅ ✔️ Map preserves object identity ✔️ No unexpected overwrites 💬 Final Thought JavaScript often hides complexity behind simplicity. Understanding these small quirks is what separates a developer from an expert. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #Coding #JavaScriptTips #JSConfusingParts #DevelopersLife #CodeNewbie #LearnToCode #SoftwareEngineering #TechTips #CodeQuality #CleanCode #100DaysOfCode #ProgrammingTips #DevCommunity #CodeChallenge #Debugging #JavaScriptDeveloper #MERNStack #FullStackDeveloper #ReactJS #NodeJS #WebDevTips #CodingLife
To view or add a comment, sign in
-
-
JavaScript just got way more powerful (and cleaner) with this feature… Most developers still write strings like this: "Hello " + name + " you are " + age + " years old" Messy Hard to read Error-prone But there’s a better way: Template Literals (ES6) Now you can write: Hello ${name}, you are ${age} years old Clean. Simple. Powerful. Here’s why Template Literals are a game changer: String Interpolation No more + operator chaos Directly embed variables inside strings Multi-line Strings Write clean formatted text without \n Embed Expressions ${num1 + num2} ${isAdmin ? "Admin" : "Guest"} Function Calls inside Strings ${greet()} Advanced Level (Most developers don’t use this enough): Tagged Template Literals Customize how strings are processed String.raw Handle raw strings like file paths easily Real Talk: Template literals don’t just improve code They improve how you think while writing code Cleaner syntax = Better readability = Fewer bugs My Take: If you're still not using template literals properly you're writing JavaScript the hard way Pro Tip: Use template literals for: Dynamic UI content API responses Clean logging HTML rendering I recently explored this deeply and it changed how I write strings in JavaScript What about you? Are you using template literals daily or still using + ? Here is link to visit my blog: https://lnkd.in/dYiNa-bz Piyush Garg | Hitesh Choudhary | Anirudh Patel | Suraj Kameshvar Prasad #javascript #webdevelopment #coding #programming #frontend #developers #learninpublic
To view or add a comment, sign in
-
-
🚀 JavaScript Fundamentals Series — Part 1 Before learning frameworks, async code, or complex patterns… you need to understand the core building blocks of JavaScript. Everything in JavaScript starts with variables and data types. In this guide you'll learn: • var, let, and const differences • Primitive vs Reference types • How JavaScript stores data in memory • Why type coercion causes weird bugs • Common mistakes developers make If your foundation here is strong, the rest of JavaScript becomes MUCH easier. I wrote a full guide explaining it clearly with diagrams and examples. Read here 👇 https://lnkd.in/dz_TuuVT Hitesh Choudhary Chai Aur Code Piyush Garg Akash Kadlag #javascript #webdevelopment #coding #learnjavascript
To view or add a comment, sign in
-
🚀 Where to Use Spread (...) and Rest (...) Operators in JavaScript (Real Use Cases) Many developers know spread and rest… But the real question is 👉 Where should you actually use them? 🔹 Spread Operator (...) → “Expand Values” 👉 Use spread when you want to open / copy / merge data 1. Copy Arrays (Avoid Bugs) const arr = [1, 2, 3]; const copy = [...arr]; 👉 Without spread: const copy = arr; // ❌ same reference (danger) 2. Merge Arrays const a = [1, 2]; const b = [3, 4]; const result = [...a, ...b]; 👉 Very common in real apps 3. Update Objects (Immutability – VERY IMPORTANT in React) const user = { name: "Javascript" }; const updatedUser = { ...user, age: 21 }; 👉 Don’t mutate original object 4. Pass Array as Function Arguments const nums = [5, 10, 2]; Math.max(...nums); 5. Clone Objects const newUser = { ...user }; 👉 Used in state updates (React) 🔹 Rest Operator (...) → “Collect Values” 1. Functions with Unlimited Arguments function sum(...numbers) { return numbers.reduce((a, b) => a + b); } 👉 Flexible functions 2. Separate Values from Array const [first, ...rest] = [1, 2, 3, 4]; 👉 Extract first → collect remaining 3. Remove Properties from Object const user = { name: "Javascript", age: 21, city: "Hyd" }; const { name, ...others } = user; 👉 Useful for filtering data 4. Handling API Data const { id, ...userData } = response; 👉 Separate important fields >>>Spread = “Break it apart” >>> Rest = “Bring it together” “Both use ... , how do you differentiate?” It depends on context — >> If it’s expanding values → Spread >> If it’s collecting values → Rest Example: function demo(a, b, ...rest) { console.log(a, b, rest); } const arr = [1, 2, 3, 4]; demo(...arr); #JavaScript #WebDevelopment #Frontend #ReactJS #Coding #Developers #LearnJavaScript #100DaysOfCode
To view or add a comment, sign in
-
A tale of two JavaScript patterns and the bugs that catch you out 🐛 I've been revisiting the two main ways to create custom objects in JavaScript. Both achieve the same goal. Both have traps. Here's what I found: ES6 Class class Character { constructor(name) { this.name = name this.powers = [] } addPowers(power) { this.powers.push(power) console.log(`${this.name} has ${this.powers} Powers!`) } } Methods live outside the constructor, inside the class body. They land on the prototype automatically so every instance shares one copy rather than each carrying its own. Constructor Function function Character(name) { this.name = name this.powers = [] this.addPowers = function(power) { this.powers.push(power) console.log(`${this.name} has ${this.powers} Powers!`) } } Easy gotcha: write function addPowers() instead of this.addPowers = and the method becomes a private inner function completely invisible outside the constructor. Your code won't error on creation, it'll just silently fail when you try to call it. The class syntax is cleaner and harder to get wrong. But understanding constructor functions teaches you what's actually happening under the hood and makes legacy codebases far less scary. Worth noting: there is a third way Object.create() but I've not covered it here. It gives you very fine-grained control over the prototype chain, but it's significantly more verbose and rarely the first tool you'd reach for. Both patterns. Both worth knowing. Have you been caught out by either of these? Let me know below 👇 #JavaScript #WebDevelopment #CodingTips #OOP #LearnToCode #JSDevs #SoftwareEngineering
To view or add a comment, sign in
-
Gea.js: Burying the Virtual DOM and Writing 'Just JavaScript' 🚀 Developed by Armagan Amcalar, Gea.js is an ultra-lightweight (~13 KB) next-gen frontend framework that eliminates the Virtual DOM (VDOM) in favor of build-time optimizations and ES6 Proxy architecture. Built on the philosophy that "a framework shouldn't dictate a new language," it allows you to build high-performance, reactive interfaces using pure JavaScript/TypeScript without complex hook structures. Key Features: - Zero Virtual DOM: Transforms JSX into optimized native DOM calls during build-time; performs surgical patches without the overhead of VDOM diffing. - Proxy-Based Reactivity: No useState or signals required. Just use plain JS classes and objects; Gea's Proxy network detects changes and updates the DOM automatically. - Batteries-Included: Comes with a built-in router, state management, and SSR support. The router itself is just a "Store" object, eliminating the need for complex Context Providers. - Minimal Mental Overhead: Say goodbye to useEffect rules or dependency arrays. Simply update this.count++ and everything works as expected. https://lnkd.in/daVSpFyP
To view or add a comment, sign in
-
🚀 **Understanding JavaScript Variables Like a Pro (var vs let vs const)** If you're working with JavaScript, choosing the right keyword — `var`, `let`, or `const` — is more important than you think. Here’s a simple breakdown 👇 🔸 **var** * Function scoped * Can be re-declared * Can be re-assigned * Hoisted with `undefined` 👉 Mostly avoided in modern JavaScript due to unexpected behavior. --- 🔹 **let** * Block scoped * Cannot be re-declared in same scope * Can be re-assigned * Hoisted but in Temporal Dead Zone (TDZ) 👉 Best for variables that will change. --- 🔒 **const** * Block scoped * Cannot be re-declared * Cannot be re-assigned * Must be initialized at declaration 👉 Best for constants and safer code. --- 💡 **Pro Tip:** Always prefer `const` by default → use `let` when needed → avoid `var`. --- 📊 The attached diagram explains: * Scope hierarchy (Global → Function → Block) * Memory behavior * Key differences visually --- 🔥 Mastering these fundamentals helps you: ✔ Write cleaner code ✔ Avoid bugs ✔ Crack interviews easily --- #JavaScript #WebDevelopment #Frontend #Coding #Programming #Developers #LearnToCode #Tech #SoftwareEngineering #NodeJs #Json
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development