I’ve lost count of how many times I’ve seen the same explanation: “Primitives are passed by value, objects by reference.” It’s everywhere—in tutorials, interviews, Stack Overflow answers… and honestly, it’s been driving me nuts because it’s not quite accurate in JavaScript. So I finally sat down and wrote the post I wish I’d read years ago: “Primitives vs Objects: How JavaScript Values Actually Work” The real difference isn’t “value vs reference”—it’s mutability. Primitives are immutable (you can’t change them, only replace them). Objects are mutable (you can change their contents, and everyone with a reference sees it). Everything else flows from there: why a = b behaves differently, why {} === {} is false, why mutating an object affects the “original”, why reassignment doesn’t, and even why JavaScript technically uses “call by sharing” for everything. If you’ve ever been confused by why changing an array in a function changes the original, or why strings act “weird” compared to objects—this might clear things up. Check it out here: https://lnkd.in/dvRfbPFC What’s the biggest JavaScript primitive/object misconception you’ve had to unlearn? Drop it below—I’m curious. 👇 #JavaScript #WebDevelopment #Programming #Frontend
JavaScript Primitives vs Objects: Understanding Mutability
More Relevant Posts
-
🚀 JavaScript Functions — Explained Functions are the backbone of JavaScript What is a Function? >> A function is a reusable block of code designed to perform a specific task. 1. Function Declaration: A function defined using the function keyword with a name. function greet(name) { return "Hello " + name; } ✔️ Hoisted (can be used before declaration) 2. Function Expression: A function stored inside a variable. const greet = function(name) { return "Hello " + name; }; ❌ Not hoisted like declarations 3. Arrow Function: A shorter syntax for writing functions using =>. const greet = (name) => "Hello " + name; ✔️ Clean and concise ⚠️ Does not have its own this 4. Parameters: Variables listed in the function definition. function add(a, b) { } >> a and b are parameters 5. Arguments: Actual values passed to a function when calling it. add(2, 3); >> 2 and 3 are arguments 6. Return Statement: The return keyword sends a value back from a function and stops execution. function add(a, b) { return a + b; } 7. Callback Function: A function passed as an argument to another function. function greet(name) { console.log("Hello " + name); } function processUser(callback) { callback("Javascript"); } 8. Higher-Order Function: A function that takes another function as an argument or returns a function. >> Examples: map(), filter(), reduce() 9. First-Class Functions: In JavaScript, functions are treated like variables. ✔️ Can be assigned to variables ✔️ Can be passed as arguments ✔️ Can be returned from other functions #JavaScript #WebDevelopment #FrontendDevelopment #Coding #Programming #LearnToCode
To view or add a comment, sign in
-
🚀 Understanding "var" Scope in JavaScript In JavaScript, there are mainly three types of scope: 1️⃣ Global Scope – Variables declared outside any function are accessible everywhere in the program. 2️⃣ Function Scope – Variables declared inside a function can only be used inside that function. 3️⃣ Block Scope – Variables declared inside blocks like "{ }" (for example in "if", "for", etc.) are only accessible inside that block. However, the important thing to remember is: 👉 The "var" keyword only follows Global Scope and Function Scope. ❌ It does NOT follow Block Scope. Let’s look at a simple example: if (true) { var message = "Hello World"; } console.log(message); // Output: Hello World Even though "message" is declared inside the "if" block, we can still access it outside the block. This happens because "var" ignores block scope. Now look at a function example: function test() { var number = 10; console.log(number); // 10 } console.log(number); // Error: number is not defined Here, "number" is declared inside the function, so it cannot be accessed outside the function. ✅ Key Takeaway: - "var" → Global Scope + Function Scope - "var" ❌ does not support Block Scope That’s why modern JavaScript developers prefer "let" and "const", because they properly support block scope. #JavaScript #WebDevelopment #Programming #BackendDevelopment
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
-
🧠 How Garbage Collection Works in JavaScript (Under the Hood) JavaScript handles memory automatically through Garbage Collection (GC), but understanding how it works helps developers avoid memory leaks and unintended object retention. The goal of GC is simple: 👉 Identify objects that are no longer reachable and reclaim their memory. JavaScript engines primarily rely on two algorithms. 1️⃣ Reference Counting (Historical Approach) In Reference Counting, every object maintains a count of how many references point to it. When the reference count reaches 0, the object becomes eligible for garbage collection. Example: let obj = { name: "JS" }; let ref = obj; obj = null; // reference count decreases but object still exists ref = null; // reference count becomes 0 → object can be collected ⚠️ Problem: Circular References let a = {}; let b = {}; a.ref = b; b.ref = a; Even if a and b are no longer accessible from the program, they still reference each other. Their reference count never becomes zero, leading to memory that cannot be reclaimed. 2️⃣ Mark-and-Sweep (Modern JavaScript Engines) Modern engines like V8 JavaScript Engine, Spider Monkey JavaScript Engine, and JavaScript Core use Mark-and-Sweep based garbage collection. This algorithm operates in two phases: 1. Mark Phase The GC starts from root objects (e.g., the global execution context, stack references). It recursively traverses and marks all reachable objects. 2. Sweep Phase Objects that were not marked are considered unreachable. The GC reclaims that memory. In simple terms: If an object cannot be reached from the root, it becomes garbage. ⚙️ Why This Matters for Developers Understanding GC helps when dealing with: • Closures retaining large objects • Detached DOM nodes in browsers • Long-lived references in caches or event listeners These patterns can keep objects reachable, preventing garbage collection and causing memory leaks. 💡 Takeaway JavaScript doesn’t free memory when variables go out of scope. It frees memory when objects become unreachable from the root set. #JavaScript #FrontendEngineering #MemoryManagement #V8 #WebDevelopment
To view or add a comment, sign in
-
JavaScript this keyword doesn't have to be a mystery. I just published a blog covering the 4 ways this gets its value: 🔹 Implicit: obj.method() 🔹 Explicit: .call(), .apply(), .bind() 🔹 New: const user = new User() 🔹 Default: The fallback (Window/Undefined) If you've ever struggled with scope or context, this one is for you. Check it out: https://lnkd.in/gKk4GYGp Special thanks to Hitesh Choudhary for giving me the question that started this all and to Akash Kadlag, for explaining and making the concepts easy to understand.
To view or add a comment, sign in
-
8 JavaScript Concepts Every Developer Must Master JavaScript isn’t about memorizing syntax. It’s about understanding how things work under the hood. These core concepts decide whether you write code that works… or code that survives production. 1️⃣ Execution Context & Call Stack JavaScript runs inside execution contexts and manages them using the call stack. This explains: • Why functions execute in order • How stack overflows happen • Why recursion can crash your app If you don’t understand the call stack, debugging becomes guesswork. 2️⃣ Hoisting During compilation: • var is hoisted with undefined • let and const live in the Temporal Dead Zone Understanding hoisting prevents subtle bugs that look “random.” 3️⃣ Scope & Closures Closures allow functions to remember variables from their parent scope even after execution. This powers: • Data hiding • Currying • Many React hook patterns Most React bugs involving stale state? Closures. 4️⃣ The this Keyword this is NOT lexical (except in arrow functions). Its value depends on how a function is called not where it’s written. Misunderstanding this leads to unpredictable behavior. 5️⃣ Event Loop & Async JavaScript Promises, async/await, and callbacks rely on: • Call stack • Web APIs • Microtask queue • Event loop If you don’t understand the event loop, async code feels like magic. And magic breaks in production. 6️⃣ Prototypes & Inheritance JavaScript uses prototype-based inheritance — not classical inheritance. Understanding prototypes clears confusion around: • Classes • __proto__ • Method sharing 7️⃣ Shallow vs Deep Copy Objects are copied by reference. If you don’t know when to deep copy: • State mutations happen • Bugs become invisible • React re-renders behave unexpectedly 8️⃣ Debounce & Throttle Critical for performance in: • Scroll events • Resize handlers • Search inputs Without them, your app wastes CPU cycles. Final Thought If you deeply understand these concepts, frameworks become easy. If you skip them, frameworks feel simple… until production breaks. Strong JavaScript > Trendy Frameworks. #JavaScript #React #Frontend #WebDevelopment #SoftwareEngineering #MERN
To view or add a comment, sign in
-
🔥 Regular Function vs Arrow Function in JavaScript — what's the real difference? This confused me when I started. Here's everything you need to know 👇 ━━━━━━━━━━━━━━━━━━━━━━━━━━ 1. The syntax is different Regular functions use the function keyword. Arrow functions use a shorter ( ) => syntax — less typing, cleaner code. 2. The "this" keyword behaves differently This is the BIG one. 📌 Regular function → has its own this. It changes depending on HOW the function is called. 📌 Arrow function → does NOT have its own this. It borrows this from the surrounding code. That's why arrow functions are great inside classes and callbacks — they don't lose track of this. 3. Arrow functions can't be used as constructors You can do new regularFunction() — works fine. You can NOT do new arrowFunction() — it throws an error. 4. Arguments object Regular functions have a built-in arguments object to access all passed values. Arrow functions don't — use rest parameters (...args) instead. ━━━━━━━━━━━━━━━━━━━━━━━━━━ ✅ When to use which? → Use arrow functions for short callbacks, array methods (.map, .filter), and when you need to keep this from the outer scope. → Use regular functions when you need your own this, use as a constructor, or need the arguments object. Understanding this = leveling up as a JavaScript developer 🚀 #JavaScript #WebDevelopment #100DaysOfCode #Frontend #CodingTips #Programming
To view or add a comment, sign in
-
🚀 JavaScript Deep Dive: `this` Keyword (Most Confusing Yet Most Asked) If you think `this` always refers to the current object… You’re already making a mistake ❌ Let’s simplify it 👇 --- 💡 Rule: 👉 `this` depends on **HOW a function is called**, not where it is written. --- 💻 Example 1 (Implicit Binding): ```js const user = { name: "Rahul", greet() { console.log(this.name); } }; user.greet(); // Rahul ✅ ``` 👉 Here, `this` → `user` --- 💻 Example 2 (Losing Context): ```js const greetFn = user.greet; greetFn(); // undefined ❌ ``` 👉 `this` is now global (or undefined in strict mode) --- 💻 Example 3 (Arrow Function Trap): ```js const user = { name: "Rahul", greet: () => { console.log(this.name); } }; user.greet(); // undefined ❌ ``` 👉 Arrow functions don’t have their own `this` 👉 They take it from **parent scope** --- 💻 Example 4 (Explicit Binding): ```js function greet() { console.log(this.name); } const user = { name: "Rahul" }; greet.call(user); // Rahul ✅ ``` --- 🔥 4 Golden Rules of `this`: 1. Global → window (or undefined in strict mode) 2. Implicit → object before dot 3. Explicit → call/apply/bind 4. New → new object created --- 💥 Interview Trap: 👉 Question: Why arrow functions are not suitable for object methods? ✅ Answer: Because they don’t have their own `this`, leading to unexpected results. --- 🎯 One Line to Remember: 👉 `this` = “Who is calling me?” --- #javascript #webdevelopment #frontend #reactjs #codinginterview #learnjavascript #developers #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 JavaScript Deep Dive – Revisiting Core Concepts Today I spent some focused time revising a few fundamental but powerful JavaScript concepts that form the backbone of modern frontend development. Even though we use these concepts daily while working with frameworks like React, revisiting them from a core JavaScript perspective always brings deeper clarity. Here’s what I revisited today: 🔹 Higher Order Functions (HOF) Understanding how functions can accept other functions as arguments or return functions. This concept powers methods like map, filter, and reduce, which are widely used in functional programming. 🔹 Closures One of JavaScript’s most powerful features. Closures allow functions to retain access to variables from their lexical scope even after the outer function has finished executing. This is heavily used in patterns like function factories, data encapsulation, and React hooks. 🔹 Destructuring (Arrays & Objects) A cleaner way to extract values from arrays and objects. It greatly improves readability and is used extensively when working with props, API responses, and state objects. 🔹 Shallow Copy vs Deep Copy Understanding how JavaScript handles object references in memory is crucial to avoid unintended mutations. Shallow copy → copies top-level properties Deep copy → creates a completely independent structure 🔹 Spread Operator (...) Very useful for copying objects, merging arrays, and maintaining immutability in modern JavaScript applications. 🔹 Rest Operator (...) Helps collect multiple values into a single array, commonly used in function parameters and destructuring. 💡 Big takeaway: Many advanced frameworks rely heavily on these fundamentals. The better we understand them, the easier it becomes to write clean, predictable, and maintainable code. Revisiting the basics often reveals insights we might miss while just focusing on frameworks. What JavaScript concept do you think every developer should revisit regularly? Ritik Rajput #JavaScript #WebDevelopment #FrontendDevelopment #CodingJourney #LearnInPublic #DeveloperGrowth #sheriyanscodingschool
To view or add a comment, sign in
-
🚀 Just published a new blog on Understanding Objects in JavaScript. In this article, I explain what objects are, why they are important in JavaScript, and how they store data using key–value pairs. I also covered creating objects, accessing properties using dot and bracket notation, updating values, adding or deleting properties, and looping through object keys. 📖 Read the full article here: https://lnkd.in/gbxx6N2G Inspired by the amazing teaching of Hitesh Choudhary Sir and Piyush Garg Sir from Chai Aur Code. ☕💻 #javascript #webdevelopment #learninginpublic #chaiAurCode
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