I Thought I Knew JavaScript… Until I Compared Two Objects 😅 🚀 Today I learned something that seems simple at first — but it completely changed how I think about JavaScript objects! In JavaScript, objects, arrays, and functions are compared by reference, not by value. That means: const obj1 = { a: 1, b: 2 } const obj2 = { a: 1, b: 2 } console.log(obj1 === obj2); // false Even though they look identical, they’re actually stored in different memory locations. Each time you write { a:1, b:2 }, you’re creating a new object in memory. However, if you assign one object to another variable: const obj1 = { a:1, b:2 }; const obj2 = obj1; console.log(obj1 === obj2); // true Now both variables reference the same memory address — so a change in one reflects in the other. Understanding this subtle difference between reference and value comparison helped me better grasp how caching, memoization, and equality checks work under the hood in JS. Takeaway: Objects are shared by reference, but compared by memory address. #JavaScript #WebDevelopment #Learning #CodingJourney #TechInsights
How JavaScript compares objects by reference, not value.
More Relevant Posts
-
🔧 Deep Dive into JavaScript Variables Today, I explored a core JavaScript concept with deeper technical insight — Variable Declarations. JavaScript provides three keywords for declaring variables: var, let, and const, each with unique behavior related to scope, mutability, and hoisting. 🧠 Technical Insights I Learned ✔️ Execution Context & Memory Allocation During the creation phase, JavaScript allocates memory for variables. var is hoisted and initialized with undefined. let and const are hoisted but remain in the Temporal Dead Zone (TDZ) until execution reaches their line. ✔️ Scope Differences var → function-scoped, leaks outside blocks, may cause unintended overrides let & const → block-scoped, making them safer for predictable behavior ✔️ Mutability & Reassignment var and let allow reassignment const does not allow reassignment, but its objects and arrays remain mutable ✔️ Best Practices (ES6+) Prefer const for values that should not change Use let for variables that require reassignment Avoid var in modern codebases due to its loose scoping and hoisting behavior ✔️ Cleaner Code Through ES6 The introduction of let and const significantly improved variable handling, reduced bugs caused by hoisting, and enabled more structured, modular JavaScript. Mastering these low-level behaviors helps build stronger foundations for understanding execution context, closures, event loops, and advanced JavaScript patterns. Grateful to my mentor Sudheer Velpula sir for guiding me toward writing technically sound and modern JavaScript. 🙌 #JavaScript #ES6 #Variables #FrontendDevelopment #CleanCode #ProgrammingFundamentals #WebDevelopment #TechnicalLearning #CodingJourney #JSConcepts #DeveloperCommunity
To view or add a comment, sign in
-
-
🧠 Understanding Block Statements and Lexical Scope in JavaScript When I first started coding in JavaScript, I didn’t really pay attention to where I declared my variables — as long as the code ran, I was happy 😅. But once I began working on bigger projects, I realized scope and block behavior can make or break your code’s predictability. Here’s the thing: A block statement is simply the part inside { } — it could be inside an if, a for, or even just a standalone block. Example: { let message = "Hello world"; console.log(message); } console.log(message); // ❌ ReferenceError What’s happening? Because of lexical scoping, variables declared with let and const only exist within the block they were defined in. Meanwhile, var ignores that and leaks out — which is one reason modern JS avoids it. Understanding how lexical scope works helps prevent weird bugs and keeps your functions predictable. It’s one of those quiet fundamentals that makes your JavaScript more intentional and less chaotic. Have you ever been bitten by a var variable leaking out of a block before? 😅 #JavaScript #WebDevelopment #Frontend #CleanCode #JSFundamentals
To view or add a comment, sign in
-
-
Day 3: Deepening JavaScript Skills with Counter Function Challenge! 🚀 Today, I tackled a classic problem — creating a flexible counter object that can increment, decrement, and reset — and it really sharpened my understanding of closures and object-oriented design in JavaScript. I implemented the createCounter function to accept an initial value and return an object with three methods: increment(): increases the value by 1 and returns it decrement(): decreases the value by 1 and returns it reset(): resets the value to the initial value and returns it This exercise reinforced how closures help maintain persistent state for each counter instance, making the code both clean and efficient. Here's a quick snippet: javascript const createCounter = (init) => { let n = init; return { increment() { return ++n; }, decrement() { return --n; }, reset() { n = init; return n; } }; }; Excited to keep pushing forward on this JavaScript journey! 💪 Let’s continue learning and sharing—feel free to share your progress or ask questions below. #JavaScript #30DaysOfJS #CodingJourney #Closure #WebDevelopment #LeetCode #ProblemSolving
To view or add a comment, sign in
-
-
Many of us are familiar with how var is hoisted in JavaScript, leading to potential confusion. But what about let and const? They are also hoisted, but with a critical difference that introduces the Temporal Dead Zone (TDZ)! What is Hoisting with let and const? 🤔 Hoisting is a phenomenon that allows us to access functions and variables before we initialize them. Contrary to popular belief, let and const declarations are indeed hoisted just like var and function declarations. However, the crucial difference lies in their memory allocation: unlike var, which is initialized with the placeholder "undefined" during the memory allocation phase (and is attached to the global object), let and const are also allocated memory, but this is stored in a separate memory space from the global one. We cannot access this separate memory space before assigning a value to let or const. This state of inaccessibility creates the Temporal Dead Zone (TDZ), which persists until the let and const variables are initialized. The Temporal Dead Zone (TDZ) ⏳ The Temporal Dead Zone is the period of time from when let and const are hoisted until they are initialized with some value. If you try to access a let or const within its TDZ, JavaScript will throw a "ReferenceError" because the variable exists but hasn't reached its initialization point. 💡 The Key Takeaway: -> Hoisting allows us to access functions and variables before initialization. -> TDZ is the time before the let and const variables are assigned a value. #javascript #reactjs #webdev
To view or add a comment, sign in
-
🚀 Understanding Hoisting in JavaScript Ever wondered how you can use a variable or function before it’s declared? 🤔 That’s because of Hoisting! In JavaScript, hoisting means that variable and function declarations are moved to the top of their scope during the compile phase — before the code actually runs. 🧠 Example: greet(); // ✅ Works! function greet() { console.log("Hello, World!"); } Here, the function greet() is hoisted to the top — that’s why you can call it even before it’s defined. But be careful with variables 👇 console.log(x); // ❌ undefined var x = 10; Variables declared with var are hoisted but not initialized, so they exist but hold undefined. However, variables declared with let and const are also hoisted but stay in the Temporal Dead Zone (TDZ) until they’re actually declared. 📌 In short: Functions → hoisted with their definitions ✅ var → hoisted but undefined ⚠️ let & const → hoisted but inaccessible until declared 🚫 #javascript #frontend #webdevelopment
To view or add a comment, sign in
-
-
🚀 5 Quick Facts About Arrays in JavaScript 1️⃣ Dynamic & Flexible – You can store numbers, strings, or even objects in the same array. 🧩 const arr = [1, "two", true]; 2️⃣ Technically Objects – typeof [] returns "object", not "array". ✅ Use Array.isArray(arr) to be sure. 3️⃣ Built for Efficiency – Use map(), filter(), and reduce() to write clean, functional code. 4️⃣ Spread Operator Power – Combine or clone arrays effortlessly. ⚙️ const merged = [...arr1, ...arr2]; 5️⃣ Zero-Indexed – The first element starts at index 0. 📍 arr[0] gives the first item. Arrays are more powerful than they look — master them, and your JS code will be cleaner, faster, and smarter 💡 #JavaScript #WebDevelopment #CodingTips #Arrays #DeveloperLife
To view or add a comment, sign in
-
💛 𝗗𝗮𝘆 𝟮 — 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲𝘀, 𝗦𝗰𝗼𝗽𝗲, 𝗮𝗻𝗱 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 Today, I revisited one of the most confusing yet powerful concepts in JavaScript — 𝗵𝗼𝗶𝘀𝘁𝗶𝗻𝗴 and 𝘀𝗰𝗼𝗽𝗶𝗻𝗴. 🧠 💡 𝗖𝗼𝗻𝗰𝗲𝗽𝘁: JavaScript moves all declarations to the top of their scope during compilation — this is known as hoisting. However, the behavior differs based on whether you use var, let, const, or functions. 💻 𝗖𝗼𝗱𝗲 𝗦𝗻𝗶𝗽𝗽𝗲𝘁: console.log(a); // undefined (hoisted) var a = 10; console.log(b); // ❌ ReferenceError (in TDZ) let b = 20; sayHello(); // ✅ Works — function declarations are hoisted function sayHello() { console.log("Hello from a hoisted function!"); } // ❌ Error: sayHi is not a function sayHi(); var sayHi = function () { console.log("Hi from function expression!"); }; 🧩 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻: 0. var is hoisted and initialized with undefined. 1. let and const are hoisted but stay uninitialized in the temporal dead zone (TDZ). 2. Function declarations are fully hoisted, so you can call them before defining. 3. Function expressions (especially when assigned to var) behave like variables — hoisted but not initialized. 📈 𝗦𝗰𝗼𝗽𝗲 𝗪𝗶𝘀𝗱𝗼𝗺: var → function scope let & const → block scope Functions → create their own local scope 🔥 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Understanding how JavaScript creates and executes contexts will help you debug faster and think more like the JS engine itself. #JavaScript #100DaysOfCode #Hoisting #Scope #Functions #FrontendDevelopment #LearningEveryday
To view or add a comment, sign in
-
*5 Things I Wish I Knew When Starting JavaScript 👨💻* Looking back, JavaScript was both exciting and confusing when I started. Here are 5 things I wish someone had told me earlier: *1. var is dangerous. Use "let" and "const" "var" is function-scoped and can lead to unexpected bugs. "let" and "const" are block-scoped and safer. *2. JavaScript is asynchronous Things like "setTimeout()"and "fetch()" don’t behave in a straight top-down flow. Understanding the *event loop* helps a lot. *3. Functions are first-class citizens* – You can pass functions as arguments, return them, and even store them in variables. It’s powerful once you get used to it. *4. The DOM is slow – avoid unnecessary access* – Repeated DOM queries and manipulations can hurt performance. Use "documentFragment" or batch changes when possible. *5. Don’t ignore array methods* map(), "filter()" , "reduce()", "find()"… they make code cleaner and more readable. I wish I started using them sooner. 💡 *Bonus Tip:* "console.log()" is your best friend during debugging! If you’re starting out with JS, save this. And if you're ahead in the journey — what do *you* wish you knew earlier? #JavaScript #WebDevelopment #CodingJourney #Frontend #LearnToCode #DeveloperTips
To view or add a comment, sign in
-
🧠 Why does let create a new closure in every loop iteration in JavaScript? Ever wondered why this works perfectly 👇 for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } // Output: 0, 1, 2 …but this doesn’t 👇 for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } // Output: 3, 3, 3 That’s not “compiler magic” — it’s actually defined in the ECMAScript specification itself. 📜 --- 📘 ECMA Definition From ECMA-262 §13.7.4.8 – Runtime Semantics: ForBodyEvaluation: > If the loop variable is declared with let or const, a new LexicalEnvironment is created for each iteration. The variable is copied (rebound) from the previous environment and used to evaluate the loop body in this new environment. --- 🔍 What This Means Every time the loop runs: JavaScript creates a new environment record (a fresh closure). The loop variable (i) is independent for that iteration. Each callback “remembers” its own copy of i. So effectively: var → single shared binding across all iterations. let / const → new closure per iteration. --- ✅ In short: let is not just about block scoping — it’s about creating predictable closures inside loops by design. #JavaScript #ECMAScript #Closures #Frontend #WebDevelopment #CodingTips #LearnInPublic
To view or add a comment, sign in
-
|| Day - 28 || + JavaScript Basics : Cohort 2.0 ✨ Key Learnings of the Day: 1. Learned about different data types in JavaScript such as float, null, array etc. 2. Understood some quirks and behaviors of JavaScript related to data types and type conversions. 3. Practiced various array operations like adding, removing, and accessing elements efficiently. + Step 3 in JavaScript for Web Development. >> #HarshVandanaSharma #SheriyansCohort2 #LearningJourney #JS #WebDevelopment #FrontendDesign #CareerGrowth
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
Great insight! I've learnt something similar, comparing two NaN values always returns false. console.log(NaN === NaN); // ❌ false Why: According to IEEE floating-point rules, NaN is not equal to anything, including itself. It's confusing yet interesting if we go deeper to understand why js behaves weirdly.