Is JS pass by value or reference ? What we generally think ? Primitives are passed by value; objects are passed by reference. The most shared example to validate this claim is const changeObj = (obj) => { obj.key1 = "value2"; console.log(obj.key1); // value2 }; const obj = { key1: "value1" }; console.log(obj.key1); // value1 changeObj(obj); console.log(obj.key1); // value2 Asking: what is pass by reference ? True References are Aliases. They actually share the same address. If you know a bit of C++, then you can understand this easily. #include <iostream> void swap(int& a, int& b) { int temp = a; a = b; b = temp; } int main() { int x = 5; int y = 6; // The values of x and y actually swap here. x = 6, y = 5 swap(x, y); } What javascript object references are ? JS object references are pointers. The variable points to object in memory. But if you try to reassign that variable inside a function to point to a completely new object? The original variable doesn't care. It still points to the original object. You can modify properties through the reference ✅ But you can't reassign the original variable ❌ Sources: 1. https://lnkd.in/gE7Zasm3 2. https://lnkd.in/ghvff7ED #javascript #til
JS Objects: Pass by Reference or Value?
More Relevant Posts
-
Most of us use === in JavaScript without understanding why it's safer than ==. Here's the difference. When you write a === b, JS checks 2 things: 1. Are the types the same? 2. Are the values the same? No type changes, no surprises; that's why === is the default choice in most comparisons. But == plays by different rules. When the type differs, JS tries to convert one or both values into a comparable type. This is called type coercion, and it follows a defined order. One use for == is when you want to check for an empty value. if (value == null) {}, checks for both null and undefined because empty values are treated as equivalent. Another use is when dealing with user input like form fields. if (age == 18) {..} This would match "18" or 18 because the string gets converted to a number. But sometimes it becomes a trap. 0 == "" // true "0" == 0 //true [] == "" //true [] == 0 //true This is why we run to === for safety. When booleans are involved, JS converts them first because they have a clear numeric conversion path. true -> 1 and false -> 0, compared to strings, which are messy. === is strict and safe. == is flexible—but only use it when you really know how coercion works. Learn more: https://lnkd.in/dxQGaF2X Quiz: What does false == "0" evaluate to?
To view or add a comment, sign in
-
-
🧠 JavaScript Problem: Check if a String is a Palindrome A palindrome is a word that reads the same backward as forward. Example: "madam", "level", "racecar" ✅ Solution 1: Using Built-in Methods function palindrome(str) { const reverseStr = str.split("").reverse().join(""); return str === reverseStr; } console.log(palindrome("abccba")); // true console.log(palindrome("abed")); // false Time Complexity: O(n) Space Complexity: O(n) ⚡ Solution 2: Using Two Pointers (Optimized) function palindrome(str) { let left = 0; let right = str.length - 1; while (left < right) { if (str[left] !== str[right]) { return false; } left++; right--; } return true; } console.log(palindrome("abccba")); // true console.log(palindrome("abed")); // false Time Complexity: O(n) Space Complexity: O(1) 💡 Note: Although both solutions have the same time complexity, Solution 2 is better because it uses constant space (O(1)), making it more efficient for large strings
To view or add a comment, sign in
-
-
We've all been there: needing to add a sprinkle of logic *before* an object's method runs, or *after* a property is set, without cluttering the main class. My initial approach? Often a messy 'if' block or trying to shoehorn it into the original logic. 😩 That's where the JavaScript Proxy object truly shines. It’s like having a middleware layer for your objects. You define custom behavior for fundamental operations (like property lookup, assignment, enumeration, function invocation) through a 'handler' object. I remember a project where we needed robust input validation across multiple client-side forms. Instead of scattering validation logic everywhere, we used Proxies to intercept property assignments to our data models. This kept our core model logic clean and all validation concerns neatly bundled in one handler. It was a game-changer for 𝗖𝗼𝗱𝗲 𝗖𝗹𝗮𝗿𝗶𝘁𝘆. Another time, I used it for simple access control on a configuration object, preventing direct writes to sensitive properties without explicit permissions. It makes you think differently about object interaction, focusing on 𝗦𝗲𝗽𝗮𝗿𝗮𝘁𝗶𝗼𝗻 𝗼𝗳 𝗖𝗼𝗻𝗰𝗲𝗿𝗻𝘀. If you haven't explored them, I highly recommend it for cleaner, more maintainable code. I've included a simple code example in the comments to illustrate how straightforward it can be! How have you leveraged JavaScript Proxies in your projects? Or what's a design pattern that unexpectedly solved a big problem for you? Share your experiences below! 👇 #JavaScript #DesignPatterns #SoftwareArchitecture #WebDevelopment
To view or add a comment, sign in
-
-
😩 I changed one object... and everything else broke. Classic JavaScript moment. You think you’ve copied an object — but you’ve only cloned the surface. Here’s what happened to me recently 👇 const user = { name: "John", address: { city: "Berlin" } }; const clone = { ...user }; clone.address.city = "Paris"; console.log(user.address.city); // 😱 "Paris" Wait — what?! I just wanted a copy… not to move the entire family. 🧠 What’s going on? The spread operator { ...obj } or Object.assign() only makes a shallow copy. That means nested objects or arrays still share references with the original. So when you mutate one, the other changes too. ✅ The Fix If you need a deep copy, you have a few safe options: // 1️⃣ Simple & built-in (modern JS) const deepClone = structuredClone(user); // 2️⃣ Old-school workaround const deepClone = JSON.parse(JSON.stringify(user)); // 3️⃣ For complex cases (like Dates, Maps, etc.) import _ from "lodash"; const deepClone = _.cloneDeep(user); Now user and deepClone are fully independent. 💡 Takeaway > A shallow copy copies values. A deep copy copies the entire structure. Know which one you need — or your state bugs will come back to haunt you. 👻 🗣️ Your Turn Have you ever been burned by this shallow copy issue? What’s your go-to method for safe cloning? #JavaScript #WebDevelopment #CodingTips #FrontendDevelopment #CleanCode #ProgrammingBugs #ES6 #CodeSmarter #DevCommunity
To view or add a comment, sign in
-
-
🔥 JS Loops Demystified: for vs for…in vs for…of If you’ve ever wondered which loop to use in JavaScript, you’re not alone. Choosing the wrong one can cause subtle bugs! Here’s a quick guide: 1️⃣ Classic for loop – The old reliable const arr = [10, 20, 30]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } Use when you need index access, or want full control over iteration. 2️⃣ for…in loop – Iterate over keys (property names) const arr = [10, 20, 30]; for (let key in arr) { console.log(key); // 0, 1, 2 } Works on objects too. ⚠️ Can be dangerous for arrays — also loops over inherited properties. 3️⃣ for…of loop – Iterate over values const arr = [10, 20, 30]; for (let value of arr) { console.log(value); // 10, 20, 30 } Perfect for arrays, strings, maps, sets. Safe, clean, and readable. 💡 Pro tip: Use for when you need the index. Use for…of for values (most array iterations). Avoid for…in on arrays — reserve it for objects. Small choice, huge impact on readability and bug prevention. #JavaScript #CodingTips #WebDevelopment #FrontendDev #CleanCode #JSProTips #ForOfVsForIn
To view or add a comment, sign in
-
Why 0.1 + 0.2 0.3 in JavaScript: The Truth About Floating-Point Numbers Why 0.1 + 0.2 ≠ 0.3 in JavaScript If you’ve ever typed this into your console: 0.1 + 0.2 === 0.3 // false console.log(0.1 + 0.2) // 0.30000000000000004 …and felt confused, you’re not alone. This tiny difference has confused developers for years, but once you understand floating-point numbers, it all makes sense. JavaScript stores every number (except BigInt) as a 64-bit IEEE 754 floating-point value. That means numbers are represented in binary, not decimal. And here’s the problem: Some decimal numbers simply can’t be represented exactly in binary form. For example: 1/3 is an infinite repeating decimal in base 10: 0.333333... Similarly, 0.1 is an infinite repeating fraction in base 2 (binary). JavaScript can’t store infinite digits, so it rounds the value slightly. That’s why when you add 0.1 + 0.2, you get 0.30000000000000004. Every floating-point number is stored as three parts: Sign bit (positive or negative) Exponent (how large or small the number is) Mantissa (the precis https://lnkd.in/gTu_5jpP
To view or add a comment, sign in
-
How JavaScript Magically Knows What an Object Is Worth Ever wondered how JavaScript knows what to do when you compare or add objects, like {} + {} without throwing an error? That’s where valueOf() quietly steps in. 🔍 What It Actually Does When JavaScript needs to convert an object to a primitive (like during comparison, math operations, or string concatenation), it follows this internal process: - Calls the object’s valueOf() method first. - If that doesn’t return a primitive value, it tries toString() next. - If both fail, you get a TypeError. This entire process is handled by the ToPrimitive abstract operation defined in the ECMAScript spec, it decides how and when conversions happen. 🧠 Under the Hood Every JS object inherits a default valueOf() from Object.prototype. By default, it just returns the object itself (this). But you can override it to define custom behavior. const score = { value: 100, valueOf() { return this.value; // return primitive number }, }; console.log(score + 20); // 120 When + is used, JavaScript tries to coerce the object, it finds your valueOf() and uses its result.
To view or add a comment, sign in
-
JavaScript — Pass by Reference and Pass by Value (Made Simple) If you ever changed one variable and somehow another one also changed — Pass by Value and Pass by Reference. Let’s understand both of them clearly with small examples. Primitive types in JavaScript are — string, number, boolean, bigint, null, and undefined. These are simple. When you assign or pass them, copy of the actual value and allocates separate memory pointing to a new address. let a = 12; let b = a; b = 13; console.log(b, a); // 13, 12 👉 a and b are two different boxes. Primitive = always copied by value Now let’s discuss about Non-Primitive types. Now this is where confusion starts. reference (memory address) where the value is stored. So when you assign one object or array to another variable, That’s why when you change one, the other also changes. const a = [1, 2, 3, 4, 5]; const b = a; b.pop(); console.log(b, a); // both will print the same - [1, 2, 3, 4] Here, both a and b point to the same array in memory. b, 🧩 Changing (mutating) means both get affected. But her https://lnkd.in/gFKiXCrE
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
💡