Ever wondered why you can’t just .map() over an object even when it looks exactly like an array? 🧐 If you’ve tried it, you’ve seen the error: TypeError: obj.map is not a function. But there is a "secret" way to force JavaScript to treat an object like an array using .call(). Here is how you can master this common interview trick. The Problem: Objects aren't Iterables The map() method lives on Array.prototype. This means only true Arrays have access to it. Even if your object has numbers as keys, JavaScript still sees it as a plain object, not a sequence. The Solution: Array-Like Objects To "trick" the map method into working, your object must be Array-like. This requires two things: Numeric keys (to act as indexes). A length property (to tell JS where to stop). The "Magic" Syntax We use .call() to borrow the map function from the Array prototype and manually point its this context to our object. JavaScript const personData = { 0: "John", 1: "Doe", 2: "Developer", length: 3 }; // Borrowing map from Array prototype const upperCaseData = Array.prototype.map.call(personData, (item) => { return item.toUpperCase(); }); console.log(upperCaseData); // Output: ["JOHN", "DOE", "DEVELOPER"] Why the 'length' property is king When you use Array.prototype.map.call(), JavaScript starts at index 0 and loops until it hits length - 1. If your object has 10 keys but length: 2, map will only process the first two items. If you forget the length property entirely, the result will be an empty array. 💡 Interview Takeaways Method Borrowing: This technique is a prime example of "Method Borrowing" in JS. The Array-like Contract: For this to work, the object must have a length property and indexed elements. Modern Alternative: In modern development, we usually use Array.from(obj).map(...), but understanding .call() shows a deeper grasp of the language's internals. #javascript #frontend #webdev #codingtips I’m currently diving deep into JavaScript internals to sharpen my frontend skills. Would you like
Mastering JavaScript: Forcing Objects to Behave Like Arrays with .call()
More Relevant Posts
-
📚 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
-
-
JavaScript Hoisting: The Concept That Separates “I use JS” from “I understand JS” Hoisting is one of those JavaScript behaviors that silently explains why some code works, and why some bugs are so hard to catch. In JavaScript, code runs in two phases: 1️⃣ Compilation (creation) phase 2️⃣ Execution phase During compilation, JavaScript sets up memory for variables and functions. This is where hoisting happens. 🔹 var hoisting Only the declaration is hoisted, not the initialization. ex: console.log(x); // undefined var x = 5; Behind the scenes, JavaScript treats it like: var x; console.log(x); x = 5; No error, but also no value yet. This behavior has caused countless subtle bugs in real-world apps. 🔹 Function declarations Function declarations are fully hoisted, name and body. sayHello(); // works function sayHello() { console.log("Hello"); } This is why function declarations behave differently from function expressions. 🔹 let & const (ES6) They are hoisted, but not initialized. Accessing them before declaration throws a ReferenceError. console.log(y); // ReferenceError let y = 10; This period is known as the Temporal Dead Zone (TDZ), a design choice to make code safer and more predictable. 💡 Why this matters in real projects - Explains unexpected undefined - Helps debug scope-related issues - Shows you understand how JS actually works under the hood 📌 Best practice Don’t rely on hoisting. Write code that’s clear, intentional, and predictable, your future self (and your team) will thank you. #JavaScript #Frontend #WebDevelopment #SoftwareEngineering #CleanCode
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 is single-threaded. So how does it handle multiple tasks at once? Meet the Event Loop. It's the unsung hero that keeps your browser from freezing while waiting for an API call. Many developers use setTimeout or fetch daily without knowing what happens under the hood. Here is the architecture that makes non-blocking I/O possible: 1️⃣ Call Stack (The Boss): JavaScript does one thing at a time. It executes functions LIFO (Last In, First Out). If the stack is busy, nothing else happens. 2️⃣ Web APIs (The Assistants): When you call setTimeout or fetch, the browser takes that task out of the Call Stack and handles it in the background (Web APIs). This frees up the stack to keep running your code! 3️⃣ Callback Queue (The Waiting Room): Once the background task is done (e.g., the timer finishes), the callback function is moved to the Queue. It waits there patiently. 4️⃣ The Event Loop (The Traffic Controller): This is the infinite loop. It constantly checks: - "Is the Call Stack empty?" - "Is there something in the Queue?" - If Stack is Empty AND Queue has items 👉 Move item to Stack. Understanding this flow is the key to debugging weird async behavior. Did you know setTimeout(fn, 0) is a hack to defer execution until the stack is clear? #JavaScript #WebDevelopment #EventLoop #CodingInterview #Frontend #SoftwareEngineering
To view or add a comment, sign in
-
-
Stop repeating props everywhere. Here is why. 👇 In modern React development, readability is just as important as functionality. One common sign of "junior" code is cluttering components with repetitive data access and manual object copying. If you want to write cleaner, more maintainable components, you need to master Destructuring and the Spread Operator. 1. Object Destructuring (For Cleaner Props) Instead of repeating props. every time you need a value, unpack the properties directly in the function signature. This makes it immediately clear what data your component requires. ❌ Bad (Noisy): JavaScript const UserCard = (props) => { return ( <div className="card"> <h2>{props.name}</h2> <p>{props.role}</p> </div> ); }; ✅ Good (The React Way): JavaScript const UserCard = ({ name, role }) => { return ( <div className="card"> <h2>{name}</h2> <p>{role}</p> </div> ); }; 2. The Spread Operator ... (For Updating State) In React, we often need to update one property of an object while keeping the rest the same. The Spread Operator allows you to copy the existing state effortlessly before applying updates. ✅ Clean Update Logic: JavaScript const updateEmail = (newEmail) => { setUser(prev => ({ ...prev, email: newEmail })); }; 💡 Pro Tip: You can also use the Spread Operator to pass a whole object as props! Instead of <Card name={user.name} role={user.role} />, you can simply write <Card {...user} />. Writing smart code > Writing more code. Do you destructure inside the function arguments or inside the component body? Let me know. ⬇️ #ReactJS #JavaScript #CleanCode #FrontendDevelopment #WebDevelopment #CodingTips
To view or add a comment, sign in
-
Many developers get confused between Spread and Rest operators because they use the same syntax (...). 👉 The real difference depends on how and where you use it. 🔹 Spread Operator (...) Purpose: Expands values ✅ Common use cases: ✔ Copy arrays ✔ Merge arrays ✔ Copy objects ✔ Pass props in React Js const arr1 = [1, 2, 3]; const arr2 = [...arr1, 4, 5]; console.log(arr2); // [1, 2, 3, 4, 5] const user = { name: "Ashwani", role: "UI Developer" }; const updatedUser = { ...user, experience: "10+ years" }; 🔹 Rest Operator (...) Purpose: Collects multiple values into a single array ✅ Common use cases: ✔ Function parameters ✔ Destructuring ✔ Handling dynamic arguments Js function sum(...numbers) { return numbers.reduce((a, b) => a + b, 0); } sum(2, 3, 4); // 9 Js const [first, ...rest] = [10, 20, 30, 40]; console.log(rest); // [20, 30, 40] 🔁 Key Difference Spread Rest Expands values Collects values Used while calling Used in definition Useful for copy/merge Useful for flexibility 💡 Interview Tip 👉 Spread = expand values 👉 Rest = gather values #JavaScript #ES6 #FrontendDevelopment #ReactJS #UIDeveloper #WebDevelopment #InterviewPreparation
To view or add a comment, sign in
-
JavaScript has many types of functions, and each exists for a specific purpose. Here’s a clear breakdown 👇 1️⃣ Function Declaration function greet() { console.log("Hello"); } ✅ Hoisted (can be called before definition) ✅ Best for reusable, main logic ❌ Not ideal inside blocks 2️⃣ Function Expression const greet = function () { console.log("Hello"); }; ❌ Not hoisted ✅ Stored in variables ✅ Useful when passing functions as values 3️⃣ Arrow Function const greet = () => { console.log("Hello"); }; ✅ Shorter syntax ❌ No own this ❌ No arguments object ✅ Perfect for callbacks & React components 4️⃣ Anonymous Function setTimeout(function () { console.log("Hello"); }, 1000); ❌ No name ✅ Used once ✅ Common in callbacks & event handlers 5️⃣ Named Function Expression const greet = function sayHello() { console.log("Hello"); }; ✅ Helpful for debugging ❌ Name not accessible outside function 6️⃣ IIFE (Immediately Invoked Function Expression) (function () { console.log("Runs immediately"); })(); ✅ Executes instantly ✅ Creates private scope ❌ Less used now (modules replaced it) 7️⃣ Callback Function function fetchData(callback) { callback(); } ✅ Function passed as argument ✅ Core of async programming ❌ Can lead to callback hell 8️⃣ Higher-Order Function const numbers = [1, 2, 3]; numbers.map(n => n * 2); ✅ Takes or returns a function ✅ Enables functional programming ✅ Common: map, filter, reduce 9️⃣ Async Function async function fetchData() { const data = await fetch(url); } ✅ Cleaner async code ✅ Built on promises ✅ Easy error handling with try/catch 🔟 Generator Function function* generator() { yield 1; yield 2; } ✅ Pauses execution ✅ Uses yield ❌ Rare, but powerful for advanced flows #functions #javascript #js #reactjs #frontenddeveloper #frontend #linkedin
To view or add a comment, sign in
-
-
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
-
🚀 Why do we use [] at the end of useEffect in React? Let me break this down simply. 🤔 What does [] actually mean? React asks: "When should I run this effect again?" Your answer goes inside []. The 3 Rules: 1️⃣ Empty [] → Run ONCE javascript useEffect(() => { fetchData(); }, []); ✅ Runs only on component mount Use for: API calls, one-time setup 2️⃣ With value [name] → Run when IT changes javascript useEffect(() => { console.log(name); }, [name]); ✅ Runs when name updates Use for: Responding to specific changes 3️⃣ No array → Run EVERY render javascript useEffect(() => { console.log("Rendered!"); }); ⚠️ Runs constantly — avoid this! 🏠 Simple Analogy [] = Installing Wi-Fi once when you move in [electricity] = Checking meter when usage changes No array = Breathing constantly 💡 Common Mistake ❌ Infinite loop: javascript useEffect(() => { setCount(count + 1); }); // Runs forever! ✅ Fixed: javascript useEffect(() => { setCount(count + 1); }, []); // Runs once 📌 Quick Reference useEffect(..., []) → Once useEffect(..., [x]) → When x changes useEffect(...) → Every render 🎯 Bottom Line The [] tells React when to re-run your code: Empty = once With values = when those change Missing = constantly (usually a bug) Master this and avoid infinite loops, performance issues, and bugs! 💪 Drop a 💡 if this helped! #React #JavaScript #WebDevelopment #Programming
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
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