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
JavaScript Patterns: ES6 Class vs Constructor Function
More Relevant Posts
-
🚨 JavaScript Challenge — 90% Get This Wrong No long questions. Just pure JavaScript. 👇 Answer before checking comments. 🧠 𝟭. 𝗪𝗵𝗮𝘁 𝘄𝗶𝗹𝗹 𝘁𝗵𝗶𝘀 𝗹𝗼𝗴? console.log(0.1 + 0.2 === 0.3); Yes or No? And why? ⚡ 𝟮. 𝗣𝗿𝗲𝗱𝗶𝗰𝘁 𝘁𝗵𝗲 𝗼𝘂𝘁𝗽𝘂𝘁 console.log("5" - 3); console.log("5" + 3); Same inputs. Different results. Explain. 🔥 𝟯. 𝗧𝗵𝗶𝘀 𝗼𝗻𝗲 𝗯𝗿𝗲𝗮𝗸𝘀 𝗯𝗿𝗮𝗶𝗻𝘀 console.log([] == ![]); True or False? (No guessing — explain it.) 🧩 𝟰. 𝗢𝘂𝘁𝗽𝘂𝘁? const obj = { a: 1 }; Object.freeze(obj); obj.a = 2; console.log(obj.a); Does it change or not? 🚀 𝟱. 𝗙𝗶𝗻𝗮𝗹 𝘁𝗿𝗮𝗽 console.log(typeof undefined); console.log(typeof null); Why is JavaScript like this? 😄 💬 Be honest — how many did you get 100% correct without Googling? Drop your answers below 👇 Let’s see who actually understands JS fundamentals. I’ll post detailed explanations in the next post. Follow if you don’t want to miss it 🔥 #javascript #frontend #codingchallenge #webdevelopment #techinterview #DAY86
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
-
-
🚀 Understanding Recursion + Finding Maximum in Nested Arrays (JavaScript) Today I practiced a powerful concept in JavaScript — recursion with nested arrays — and used it to solve a real problem: 👉 Find the maximum number from a deeply nested array 💡 Example: [1, 0, 7, [2, 5, [10], 4]] 🔍 Approach I followed: ✅ Step 1: Used recursion to flatten the nested array If the element is a number → push into result If it’s an array → call the same function again ✅ Step 2: After flattening, used a loop to find the maximum value 🧠 Key Learnings: • Each recursive call creates its own memory (execution context) • Data is temporarily stored in the call stack • The return keyword helps pass results back step by step • Without capturing the returned value, recursion results can be lost • Breaking problems into smaller parts makes complex logic easier ⚡ Final Output: 👉 Maximum number: 10 💬 This exercise really helped me understand: How recursion works internally How data flows through function calls Difference between primitive and reference types #JavaScript #Recursion #ProblemSolving #WebDevelopment #CodingJourney
To view or add a comment, sign in
-
JavaScript in 2026: The Dev Update You Didn't Know You Needed ECMAScript continues to evolve, and this year's updates are particularly noteworthy for JavaScript developers. Here’s a comprehensive overview of what’s new, what’s on the horizon, and why it matters. 1. Temporal API — The Biggest JS Feature in Years (ES2026) Date handling in JavaScript has faced challenges since 1995. With the Temporal API, that’s changing. const now = Temporal.Now.zonedDateTimeISO("Asia/Kolkata"); console.log(now.toLocaleString()); // Correct. Always. 2. using keyword — Automatic Resource Cleanup (ES2026) This feature simplifies resource management in asynchronous functions. async function saveData() { await using file = new FileHandle("output.txt"); await file.write("hello"); // file auto-closed here, even on error } No more worries about forgetting to close database connections or file handles. The runtime ensures cleanup when the variable goes out of scope, which is a significant improvement for server-side Node.js development. 3. Iterator Helpers — Lazy Evaluation (ES2025) This update enhances efficiency by allowing lazy evaluation without creating extra arrays. // Old way: creates 3 new arrays array.map(x => x*2).filter(x => x>10).slice(0, 3); // New way: zero extra arrays, stops after 3 Iterator.from(array).map(x => x*2).filter(x => x>10).take(3).toArray(); This feature works seamlessly with Sets, Maps, Generators, and any iterable, improving performance and memory usage. Additional updates include: - Array.fromAsync() — Collect async generator results into an array effortlessly - Iterator.concat() — Lazily iterate across multiple pages/sources - Error.isError() — Reliably detect real Error #JavaScript #ECMAScript2026 #WebDevelopment #TypeScript #FrontendDev #NodeJS #Programming #SoftwareEngineering #TechNews #CodingLife
To view or add a comment, sign in
-
-
🚀 Day 3/100 — Closures in JavaScript (Used Everywhere in Production) Continuing my 100 Days of JavaScript & TypeScript challenge. Today I explored one of the most powerful (and often misunderstood) concepts in JavaScript: 👉 Closures ⸻ 📌 What is a Closure? A closure is created when a function remembers variables from its outer scope, even after that outer function has finished executing. In simple terms: A function + its lexical environment = Closure ⸻ 📌 Example function createCounter() { let count = 0; return function () { count++; return count; }; } const counter = createCounter(); console.log(counter()); // 1 console.log(counter()); // 2 Even though createCounter() has finished execution, the inner function still has access to count. That’s a closure in action. ⸻ 🧠 Why This Works Because JavaScript functions capture their surrounding scope at the time they are created. This is called the lexical scope. ⸻ 💡 Real-World Use Cases Closures are everywhere in production systems: • Data privacy (encapsulation without classes) • Creating reusable functions • Maintaining state in async operations • Event handlers • Memoization & caching ⸻ 💡 Engineering Insight Closures are the foundation behind: • React hooks • Middleware patterns • Function factories • Many JavaScript libraries But they can also cause issues: ⚠ Memory leaks if references are not handled properly ⚠ Unexpected values in loops (classic bug) Example issue: for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } Output: 3 3 3 Fix using let (block scope): for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } Output: 0 1 2 ⸻ ⏭ Tomorrow: Hoisting in JavaScript (var, let, const — what really happens?) #100DaysOfCode #JavaScript #TypeScript #WebDevelopment #SoftwareEngineering #Closures
To view or add a comment, sign in
-
🔍 JavaScript Bug You Might Have Seen (setTimeout + loop) You write this code: for (var i = 1; i <= 3; i++) { setTimeout(() => { console.log(i); }, 1000); } You expect: 1 2 3 But you get: 4 4 4 This happens because of closure 📌 What is a Closure? 👉 A closure is a function along with its lexical environment. Not clear? No problem. Here’s a simpler version: 👉 A closure is a function along with the variables it remembers from where it was created. In this case: The function inside setTimeout 👉 remembers the SAME i variable And when it executes: 👉 Loop has already finished → i = 4 So all logs print: 4, 4, 4 How to fix it? ✔ Use let (creates a new variable per iteration) for (let i = 1; i <= 3; i++) { setTimeout(() => { console.log(i); }, 1000); } ✔ Or create a new scope manually for (var i = 1; i <= 3; i++) { (function(i) { setTimeout(() => { console.log(i); }, 1000); })(i); } 💡 Takeaway: ✔ Closures remember variables, not values ✔ var shares the same scope → leads to bugs ✔ let creates a new scope per iteration 👉 If you understand closures, you’ll avoid some very tricky bugs. 🔁 Save this for later 💬 Comment “closure” if this made sense ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🚀 **𝐃𝐚𝐲 5 – 𝐇𝐨𝐢𝐬𝐭𝐢𝐧𝐠 𝐢𝐧 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 (𝐂𝐥𝐞𝐚𝐫 & 𝐏𝐫𝐚𝐜𝐭𝐢𝐜𝐚𝐥 𝐄𝐱𝐩𝐥𝐚𝐧𝐚𝐭𝐢𝐨𝐧)** You might have seen this 👇 👉 Using a variable before declaring it But why does this work? 🤔 --- 💡 **What is Hoisting?** Hoisting means: 👉 Before execution, JavaScript **allocates memory for variables and functions** 👉 In simple words: **Declarations are processed before code runs** --- 💡 **Example:** ```js id="d5pro1" console.log(a); var a = 10; ``` 👉 Output: `undefined` --- 💡 **What actually happens behind the scenes?** Before execution (Memory Phase): * `a` → undefined Then execution starts: * `console.log(a)` → prints undefined * `a = 10` --- 💡 **Important Rule** 👉 JavaScript only hoists **declarations**, not values --- 💡 **var vs let vs const** 👉 **var** * Hoisted * initialized as `undefined` * can be accessed before declaration 👉 **let & const** * Hoisted * BUT not initialized --- ⚠️ **Temporal Dead Zone (TDZ)** This is the time between: 👉 variable declared 👉 and initialized During this: ❌ Accessing variable → **ReferenceError** --- 💡 **Example:** ```js id="d5pro2" console.log(a); let a = 10; ``` 👉 Output: **ReferenceError** --- ⚡ **Key Insight (Very Important)** 👉 Hoisting is NOT moving code 👉 It’s just **memory allocation before execution** --- 💡 **Why this matters?** Because it helps you understand: * unexpected `undefined` values * ReferenceErrors * how JavaScript actually runs code --- 👨💻 Continuing my JavaScript fundamentals series 👉 Next: **JavaScript Runtime & Event Loop** 👀 #JavaScript #WebDevelopment #FrontendDevelopment #Coding #SoftwareEngineer #Tech
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
-
-
Ever wondered what actually happens when you use new in JavaScript? 🤔 Today I learned: 👉 How objects are created behind the scenes 👉 How prototypes are linked 👉 How constructors build instances Documented everything in this article 👇 https://lnkd.in/gr2UykHg #JavaScript #100DaysOfCode #WebDev #chaicode Chai Code Hitesh ChoudharyPiyush Garg Akash Kadlag Suraj Kumar Jha
To view or add a comment, sign in
-
⚠️ JavaScript Function Expression — A Common Corner Case That Trips Developers 🔍 The Corner Case: Hoisting Behavior console.log(add(2, 3)); // ❌ TypeError: add is not a function var add = function(a, b) { return a + b; }; 👉 Why does this fail? Because only the variable declaration (var add) is hoisted, not the function itself. So internally, JavaScript sees this as: var add; console.log(add(2, 3)); // ❌ add is undefined add = function(a, b) { return a + b; }; ✅ Now Compare with Function Declaration console.log(add(2, 3)); // ✅ 5 function add(a, b) { return a + b; } 👉 Entire function is hoisted — so it works! 💥 Another Tricky Case (Named Function Expression) const foo = function bar() { console.log(typeof bar); }; foo(); // ✅ function bar(); // ❌ ReferenceError: bar is not defined 👉 bar is only accessible inside the function, not outside! 🎯 Key Takeaways ✔ Function expressions are NOT fully hoisted ✔ Only variable declarations are hoisted (var, let, const behave differently) ✔ Named function expressions have limited scope ✔ Always define function expressions before using them #JavaScript #Frontend #CodingInterview #WebDevelopment #JSConcepts #100DaysOfCode
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