✅ JavaScript Output — Let’s Understand Why This Happens This morning’s code was: let a = []; let b = []; console.log(a == b); console.log(a === b); let c = a; console.log(a === c); 💡 Correct Output false false true Simple Explanation : 🔹 Step 1: let a = []; let b = []; Even though both look the same ([]), JavaScript creates two different arrays in memory. So: a → one memory reference b → another memory reference 🔹 console.log(a == b); == checks value/reference. Since a and b point to different arrays, the result is: false ✔ Output: false 🔹 console.log(a === b); === checks value + type. But for objects/arrays, this really means: Are both variables pointing to the same memory location? They are not. So: false ✔ Output: false 🔹 let c = a; Now c points to the same array as a. So: a and c share the same memory reference 🔹 console.log(a === c); Now JavaScript checks: Same reference? → Yes So: true ✔ Output: true 🎯 Key Takeaways : Arrays and objects are reference types [] == [] and [] === [] are always false Two arrays with the same content are still different in memory Equality checks compare references, not structure 📌 That’s why in real code, we don’t compare arrays directly. 💬 Your Turn Did you already know this behavior? Comment “Knew it 👍” or “Learned today 😮” #JavaScript #FrontendDevelopment #LearnJS #CodingInterview #Arrays #TechWithVeera #WebDevelopment #100DaysOfCode Export Message as PDF
JavaScript Array Reference Equality Explained
More Relevant Posts
-
✅ JavaScript Output — Functions vs Function Calls Explained This morning’s code was: function greet() { return "Hello"; } console.log(typeof greet); console.log(typeof greet()); console.log(greet instanceof Object); 💡 Correct Output function string true 🧠 Simple Explanation : 🔹 Line 1: typeof greet Here, we are not calling the function. We are just referring to it. In JavaScript: A function itself is a special type of object typeof a function returns "function" ✔ Output: function 🔹 Line 2: typeof greet() Now the function is called. greet() // returns "Hello" So this becomes: typeof "Hello" Since "Hello" is a string, ✔ Output: string 🔹 Line 3: greet instanceof Object This checks: “Is greet an object?” In JavaScript: Functions are objects They can have properties and methods So the answer is: ✔ Output: true 🎯 Key Takeaways : typeof functionName → "function" typeof functionName() → type of returned value Functions are objects in JavaScript That’s why functions can have properties like: greet.customProp = "test"; 📌 This is why JavaScript is called a first-class function language. 💬 Your Turn Did you already know functions are objects in JavaScript? Comment “Knew it 👍” or “Learned today 😮” #JavaScript #FrontendDevelopment #LearnJS #CodingInterview #Functions #TechWithVeera #WebDevelopment #100DaysOfCode
To view or add a comment, sign in
-
-
The JavaScript Feature That Simulates Private Variables 🔒 Let’s talk about one of JavaScript’s most powerful, yet often misunderstood features: Closures. Many developers struggle with the concept initially, but once it clicks, it changes how you architect your code. At its core, a closure gives you access to an outer function’s scope from an inner function. The magic happens because the inner function "remembers" the environment in which it was created, even after the outer function has finished executing. Why is this useful? JavaScript doesn't have native "private" variables in the traditional OOP sense (though class fields are changing this). Closures allow us to emulate data privacy. Look at this classic example: creates a counter where the count variable is completely inaccessible from the outside world except through the returned increment function. function createCounter() { let count = 0; // This variable is now "private" return function() { count++; return count; }; } const counter = createCounter(); console.log(counter()); // 1 console.log(counter()); // 2 // console.log(count); // ReferenceError: count is not defined You cannot accidentally modify count from the global scope. You have created a protected state. Are you using closures intentionally in your codebase today? #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #Closures
To view or add a comment, sign in
-
-
JavaScript Constructor Function || More Than Just Object Creation 🙂 In JavaScript, a constructor function is not only used to create objects. When combined with closures, it becomes a powerful tool for data encapsulation. function Counter() { let count = 0; this.increment = function () { count++; console.log(count); }; this.decrement = function () { count--; console.log(count); }; } const counter = new Counter(); Here, count is a private variable. It cannot be accessed or modified directly from outside the function. The methods increment and decrement form a closure over count, which allows them to remember and update its value even after the constructor has finished executing. The new keyword creates a new object and binds this to it, turning these functions into public methods while keeping the state private. This pattern is especially useful for: • Encapsulating internal state • Avoiding global variables • Writing predictable and maintainable JavaScript #JavaScript #JavaScriptClosure #ConstructorFunction #FrontendDevelopment #WebDevelopment #SoftwareEngineering #ProgrammingConcepts #JavaScriptTips #CleanCode #CodingLife #DeveloperCommunity #LearnJavaScript #JSDevelopers #FrontendEngineer #TechLearning #CodeUnderstanding JavaScript Mastery JavaScript Developer
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
-
-
✅ JavaScript Output — Let’s Understand Why This Happens This morning’s code was: let x = 0; if (x) { console.log("Inside if"); } else { console.log("Inside else"); } console.log(Boolean(x)); 💡 Correct Output Inside else false 🧠 Simple Explanation : 🔹 Step 1: Understanding the if condition In JavaScript, if does not check for true or false only. It checks whether a value is truthy or falsy. Here’s the key rule 👇 👉 0 is a falsy value in JavaScript. So when JavaScript evaluates: if (x) // x = 0 It treats 0 as false. That’s why the if block is skipped and the else block runs. ✔ Output: Inside else Step 2: Boolean(x) Now we explicitly convert x into a boolean: Boolean(0) Since 0 is falsy, it becomes: false ✔ Output: false 🎯 Key Takeaways : 0 is falsy if (x) checks truthy / falsy, not strict booleans Boolean(value) shows how JavaScript internally treats a value 📌 Common falsy values in JS: javascript Copy code false, 0, "", null, undefined, NaN 💬 Your Turn Did you already know 0 is falsy? Comment “Knew it 👍” or “Learned today 😮” #JavaScript #FrontendDevelopment #LearnJS #CodingInterview #TruthyFalsy #TechWithVeera #WebDevelopment #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 JavaScript Maps (Key–Value Pairs) — A Cleaner Way to Store Data. Today I learned about Map in JavaScript, and it’s much more powerful than using plain objects in many cases. A Map stores data in key–value pairs, just like objects — but with important advantages. 🔹 Why use Map instead of an Object? ✅ Keys can be any data type (object, function, number, etc.) ✅ Maintains insertion order ✅ Built-in methods for easy operations ✅ Better performance for frequent additions/removals 🔹 Simple example: const userMap = new Map(); userMap.set("name", "Sourav"); userMap.set("role", "Developer"); userMap.set(1, "ID"); console.log(userMap.get("name")); // Sourav 🔹 Useful methods: set(key, value) → add/update get(key) → access value has(key) → check existence delete(key) → remove size → total entries 💡 Real-world use cases: Caching API responses Managing user sessions Handling complex keys in applications Learning these core JavaScript concepts deeply is helping me write more efficient and readable code. 📌 If you’re learning JS, don’t skip Map — it’s a small concept with big impact. 👉 Do you prefer Object or Map in your projects? Let’s discuss 👇 #JavaScript #WebDevelopment #LearningInPublic #FrontendDevelopment #MERN #CodingJourney #DeveloperLife
To view or add a comment, sign in
-
-
✅ What is for...of in JavaScript? For...of loop — JavaScript’s way of saying “Relax, I’ve got the iteration covered.” 😄 Let’s walk through examples and then when you should (and shouldn’t) use it. for...of is used to iterate over iterable values — not indexes, but the actual elements. Works with: • Arrays • Strings • Maps • Sets • NodeLists • Any iterable object 🔹 Basic for...of Example (Array) const fruits = ["Apple", "Banana", "Mango"]; for (const fruit of fruits) { console.log(fruit); } 👉 You get values directly, not indexes. 🔹 for...of with async / await (🔥 Killer Feature) async function processOrders(orders) { for (const order of orders) { await process(order); } } ⚠️ forEach cannot handle await properly. ✅ for...of is the correct choice here. 🧠 Best Use Cases for for...of ✅ When you want simple, readable iteration ✅ When you need async/await ✅ When you may need break / continue ✅ When iterating Maps, Sets, NodeLists ✅ When you care about values, not indexes 🚫 When NOT to use for...of ❌ When iterating plain objects (use Object.entries) ❌ When you need index-based logic ❌ When you want pure functional chaining (map, filter)
To view or add a comment, sign in
-
Do you know how to create custom arrays in #JavaScript? If yes, I am happy. Let me explain how we can create custom arrays and on what purposes it helps to us. In JavaScript, arrays are just objects under the hood. That means you can build your own array-like structure with: Custom method names, Full control over behavior, Extra properties if needed. This is especially useful when: If you want clearer method names If you’re learning data structures If you want to override or extend array behavior Here's an example, to create custom arrays: class myArr { constructor() { this.length = 0 this.data = {} } push(item) { this.data[this.length] = item this.length++ return this.length } pop() { const lastElem = this.data[this.length - 1] delete this.data[this.length - 1] this.length-- return lastElem } } const myNewArr = new myArr() myNewArr.push("apple") myNewArr.push("mango") myNewArr.push("banana") myNewArr.pop() console.log(myNewArr) By doing this, you can learn how arrays really work and you can improve problem-solving skills as well. You can try and comment with shift method implementation. If you’re serious about mastering JS, this concept is worth understanding.
To view or add a comment, sign in
-
-
💡 JavaScript Tip: Template Literals Make Strings Cleaner - Backtick (``) means more than you think! Honestly, I thoughy backticks, quotes and double quotes are like take one hit another type. I was wrong!!! One of the most practical features in modern JavaScript is template literals. Instead of building strings with + and escape characters, template literals let you write strings the way they actually look. 🔹 They use backticks (`) 🔹 They support string interpolation (Note:String interpolation is the ability to insert variables or expressions directly into a string, so the final text is built automatically at runtime.) 🔹 They preserve line breaks naturally Example: const name = "Alice"; const age = 25;const message = `My name is ${name}and I am ${age} years old.`; console.log(message); No +, no \n, no clutter. Even better, you can embed real JavaScript expressions: const score = 9.5; const output = `Final score: ${(score / 10) * 100}%`; ✨ Why this matters: Code becomes more readable Multiline strings are effortless Dynamic text is easier to maintain If you're still concatenating strings with +, template literals are a small change that makes a big difference in day-to-day JavaScript work. #JavaScript #WebDevelopment #CleanCode #ProgrammingTips #ES6 20:25–28 "My Lord, expand for me my chest, and ease for me my task, and untie the knot from my tongue, so that they may understand my speech."
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
-
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
Learned something new again today