🚀 A JavaScript Mistake With Object.freeze() At first glance, this looks safe: const user = { name: "Inderpal", address: { city: "Noida" } }; Object.freeze(user); user.name = "Updated"; user.address.city = "Delhi"; console.log(user); You might expect nothing to change. But output will be: { name: "Inderpal", address: { city: "Delhi" } } Why? Because Object.freeze() only performs a shallow freeze. It prevents changes to top-level properties, but nested objects can still be modified. To truly make it immutable, you need deep freezing. function deepFreeze(obj) { Object.keys(obj).forEach(key => { if (typeof obj[key] === "object" && obj[key] !== null) { deepFreeze(obj[key]); } }); return Object.freeze(obj); } JavaScript often protects the surface, not the depth. Understanding shallow vs deep behavior prevents subtle state bugs. Have you ever assumed something was immutable when it wasn’t? #javascript #frontenddeveloper #webdevelopment #coding #softwareengineering
JavaScript Object Freeze Limitation: Shallow vs Deep Freeze
More Relevant Posts
-
JavaScript objects have a powerful feature called Prototype that enables inheritance. In JavaScript, if an object doesn’t have a specific property or method, the engine automatically looks for it in its prototype. This process continues up the prototype chain until the property is found or the chain ends. Example: function Person(name) { this.name = name; } Person.prototype.greet = function () { console.log("Hello, my name is " + this.name); }; const john = new Person("John"); john.greet(); Even though john doesn’t directly have the greet() method, it can still access it through Person.prototype. This mechanism allows JavaScript objects to share methods and inherit behavior efficiently. Understanding prototypes helps you better understand how inheritance and object behavior work behind the scenes in JavaScript. Follow for more JavaScript concepts explained visually. #javascript #webdevelopment #frontenddeveloper #coding #learninginpublic #100DaysOfCode
To view or add a comment, sign in
-
-
Ever copied an object in JavaScript… and later wondered why changing one thing broke something else? I used the spread operator, Object.assign—everything looked right. The object was “copied,” features worked, and I moved on. Until one small change inside a nested object started affecting the original data. That’s when I realized copying in JavaScript isn’t as straightforward as it looks. I used to think: “If I copy an object, I get a completely separate version.” Sounds reasonable—but it misses an important detail. So I slowed down and explored what was actually happening. References. Memory locations. Nested structures. I built tiny examples, tweaked values, compared outputs—sometimes it worked, sometimes it didn’t… until patterns started to show up. And then it made sense. The issue wasn’t the syntax—it was understanding what gets copied and what still points to the same place in memory. That shift changed a lot: • I stopped assuming copies were independent • Debugging weird state changes became much easier • Spread vs structuredClone finally had a clear difference • Nested objects stopped feeling unpredictable Most importantly: 👉 A shallow copy duplicates only the top level 👉 Nested objects still share the same reference 👉 A deep copy creates a fully independent structure Now when something changes unexpectedly, I don’t guess—I check how the data was copied. Still learning, but this one concept made JavaScript feel a lot more predictable. What’s one JS concept that took you time to truly understand? #JavaScript #WebDevelopment #Frontend #LearningInPublic #JSConcepts #Debugging
To view or add a comment, sign in
-
-
🔍 Prototypes and this in JavaScript — going beyond the syntax into the actual mechanics. Here's what's worth knowing: 🧬 On Prototypes Methods aren't copied to every object instance. They live once on the prototype — all instances share them via reference. That's how JS stays memory efficient even with thousands of objects. Every method lookup is a live chain traversal, every single time. Object.create is pure prototype wiring — it sets the [[Prototype]] of a new object. That's it. 🎯 On this — four rules, in priority order 1️⃣ new binding → this = newly created object 2️⃣ Explicit binding → .call() .apply() .bind() — you decide 3️⃣ Implicit binding → obj.method() — this = object left of the dot 4️⃣ Default binding → standalone call — this = window or undefined Arrow functions sit outside all four rules — they inherit this lexically from wherever they were defined. ⚠️ The classic trap js setTimeout(this.log, 1000); // this is lost Detach a method from its object and this evaporates. Fix → arrow wrapper, .bind(), or bind in the constructor. Each has different tradeoffs. 🧠 On EventEmitters and memory Per-instance state must always be initialized in the constructor. If it accidentally lands on the prototype — every instance shares the same object. Emitting on one instance fires callbacks registered on all instances. Silent. No error thrown. Every .on() listener holds a closure reference — keeping objects alive in memory long after they're "destroyed." Always implement .off(). Always clean up. Follow along — sharing one deep dive at a time. 🚀 #JavaScript #Prototypes #FrontendEngineering #WebPerformance #PlatformEngineering
To view or add a comment, sign in
-
Say Goodbye to JavaScript Date Object Headaches! For years, developers have struggled with the built-in Date object in JavaScript—it's mutable, inconsistent, and a major pain when dealing with time zones or complex date arithmetic. Most of us have relied on external libraries like Moment.js or date-fns to get the job done. But the future is here: the Temporal API is arriving as a new built-in standard, and it's a game-changer! 🚀 Temporal provides a robust, modern, and reliable way to handle dates and times. Here’s why you should be excited: 🔒 Immutability: Every Temporal object is immutable, which eliminates a major source of bugs in date manipulation. 🌍 First-Class Time Zones: It has explicit, robust support for time zones and daylight saving time (DST). ➗ Safe Arithmetic: Performing calculations like adding or subtracting days is predictable and straightforward with methods like add() and subtract(). 🎯 Clear Data Types: Instead of one generic Date object, Temporal offers distinct types for different use cases: Instant: For exact points in time. PlainDate, PlainTime, PlainDateTime: For wall-clock dates and times without a specific time zone. ZonedDateTime: For handling time-zoned timestamps. Major browsers are actively implementing the proposal. You can start experimenting with it today using a polyfill or check out the official TC39 documentation. It's time to level up our date-handling skills! Who's ready to make the switch? #JavaScript #WebDev #Frontend #Temporal #Programming #Coding #TechNews
To view or add a comment, sign in
-
-
Shipping is a habit! 🚀 2 Days, 2 Projects, and a deeper dive into JavaScript. I’ve been heads-down in the #ChaiAurCode journey, and the momentum is real. Over the last 48 hours, I’ve moved from understanding basic logic to shipping functional mini-projects. Project 1: Dynamic List Creator 📝 Focused on mastering the DOM. It’s one thing to see a list on a screen, it’s another to handle real-time user input, state updates, and clean element creation dynamically. 🌐 Try the List Creator: https://lnkd.in/grMrRqMt Project 2: Color Palette Generator 🎨 This one was a technical "Aha!" moment. 🌐 Try the Palette Generator: https://lnkd.in/gCUwyhrc Key takeaways: ➡️ Precision Math: Implementing Math.random() * (max - min) + min to control color tones (Light vs. Dark). ➡️ String Manipulation: Using .padStart(2, "0") to ensure valid Hex codes a small detail that prevents major UI bugs. ➡️ The Backend Loop: I even experimented with running an Express server and frontend logic in a single file to visualize the full Request-Response cycle. Big thanks to my mentors Hitesh Choudhary and Suraj Kumar Jha for the guidance during the T-class sessions! Github repo links - List Creator - https://lnkd.in/gH9hzGY3 Palette Generator - https://lnkd.in/gEAv7NJ4 (I've shared the screen recording for the List Creator in the comments below! 👇) Anirudh J. Akash Kadlag Jay Kadlag Piyush Garg #WebDevelopment #JavaScript #BuildInPublic #FullStackJourney #LearningTogether #Vercel #CodingProgress
To view or add a comment, sign in
-
Most JavaScript developers are writing async code without understanding what's actually happening. I spent today going deep on the internals. Here's what actually matters: 🔁 THE EVENT LOOP Everyone says "JavaScript is single-threaded" but can't explain why this works: console.log('1') setTimeout(() => console.log('2'), 0) Promise.resolve().then(() => console.log('3')) console.log('4') Output: 1 → 4 → 3 → 2 The reason? Microtasks (Promises) always drain before macrotasks (setTimeout). Not knowing this will produce bugs you can't explain. 🔒 CLOSURES Not just a concept. A practical superpower. I built a memoize() function from scratch today. One function. Saves expensive recalculations by remembering previous results. This is a real interview question at top companies — and most devs can't write it. 🔗 PROTOTYPE CHAIN Hot take: if you only write classes without understanding prototypes, you don't understand JavaScript. Every class in JS compiles down to prototype assignment. Once I rewrote a class using Object.create() manually, inheritance finally made sense. The truth nobody tells you: Senior devs aren't faster because they know more syntax. They're faster because they understand what the engine is actually doing. Day 1 of my 15-day full-stack + AI engineering sprint. Building in public. What JavaScript concept took you the longest to actually understand? 👇 #JavaScript #WebDevelopment #FullStack #100DaysOfCode #LearningInPublic
To view or add a comment, sign in
-
One of my favorite JavaScript one-liners: filter(Boolean). Filtering out falsy values from an array meant chaining conditions and hoping I hadn't missed an edge case. When you pass Boolean as a callback to .filter(), JavaScript calls Boolean(item) on every element. Anything falsy - null, undefined, 0, ", false, NaN - gets removed. What you're left with is a clean array of only meaningful values. It's not just about writing less code. It's about communicating intent clearly. This pattern shines especially in real-world scenarios: cleaning up APl responses, processing user input, or combining .map) and.filter) to transform and sanitize data in a single chain. #JavaScript #WebDevelopment #SoftwareEngineering #CleanCode #Frontend #Programming #JS #CodeQuality #TechTips #Developer
To view or add a comment, sign in
-
-
Tuesday – JavaScript Concept Observer vs Promise vs Async/Await These three are often confused, but they solve different problems. Promise Represents a single future value. Example use case: API request. fetch(”/api/data”) .then(res => res.json()) Promise gives: ✔ one result ✔ once completed ✔ cannot emit multiple values ⸻ Async / Await Just a cleaner way to write Promises. Example: async function loadData() { const res = await fetch(”/api/data”) return res.json() } It improves readability but internally it still uses Promises. ⸻ Observer Pattern Completely different concept. Observers listen to multiple events over time. Example: Event systems or streams. Example concept: observer.subscribe(data => { console.log(data) }) Observer can: ✔ emit multiple values ✔ stream updates ✔ stay active This pattern powers libraries like RxJS. ⸻ Quick summary: Promise → one future value Async/Await → syntax for promises Observer → stream of values over time Understanding these differences makes async code much easier to design. See you tomorrow for AI Integration Wednesday 🤖 #JavaScript #AsyncProgramming #FrontendDevelopment
To view or add a comment, sign in
-
One of my favorite JavaScript one-liners: .filter(Boolean) Filtering out falsy values from an array meant chaining conditions and hoping I hadn't missed an edge case. When you pass Boolean as a callback to .filter(), JavaScript calls Boolean(item) on every element. Anything falsy - null, undefined, 0, "", false, NaN - gets removed. What you're left with is a clean array of only meaningful values. It's not just about writing less code. It's about communicating intent clearly. This pattern shines especially in real-world scenarios: cleaning up API responses, processing user input, or combining .map() and .filter() to transform and sanitize data in a single chain. #JavaScript #WebDevelopment #SoftwareEngineering #CleanCode #Frontend #Programming #JS #CodeQuality #TechTips #Developer --- I post about web engineering, front-end and soft skills in development. Follow me here: Irene Tomaini
To view or add a comment, sign in
-
-
🚀 A JavaScript forEach() Mistake At first glance, this looks correct: const numbers = [1, 2, 3, 4]; const result = numbers.forEach(num => num * 2); console.log(result); Expected: [2, 4, 6, 8] Actual output: undefined Why? Because forEach() does not return a new array. It only executes a function for each element. So result becomes undefined. If you want to transform data, use map(). ✅ Correct approach: const numbers = [1, 2, 3, 4]; const result = numbers.map(num => num * 2); console.log(result); Now the output is: [2, 4, 6, 8] Small difference in method. Big difference in behavior. In JavaScript, choosing the right array method matters more than the logic itself. What array method confused you the most when you started? #javascript #frontenddeveloper #webdevelopment #coding #softwareengineering
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