𝕎𝕙𝕪 [] === [] 𝕚𝕤 𝔽𝕒𝕝𝕤𝕖 (𝕒𝕟𝕕 𝕨𝕙𝕪 𝕚𝕥 𝕓𝕣𝕖𝕒𝕜𝕤 𝕪𝕠𝕦𝕣 ℝ𝕖𝕒𝕔𝕥 𝔸𝕡𝕡𝕤) In JavaScript, primitives (Strings, Numbers, Booleans) are compared by value. But Objects and Arrays are compared by reference. Why does this happen? When you create an array or object, JavaScript allocates a specific spot in memory. Even if the content is identical, list1 and list2 point to different memory addresses. Why this matters in the MERN Stack: 1️⃣ In React (Optimization): If you pass an inline array options={['a', 'b']} as a prop, React sees a "new" reference on every single render. This can trigger unnecessary re-renders of child components, killing performance. Use useMemo or keep constants outside the component to preserve the reference. 2️⃣ In Dependency Arrays: Using an object or array inside a useEffect dependency array without memoization will cause the effect to run on every render, potentially creating an infinite loop. 3️⃣ In State Updates: This is why we use the spread operator [...prevItems]. We must create a new reference for React to "notice" that the state has changed and trigger a UI update. The Takeaway: Always be mindful of where your objects are created. If you don't control your references, you don't control your performance. #JavaScript #ReactJS #WebDevelopment #ProgrammingTips #Frontend #SoftwareEngineering
JavaScript Object Comparison by Reference Explained
More Relevant Posts
-
JavaScript Prototypes — the part most people misunderstand Most JavaScript magic comes from one rule: Property access walks the prototype chain The lookup rule (exactly how JS works) When you do: obj.key JavaScript checks in this order: obj obj.__proto__ obj.__proto__.__proto__ …until null No copying. Only delegation. prototype vs __proto__ (interview classic) function Person(name) { this.name = name; } const p = new Person("Alex"); What’s actually true: p.__proto__ === Person.prototype prototype → property of constructor functions __proto__ → internal link on objects new connects them Why methods belong on prototype Person.prototype.sayHi = function () { return "Hi " + this.name; }; One function in memory Shared by all instances Faster & cleaner than redefining per object The dangerous part ⚠️ Person.prototype.age = 25; You didn’t update one object. You updated every object linked to that prototype. This is how global bugs are born. Mental model 🧠 Objects don’t inherit properties. They delegate lookups. Senior takeaway 🥇 If you understand prototypes: class becomes obvious this makes sense Method sharing is clear Many “weird JS bugs” disappear #javascript #advancedjs #interviewprep #frontend #softwareengineering
To view or add a comment, sign in
-
🧠 What Is Lexical Scope in JavaScript? If you’ve ever wondered how JavaScript knows which variable to use, the answer is Lexical Scope 👇 --- 🔍 What Does Lexical Mean? Lexical means where the code is written, not where it is executed. JavaScript determines variable access at compile time, based on the physical structure of the code. --- 📦 What Is Lexical Scope? Lexical scope defines: ➡️ Which variables are accessible ➡️ Where in the code A function can access: ✔ Its own variables ✔ Variables from its outer (parent) scope --- 🧪 Simple Example function outer() { let name = "JS"; function inner() { console.log(name); } inner(); } outer(); ✅ inner() can access name ❌ outer() cannot access variables inside inner() --- 🔒 Scope Chain When JavaScript looks for a variable: 1️⃣ It checks the current scope 2️⃣ Then the outer scope 3️⃣ Continues until global scope If not found → ❌ ReferenceError --- ⚛️ Lexical Scope vs Dynamic Scope ✔ JavaScript → Lexical ❌ Not based on call stack ❌ Not based on runtime execution This is why closures work in JavaScript. --- 🎯 Why Lexical Scope Matters 🔥 Enables closures 🔥 Prevents variable conflicts 🔥 Makes code predictable 🔥 Foundation of modern JS frameworks Without lexical scope — JavaScript wouldn’t behave consistently. --- 🧠 In One Line 📌 Lexical scope is determined by where functions are defined, not where they are called. Master this concept and half of JavaScript becomes clear 🚀 --- #JavaScript #LexicalScope #Closures #WebDevelopment #FrontendDevelopment #BackendDevelopment #CleanCode #JavaScriptConcepts #JSInterview #InterviewPrep #TechLearning #Developers #100DaysOfCode
To view or add a comment, sign in
-
-
20 JavaScript Questions Every Developer Should Know 1. What is the difference between map(), filter(), and reduce()? 2. Explain the difference between function declarations and function expressions 3. What is the spread operator and rest parameter? 4. How does JavaScript handle type coercion? 5. What are higher-order functions? 6. Explain callback functions and callback hell. 7. What is memoization and why is it useful? 8. What are template literals and their advantages? 9. Explain the concept of currying 10. What is the difference between slice() and splice()? 11. What is the difference between innerHTML, textContent, and innerText? 12. Explain how the setTimeout and setInterval functions work 13. What are JavaScript modules and why are they important? 14. What is the difference between for...in and for...of loops? 15. Explain what IIFE (Immediately Invoked Function Expression) is. 16. What is the arguments object and how does it differ from rest parameters? 17. Explain the difference between Object.freeze() and Object.seal() 18. What are Web APIs and how do they relate to JavaScript? 19. What is NaN and how do you check for it? 20. Explain the concept of debouncing and throttling 𝐠𝐞𝐭 𝐞𝐛𝐨𝐨𝐤 𝐰𝐢𝐭𝐡 (detailed 232 ques = 90+ frequently asked Javascript interview questions and answers, 70+ Reactjs Frequent Ques & Answers, 50+ Output based ques & ans, 23+ Coding Questions & ans, 2 Machine coding ques & ans) 𝐄𝐛𝐨𝐨𝐤 𝐋𝐢𝐧𝐤: https://lnkd.in/gJMmH-PF Follow on Instagram : https://lnkd.in/gXTrcaKP #javascript #javascriptdeveloper #reactjs #reactnative #vuejsdeveloper #angular #angulardeveloper
To view or add a comment, sign in
-
A solid foundation in JavaScript is crucial for developers. Recently, I came across a thought-provoking post by Sai Krishna Nangunuri, presenting 20 JavaScript questions every developer should know. These questions not only challenge our understanding but also sharpen our problem-solving skills. If you're looking to dive deeper, consider exploring resources that compile such important questions, including interview prep materials that cover various aspects of JavaScript and frameworks like React. #javascript #reactjs
Lead Engineer @ Inspire | Educator Influencer | 130k+ on Instagram | 23k+ on Linkedin | 22k+ on youtube | Full stack Reactjs developer
20 JavaScript Questions Every Developer Should Know 1. What is the difference between map(), filter(), and reduce()? 2. Explain the difference between function declarations and function expressions 3. What is the spread operator and rest parameter? 4. How does JavaScript handle type coercion? 5. What are higher-order functions? 6. Explain callback functions and callback hell. 7. What is memoization and why is it useful? 8. What are template literals and their advantages? 9. Explain the concept of currying 10. What is the difference between slice() and splice()? 11. What is the difference between innerHTML, textContent, and innerText? 12. Explain how the setTimeout and setInterval functions work 13. What are JavaScript modules and why are they important? 14. What is the difference between for...in and for...of loops? 15. Explain what IIFE (Immediately Invoked Function Expression) is. 16. What is the arguments object and how does it differ from rest parameters? 17. Explain the difference between Object.freeze() and Object.seal() 18. What are Web APIs and how do they relate to JavaScript? 19. What is NaN and how do you check for it? 20. Explain the concept of debouncing and throttling 𝐠𝐞𝐭 𝐞𝐛𝐨𝐨𝐤 𝐰𝐢𝐭𝐡 (detailed 232 ques = 90+ frequently asked Javascript interview questions and answers, 70+ Reactjs Frequent Ques & Answers, 50+ Output based ques & ans, 23+ Coding Questions & ans, 2 Machine coding ques & ans) 𝐄𝐛𝐨𝐨𝐤 𝐋𝐢𝐧𝐤: https://lnkd.in/gJMmH-PF Follow on Instagram : https://lnkd.in/gXTrcaKP #javascript #javascriptdeveloper #reactjs #reactnative #vuejsdeveloper #angular #angulardeveloper
To view or add a comment, sign in
-
Mastering Set in JavaScript Set in JavaScript allows us to store unique values only. Arrays can do something similar but there are important differences we should know. In this post, we’ll explore how Set works and when to use it. For the full comparison with Array, please watch the video. A Set is an unordered collection that stores only unique values and is optimised for quick existence checks. 🔹 Create a Set const mySet = new Set([1,2,3]); 🔹 Add values mySet.add(4); If we try to add a duplicate value: mySet.add(3); it will be ignored, because a Set only stores unique values. We can also add strings, arrays, and objects in the same way. In the case of objects though, a Set treats values as duplicates if they share the same reference. const a = {id: 1}; mySet.add(a); mySet.add(a); 🔹 Finding values Unlike arrays, Sets don’t have indexes, so values can’t be accessed by position. Instead, values are accessed through iteration using forEach or for...of: mySet.forEach((value) => console.log(value)); or for (const value of mySet) { console.log(value); } There is no index available during iteration. 🔹 Remove or clear values: mySet.delete(2); mySet.clear(); 🔹 Check for value: mySet.has(2); 🔹 Get size: mySet.size; Use a Set when we need to track only unique values and want fast checks to see if something already exists. #frontend #javascript #set #array
To view or add a comment, sign in
-
One of the most common bugs in JavaScript and React comes from copying objects the wrong way 😅 Shallow Copy vs Deep Copy In JavaScript, when you copy an object using the spread operator (...), you are only creating a shallow copy. Example: ``` const user = { name: “Ali”, skills: [“JS”, “React”] }; const copy = { …user }; copy.skills.push(“Node”); console.log(user.skills); // [“JS”, “React”, “React”, “Node”] ``` Why did the original object change? Because: • name was copied • but skills is still pointing to the same array in memory Both user.skills and copy.skills reference the same place. To create a real independent copy, use: const deepCopy = structuredClone(user); Now changing deepCopy will not affect user. 📌 In React, this mistake can cause: • state bugs • missing re-renders • very confusing UI issues Understanding how memory and references work is a game changer. #JavaScript #React #Frontend #WebDevelopment #Programming
To view or add a comment, sign in
-
JavaScript objects don’t behave the way many people expect. ✔ The output of the code in the picture will be: [ { id: 1, name: "Updated John" }, { id: 2, name: "Jane" } ] This surprises many people, but it is completely expected behavior in JavaScript. 🤔Why this happens? → Arrays in JavaScript store references to objects → Array.find() returns the actual object, not a copy → Objects are reference types, not value types So after this line: const foundUser = users.find(u => u.id === 1); 👉 Both of these point to the same object in memory: users[0] ────┐ ├──► { id: 1, name: "John" } foundUser ───┘ 👉 When you do: foundUser.name = "Updated John"; You are mutating that shared object. Since the array holds a reference to the same object, the array reflects the change. 💡 A safer approach is to update immutably (create a new array and a new object): const updatedUsers = []; const updatedUsers = users.map(user => user.id === 1 ? { ...user, name: "Updated John" } : user ); ▶ But remember: { ...user } is a shallow copy. If user contains nested objects, those nested references are still shared. In that case, you must copy the nested structure you modify, or use a deep clone. ▶ There is another option which is called structuredClone(). This function returns a deep copy of the object you are passing as an argument. const copy = structuredClone(user); Now mutating copy won’t affect the original object. #JavaScript #WebDevelopment #Coding
To view or add a comment, sign in
-
-
🔒 𝙅𝙖𝙫𝙖𝙎𝙘𝙧𝙞𝙥𝙩 𝙋𝙧𝙞𝙫𝙖𝙩𝙚 𝙁𝙞𝙚𝙡𝙙𝙨 𝙞𝙣 𝘼𝙘𝙩𝙞𝙤𝙣: 𝘽𝙪𝙞𝙡𝙙𝙞𝙣𝙜 𝙖 𝙎𝙞𝙢𝙥𝙡𝙚 𝘽𝙖𝙣𝙠 𝘼𝙘𝙘𝙤𝙪𝙣𝙩 𝘾𝙡𝙖𝙨𝙨 One of the best modern JavaScript features? Private class fields using # true encapsulation, finally native in JS! 🚀 Here’s a clean example of how to use them: class Account { #balance; constructor(balance) { this.#balance = balance; } deposit(amount) { this.#balance += amount; } withdraw(amount) { if (this.#balance >= amount) { this.#balance -= amount; } } getBalance() { return this.#balance; } } No more relying on conventions like _balance or closures #balance is actually private and can't be accessed or modified directly from outside the class. Perfect for modeling real-world objects securely in your frontend (or backend) apps. What’s your favorite modern JS feature for writing cleaner, safer code? Private fields, optional chaining, nullish coalescing, or something else? Let me know in the comments! 👇 #JavaScript #WebDevelopment #Frontend #ModernJavaScript #CodingTips #Developers
To view or add a comment, sign in
-
-
✅ JavaScript Output — Understanding Object Properties Clearly This morning’s code was: let user = { name: "Veera" }; console.log(user.name); console.log(user.age); console.log("age" in user); console.log(user.hasOwnProperty("age")); 💡 Correct Output Veera undefined false false 🧠 Simple Explanation : 🔹 Line 1: console.log(user.name); The property name exists in the object. So JavaScript prints: Veera 🔹 Line 2: console.log(user.age); The property age does not exist in the object. When you access a missing property, JavaScript does not throw an error — it simply returns: undefined ✔ Missing property ≠ error. 🔹 Line 3: "age" in user The in operator checks: “Does this property exist in the object (or its prototype)?” Since age is not present anywhere, the result is: false 🔹 Line 4: user.hasOwnProperty("age") This checks: “Is this property defined directly on this object?” Again, age is not defined on user. So the result is: false 🎯 Key Takeaways : Accessing a missing property returns undefined "key" in object checks existence, not value hasOwnProperty() checks only direct properties undefined value ≠ property exists 📌 This distinction is very important when working with: APIs Forms Optional data 💬 Your Turn Did you know the difference between undefined, in, and hasOwnProperty? Comment “Clear now ✅” or “Learned today 🙌” #JavaScript #FrontendDevelopment #LearnJS #CodingInterview #Objects #TechWithVeera #WebDevelopment #100DaysOfCode
To view or add a comment, sign in
-
-
📚 JavaScript Array Methods – Cheat Sheet 🚀 Save this post 🔖 — you’ll thank yourself later! 🔁 Iteration arr.forEach(fn) // Loop without return arr.map(fn) // Transform array 🔍 Search & Check arr.find(fn) // First match arr.findIndex(fn)// Index of match arr.includes(x) // true / false arr.some(fn) // Any match? arr.every(fn) // All match? 🎯 Filter & Reduce arr.filter(fn) // Subset arr.reduce(fn, i)// Accumulate to single value 🔀 Add / Remove arr.push(x) // Add end arr.pop() // Remove end arr.unshift(x) // Add start arr.shift() // Remove start ✂️ Modify arr.slice(a, b) // Non-mutating copy arr.splice(a,n) // Mutates array 🔃 Reorder arr.sort(fn) // Sort arr.reverse() // Reverse 🔗 Combine & Convert arr.concat(b) // Merge arrays arr.join(',') // Array → String Array.from(x) // Convert to array 📦 Flatten & Fill arr.flat(n) // Flatten depth n arr.fill(x) // Fill values 💡 Tip: 👉 Prefer map, filter, reduce for clean & functional code 👉 Avoid mutating methods in large apps unless required If you’re preparing for JS interviews or working daily with Angular / React, this cheat sheet is gold ✨ #JavaScript #WebDevelopment #Frontend #Angular #React #CodingTips #LinkedInLearning
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
They are stored at different memory address