📊 Day 13 – Poll Answer & Explanation ```javascript const a = [1, 2, 3]; const b = a; b.push(4); console.log(a); console.log(b); ``` ### ❓ What will be the output? ## ✅ Correct Answer: **B** ``` [1,2,3,4] [1,2,3,4] ``` --- ## 📌 Step-by-Step Explanation **1️⃣ Arrays are Reference Types** In **JavaScript**, arrays are **objects**. Objects are stored in **memory by reference**, not by value. --- **2️⃣ Assigning `b = a`** ```javascript const b = a; ``` This **does NOT create a new array**. Instead, **both `a` and `b` point to the same array in memory**. ``` a ──► [1,2,3] b ──► ``` --- **3️⃣ Modifying the Array** ```javascript b.push(4); ``` Since **`b` references the same array**, the original array is modified. ``` a ──► [1,2,3,4] b ──► ``` --- **4️⃣ Final Output** ```javascript console.log(a); // [1,2,3,4] console.log(b); // [1,2,3,4] ``` Both variables print the **same updated array**. --- ## 💡 Key Takeaway 👉 **Arrays and objects in JavaScript are stored by reference.** 👉 If multiple variables reference the **same object**, modifying one **affects all of them**. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #CodingInterview #DeveloperCommunity #100DaysOfCode #LearnToCode
JavaScript Arrays Stored by Reference
More Relevant Posts
-
Catching bugs at 2:00 PM but they don’t wake me up at 2:00 AM. 🛠️ Moving from #JavaScript to #TypeScript wasn’t just a syntax change; it was a shift in confidence. By defining our data structures upfront, we’ve effectively eliminated the "undefined is not a function" errors that used to haunt our production logs. The Difference: In JS, you pass an object and hope the property exists. In TS, the editor won't even let you save the file until you've handled the possibility of it being missing. Example: // JavaScript: The "Finger-Crossing" Method function getUsername(user) { return user.profile.name; // Runtime Error if profile is missing! } // TypeScript: The "Contract" Method interface User { profile?: { name: string }; } function getUsername(user: User) { return user.profile?.name ?? "Guest"; // Type-safe and explicit } The initial setup takes a few extra minutes, but the hours saved in debugging are immeasurable. Have you made the switch yet? Or are you still team Vanilla? 👇 #WebDevelopment #TypeScript #SoftwareEngineering #Coding
To view or add a comment, sign in
-
-
💡 Pass by Value vs Pass by Reference in JavaScript (Simple Explanation) If you're learning JavaScript, understanding how data is passed is crucial 👇 🔹 Pass by Value (Primitives) When you assign or pass a primitive type (number, string, boolean, null, undefined, symbol, bigint), JavaScript creates a copy. let a = 10; let b = a; b = 20; console.log(a); // 10 console.log(b); // 20 👉 Changing b does NOT affect a because it's a copy. 🔹 Pass by Reference (Objects) When you work with objects, arrays, functions or date objects, JavaScript passes a reference (memory address). let obj1 = { name: "Ali" }; let obj2 = obj1; obj2.name = "Ahmed"; console.log(obj1.name); // Ahmed console.log(obj2.name); // Ahmed 👉 Changing obj2 ALSO affects obj1 because both point to the same object. 🔥 Key Takeaway Primitives → 📦 Copy (Independent) Objects → 🔗 Reference (Shared) 💭 Pro Tip To avoid accidental changes in objects, use: Spread operator {...obj} Object.assign() Understanding this concept can save you from hidden bugs in real-world applications 🚀 #JavaScript #WebDevelopment #Frontend #Programming #CodingTips
To view or add a comment, sign in
-
🚀 JavaScript Scope Explained (Global, Function & Block Scope) One of the most important concepts every JavaScript developer must understand is **Scope**. Scope defines **where a variable can be accessed in your code**. Let’s break it down 👇 1️⃣ Global Scope Variables declared outside any function are accessible everywhere. ```javascript let name = "Abhishek"; function greet() { console.log(name); } ``` 2️⃣ Function Scope (var) Variables declared with `var` inside a function are only accessible within that function. ```javascript function test() { var message = "Hello"; } console.log(message); // Error ``` 3️⃣ Block Scope (let / const) `let` and `const` are block scoped, meaning they only exist inside `{ }`. ```javascript if(true){ let age = 25; } console.log(age); // Error ``` ⚠️ Common Mistake with `var` ```javascript if(true){ var age = 25; } console.log(age); // 25 (unexpected) ``` ✔ Best Practice Use **const by default** Use **let when value changes** Avoid **var** in modern JavaScript. 💬 Interview Question: What is the **Temporal Dead Zone (TDZ)** in JavaScript? #JavaScript #WebDevelopment #Frontend #Programming #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 90 of me reading random and basic but important dev topicsss...... Today I read about the File Object in JavaScript As web applications become more robust, handling file uploads, drag-and-drop interfaces, and binary data is an absolute must for modern frontend development. What is a File? At its core, a File object is just a specific type of Blob (Binary Large Object) that is extended with filesystem-related capabilities. Because it inherits from Blob, it has access to all the same properties, but adds two crucial pieces of OS-level data: * name: The file name string (e.g. "profile.png"). * lastModified: The timestamp of the last modification (integer date). How do we get a File object? There are two primary ways we encounter files in the browser: 1. User Input (The Common Way) Most of the time, the OS provides this data when a user interacts with an <input type="file"> or a drag-and-drop interface. function handleUpload(input) { // input.files is an array-like object, as users can select multiple files let file = input.files[0]; console.log(`Name: ${file.name} | Modified: ${file.lastModified}`); } 2. The Constructor (The Programmatic Way) You can manually construct a file using: new File(fileParts, fileName, [options]) * fileParts: An array of Blob, BufferSource, or String values. * fileName: The name of your new file. * options: An optional object where you can pass a custom lastModified timestamp. Pro-Tip: Sending files to the backend is incredibly seamless. Modern network APIs like fetch and XMLHttpRequest natively accept File objects in their payload! You don't always have to parse them first. Keep Learning!!!! #JavaScript #WebDevelopment #Frontend #SoftwareEngineering #CodingTips
To view or add a comment, sign in
-
-
📊 Day 14 – Poll Answer & Explanation console.log([1,2] + [3,4]); ❓ What will be the output? Many developers expect array concatenation, but JavaScript behaves differently ✅ Step-by-Step Explanation Step 1️⃣ JavaScript sees the `+` operator. The `+` operator can perform: Addition String concatenation Step 2️⃣ When arrays are used with `+`, JavaScript converts them to strings. [1,2].toString() // "1,2" [3,4].toString() // "3,4" Step 3️⃣ Now the operation becomes: "1,2" + "3,4" Step 4️⃣ This performs string concatenation. "1,23,4" ### 🎯 Final Output 1,23,4 📌 Key Concept The `+` operator with arrays converts them into strings first, then performs string concatenation. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #CodingInterview #DeveloperCommunity #100DaysOfCode #LearnToCode
To view or add a comment, sign in
-
⚠️ JavaScript Function Expression — A Common Corner Case That Trips Developers 🔍 The Corner Case: Hoisting Behavior console.log(add(2, 3)); // ❌ TypeError: add is not a function var add = function(a, b) { return a + b; }; 👉 Why does this fail? Because only the variable declaration (var add) is hoisted, not the function itself. So internally, JavaScript sees this as: var add; console.log(add(2, 3)); // ❌ add is undefined add = function(a, b) { return a + b; }; ✅ Now Compare with Function Declaration console.log(add(2, 3)); // ✅ 5 function add(a, b) { return a + b; } 👉 Entire function is hoisted — so it works! 💥 Another Tricky Case (Named Function Expression) const foo = function bar() { console.log(typeof bar); }; foo(); // ✅ function bar(); // ❌ ReferenceError: bar is not defined 👉 bar is only accessible inside the function, not outside! 🎯 Key Takeaways ✔ Function expressions are NOT fully hoisted ✔ Only variable declarations are hoisted (var, let, const behave differently) ✔ Named function expressions have limited scope ✔ Always define function expressions before using them #JavaScript #Frontend #CodingInterview #WebDevelopment #JSConcepts #100DaysOfCode
To view or add a comment, sign in
-
A tale of two JavaScript patterns and the bugs that catch you out 🐛 I've been revisiting the two main ways to create custom objects in JavaScript. Both achieve the same goal. Both have traps. Here's what I found: ES6 Class class Character { constructor(name) { this.name = name this.powers = [] } addPowers(power) { this.powers.push(power) console.log(`${this.name} has ${this.powers} Powers!`) } } Methods live outside the constructor, inside the class body. They land on the prototype automatically so every instance shares one copy rather than each carrying its own. Constructor Function function Character(name) { this.name = name this.powers = [] this.addPowers = function(power) { this.powers.push(power) console.log(`${this.name} has ${this.powers} Powers!`) } } Easy gotcha: write function addPowers() instead of this.addPowers = and the method becomes a private inner function completely invisible outside the constructor. Your code won't error on creation, it'll just silently fail when you try to call it. The class syntax is cleaner and harder to get wrong. But understanding constructor functions teaches you what's actually happening under the hood and makes legacy codebases far less scary. Worth noting: there is a third way Object.create() but I've not covered it here. It gives you very fine-grained control over the prototype chain, but it's significantly more verbose and rarely the first tool you'd reach for. Both patterns. Both worth knowing. Have you been caught out by either of these? Let me know below 👇 #JavaScript #WebDevelopment #CodingTips #OOP #LearnToCode #JSDevs #SoftwareEngineering
To view or add a comment, sign in
-
One small pattern I really like in JavaScript/TypeScript: return data.items .slice(offset, offset + limit) .map(({ id, firstName, lastName, companyId }) => ({ id, firstName, lastName, companyId, })); Why this is clean: • slice(offset, offset + limit) → handles pagination in a single, readable step • map(...) → transforms data immediately, returning only what’s needed • Object destructuring → avoids repetitive item.id, item.firstName, etc. • No mutations → everything is predictable and functional It’s concise, readable, and does exactly what it needs — nothing more. Sometimes clean code is just about using the right built-in methods. #JavaScript #TypeScript #CleanCode #javascript #remote
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