What do you think will be the output of these expressions in javascript? {} + [] [] + {} {} + {} [] + [] At first glance, most developers assume JavaScript will treat these as normal object or array operations. But the real reason behind the output is type coercion and how JavaScript converts objects and arrays into primitive values when using the + operator. When the + operator is used with objects or arrays, JavaScript tries to convert them into primitive values (usually strings). An empty array [] becomes an empty string "" An object {} becomes "[object Object]" After this conversion, the + operator performs string concatenation. So the expressions effectively become: "[object Object]" + "" "" + "[object Object]" "[object Object]" + "[object Object]" "" + "" Understanding this behavior is important because JavaScript’s implicit type coercion can sometimes lead to unexpected results in real-world applications. A simple rule to remember: {} → "[object Object]" [] → "" Once you remember this conversion, these puzzles become much easier to reason about. For more insightful content checkout below: 🟦 𝑳𝒊𝒏𝒌𝒆𝒅𝑰𝒏 - https://lnkd.in/dwi3tV83 ⬛ 𝑮𝒊𝒕𝑯𝒖𝒃 - https://lnkd.in/dkW958Tj 🟥 𝒀𝒐𝒖𝑻𝒖𝒃𝒆 - https://lnkd.in/dDig2j75 or Priya Frontend Vlogz 🔷 𝐓𝐰𝐢𝐭𝐭𝐞𝐫 - https://lnkd.in/dyfEuJNt #frontend #javascript #react #reactjs #html #css #typescript #es6 #interviewquestions #interview #interviewpreparation
JavaScript Type Coercion with Objects and Arrays
More Relevant Posts
-
I was recently asked a classic JavaScript "gotcha" in an interview: "How do you return an object in an arrow function, and why are parentheses required?" It sounds simple But the "Why" is where most developers get tripped up. The Problem: In JavaScript, {} is ambiguous. It can mean an Object Literal OR a Function Block. By default, the JS engine sees a brace after an arrow => and assumes it's a function block. The Result: const getUser = () => { name: 'Chandhan' }; The engine thinks name: is a label and returns undefined. The Fix: Wrap it in parentheses! ({ ... }) The () forces the engine to treat the contents as an expression, not a statement. ✅ const getUser = () => ({ name: 'Chandhan' }); Small syntax, big difference in how the engine parses your code. #JavaScript #WebDevelopment #CodingTips #Angular #Frontend #InterviewPrep
To view or add a comment, sign in
-
🚀 Higher-Order Functions in JavaScript — A Must-Know Concept! 💡 What is a Higher-Order Function? A function is called a Higher-Order Function if it: ✔️ Takes another function as an argument ✔️ Returns a function as its result 🔍 Simple Example: function greet(name) { return `Hello, ${name}`; } function processUserInput(callback) { const name = "Jake"; return callback(name); } console.log(processUserInput(greet)); 👉 Here, processUserInput is a Higher-Order Function because it accepts greet as a callback. ⚡ Why are Higher-Order Functions powerful? ✅ Code reusability ✅ Cleaner and more readable code ✅ Helps in functional programming ✅ Widely used in JavaScript methods like: array.map(), array.filter(), array.reduce() 🔥 Interview Twist: function multiplier(factor) { return function (number) { return number * factor; }; } const double = multiplier(2); console.log(double(5)); // ? 🧠 Output: 10 👉 Because multiplier returns another function — classic Higher-Order Function! 🔥 The Important Concept: Closure Even though multiplier execution is finished, the inner function still remembers factor. This is called a closure: "A function remembers variables from its outer scope even after that outer function has finished executing." #JavaScript #WebDevelopment #Frontend #CodingInterview #Developers
To view or add a comment, sign in
-
🤯 One of the most confusing concepts in JavaScript — 'this' keyword If you've worked with JavaScript, you’ve probably asked: 👉 “What exactly does ‘this’ refer to?” Here’s the simple rule: 👉 “this = Who called me?” Let’s understand with examples 👇 📌 1. Object Method const user = { name: "Vinay", greet() { console.log(this.name); } }; user.greet(); // Vinay 👉 Here, 'this' refers to the user object 📌 2. Normal Function function show() { console.log(this); } show(); // window (in browser) 👉 Here, 'this' refers to the global object 📌 3. Arrow Function const obj = { name: "Vinay", greet: () => { console.log(this.name); } }; obj.greet(); // undefined 👉 Arrow functions don’t have their own 'this' 👉 They inherit it from the parent scope 📌 4. Event Listener button.addEventListener("click", function () { console.log(this); }); 👉 Here, 'this' refers to the clicked element 💥 Final Tip: 👉 “'this' is not about where it’s written, it’s about how it’s called.” Master this concept, and your JavaScript skills will level up 🚀 #JavaScript #WebDevelopment #Coding #DeveloperLife #Frontend #Programming #JSConcepts
To view or add a comment, sign in
-
-
🔍 JavaScript Quirk: this behaves differently than you think This is one of the most confusing parts of JavaScript 👇 const user = { name: "Avinash", greet: function () { console.log(this.name); } }; user.greet(); // ? ✅ Output: "Avinash" Here, this refers to the object calling the function. Now look at this 👇 const greet = user.greet; greet(); // ? 💥 Output: undefined Why? Because this is no longer bound to user. In this case, this refers to the global object (or undefined in strict mode). Now the tricky part 👇 const user = { name: "Avinash", greet: () => { console.log(this.name); } }; user.greet(); // ? 💥 Output: undefined Why? Arrow functions don’t have their own this. They inherit it from their surrounding scope. 🚨 NEVER use this inside arrow functions for object methods. 💡 Takeaway: ✔ this depends on HOW a function is called ✔ Regular functions → dynamic this ✔ Arrow functions → lexical this ✔ Arrow + this in methods = bug waiting to happen 👉 Master this = fewer hidden bugs 🔁 Save this for later 💬 Comment "this" if it clicked ❤️ Like if this helped #javascript #frontend #webdevelopment #codingtips #js #developer
To view or add a comment, sign in
-
One of the most critical concepts in JavaScript — and a topic that every serious developer must understand to master async behavior. Many developers know how to use setTimeout, Promises, or fetch, but far fewer understand how JavaScript actually executes asynchronous code under the hood. In this post, I’ve broken down the complete JavaScript Asynchronous Execution Model, including the role of the Call Stack, Web APIs, Event Loop, and task queues. Covered in this slide set: 1. Why JavaScript is single-threaded and what that actually means 2. How the Call Stack executes synchronous code line by line 3. How asynchronous tasks are offloaded to Browser Web APIs 4. How completed async tasks move into Callback Queue (Macrotask Queue) 5. How Microtask Queue (Promises) has higher priority than normal callbacks 6. How the Event Loop coordinates everything to keep JavaScript non-blocking Clear explanation of: 1. Why setTimeout(..., 0) still runs after synchronous code 2. Why Promises execute before setTimeout 3. How fetch() integrates with the microtask queue 4. Why infinite microtasks can cause Callback Starvation 5. How the Event Loop constantly monitors the Call Stack Also explains an important rule of async JavaScript: 👉 Execution order is always Call Stack → Microtask Queue → Callback Queue Understanding this model makes it much easier to reason about: 1. Closures 2. Callbacks 3. Promises & async/await 4. React state updates 5. Node.js event-driven architecture These notes focus on execution clarity, interview readiness, and real-world understanding of the JavaScript runtime — not just memorizing behavior. Part of my JavaScript Deep Dive series, where I break down core JS concepts from the engine and runtime perspective. #JavaScript #AsyncJavaScript #EventLoop #WebAPIs #CallStack #MicrotaskQueue #CallbackQueue #Promises #JavaScriptRuntime #FrontendDevelopment #BackendDevelopment #WebDevelopment #MERNStack #NextJS #NestJS #SoftwareEngineering #JavaScriptInterview #DeveloperCommunity #LearnJavaScript #alihassandevnext
To view or add a comment, sign in
-
You say you’re “comfortable with JavaScript”? Cool. Let’s test that. Answer these in the comments 👇 🧠 1. What will this output? Why? 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨([] + []); 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨([] + {}); 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨({} + []); Most developers get at least one wrong. ⚡ 2. Predict the output: 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘰𝘶𝘵𝘦𝘳() { 𝘭𝘦𝘵 𝘤𝘰𝘶𝘯𝘵 = 0; 𝘳𝘦𝘵𝘶𝘳𝘯 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘪𝘯𝘯𝘦𝘳() { 𝘤𝘰𝘶𝘯𝘵++; 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨(𝘤𝘰𝘶𝘯𝘵); }; } 𝘤𝘰𝘯𝘴𝘵 𝘧𝘯 = 𝘰𝘶𝘵𝘦𝘳(); 𝘧𝘯(); 𝘧𝘯(); 𝘧𝘯(); What concept is this testing? 🔥 3. What’s the difference between these two? 𝘖𝘣𝘫𝘦𝘤𝘵.𝘧𝘳𝘦𝘦𝘻𝘦(𝘰𝘣𝘫); 𝘖𝘣𝘫𝘦𝘤𝘵.𝘴𝘦𝘢𝘭(𝘰𝘣𝘫); When would you use one over the other in production? 🧩 4. True or False? 𝘵𝘺𝘱𝘦𝘰𝘧 𝘯𝘶𝘭𝘭 === "𝘰𝘣𝘫𝘦𝘤𝘵" 𝘐𝘧 𝘵𝘳𝘶𝘦 — 𝘦𝘹𝘱𝘭𝘢𝘪𝘯 𝘸𝘩𝘺. 𝘐𝘧 𝘧𝘢𝘭𝘴𝘦 — 𝘦𝘹𝘱𝘭𝘢𝘪𝘯 𝘸𝘩𝘺. 🚀 5. Async trap — what happens here? 𝘢𝘴𝘺𝘯𝘤 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘵𝘦𝘴𝘵() { 𝘳𝘦𝘵𝘶𝘳𝘯 42; } 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨(𝘵𝘦𝘴𝘵()); What exactly gets logged? If you can answer all 5 confidently, you’re not just “using” JavaScript. You understand it. Drop your answers below 👇 Let’s see who’s interview-ready. #javascript #frontenddeveloper #codinginterview #webdevelopment #softwareengineering #DAY73
To view or add a comment, sign in
-
One of the first things that trips up JavaScript developers — at every level — is the `this` keyword. It doesn't work like most other languages. In JavaScript, `this` is not about where a function is written. It's about how it is called. Once you understand the 4 binding rules, it becomes very predictable. 01 — Default binding When called alone, `this` is the global object (or `undefined` in strict mode) 02 — Implicit binding When called on an object, `this` is that object 03 — Explicit binding `.call()`, `.apply()`, and `.bind()` let you set `this` manually 04 — Arrow functions They don't have their own `this`. They inherit it from the surrounding scope // Rule 2 — implicit const user = { name: "Aman", greet() { console.log(this.name); } }; user.greet(); // "Aman" — this = user // Rule 3 — explicit greet.call({ name: "Aman" }); // "Aman" — this = the object you passed // Rule 4 — arrow function inside a method const timer = { start() { setTimeout(() => console.log(this), 1000); // this = timer ✓ } }; The most practical takeaway from Rule 4: 🔵 Regular function → `this` is set by the caller 🟢 Arrow function → `this` is set by the enclosing scope This is why arrow functions are so useful inside callbacks and event handlers — they hold onto the `this` you actually want, without any extra work. Which rule do you find most developers struggle with? I'd love to hear your experience in the comments. 👇 #JavaScript #WebDevelopment #SoftwareEngineering #Programming #100DaysOfCode
To view or add a comment, sign in
-
🚀 Understanding JSX in React — Syntax & Rules Simplified! If you're working with React, JSX is everywhere. But JSX is not HTML—it’s JavaScript with a syntax extension. 💡 What is JSX? JSX (JavaScript XML) lets you write UI like this: const element = <h1>Hello, World!</h1>; 👉 Behind the scenes, React converts this into: React.createElement("h1", null, "Hello, World!"); ⚙️ How JSX works 👉 JSX is compiled into JavaScript 👉 It describes what the UI should look like 👉 React uses it to create Virtual DOM 🧠 Key Rules of JSX (Very Important!) 🔹 1. Return a single parent element // ❌ Wrong return ( <h1>Hello</h1> <p>World</p> ); // ✅ Correct return ( <> <h1>Hello</h1> <p>World</p> </> ); 🔹 2. Use className instead of class <div className="container"></div> 🔹 3. JavaScript inside {} const name = "React"; <h1>Hello {name}</h1> 🔹 4. Self-closing tags <img src="image.png" /> 🔹 5. Inline styles as objects <div style={{ color: "red" }}></div> 🧩 Real-world use cases ✔ Building UI components ✔ Rendering dynamic data ✔ Conditional UI rendering ✔ Mapping lists 🔥 Best Practices (Most developers miss this!) ✅ Keep JSX clean and readable ✅ Extract complex logic outside JSX ✅ Use fragments instead of unnecessary divs ❌ Avoid writing heavy logic inside JSX ⚠️ Common Mistake // ❌ Too much logic inside JSX return <h1>{user.isLoggedIn ? "Welcome" : "Login"}</h1>; 👉 Fine for small cases, but extract logic for complex UI 💬 Pro Insight JSX is not about writing HTML in JS— 👉 It’s about describing UI in a declarative way 📌 Save this post & follow for more deep frontend insights! 📅 Day 6/100 #ReactJS #FrontendDevelopment #JavaScript #JSX #WebDevelopment #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
🚀 JavaScript Event Loop — Explained Simply (with Example) If you’re preparing for frontend interviews or working with async JS, understanding the Event Loop is a must! 💯 🧠 What is Event Loop? 👉 JavaScript is single-threaded, but still handles async tasks like a pro 👉 Event Loop ensures non-blocking execution by managing execution order ⚙️ Key Concepts: 📌 Call Stack → Executes synchronous code 📌 Web APIs → Handles async tasks (setTimeout, fetch, DOM events) 📌 Microtask Queue → Promises (high priority ⚡) 📌 Callback Queue → setTimeout, setInterval 🔥 Example: JavaScript console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); 🎯 Output: Start End Promise Timeout 🧩 Why this output? 👉 JS executes sync code first 👉 Then Event Loop checks: ✔ Microtasks (Promises) → First ✔ Macrotasks (setTimeout) → After 💡 Golden Rule: 👉 Promise > setTimeout (Priority matters!) 🚀 Real-world usage: ✔ API calls (fetch/axios) ✔ UI updates without blocking ✔ Handling async flows in React apps 🎯 Interview One-liner: 👉 “Event Loop manages async execution by prioritizing microtasks over macrotasks after the call stack is empty.” If this helped you, drop a 👍 or comment below! Let’s keep learning and growing 🚀 #JavaScript #EventLoop #FrontendDevelopment #ReactJS #WebDevelopment #CodingInterview #AsyncJS #Developers
To view or add a comment, sign in
-
🚀 Callback Functions in JavaScript — Simple but Tricky! A callback function is a function passed as an argument to another function and executed later. 💡 Basic Example: function greet(name, callback) { console.log("Hi " + name); callback(); } function sayBye() { console.log("Goodbye!"); } greet("User", sayBye); 🧠 Output: Hi User Goodbye! 🔥 Question #1 (Hoisting Surprise): function test(callback) { callback(); } test(function () { console.log(a); var a = 10; }); 🧠 Output: undefined 📌 Reason: var a is hoisted but initialized as undefined. 🔥 Question #2 (Scope Trap): function outer(cb) { let x = 5; cb(); } outer(function () { console.log(x); }); 🧠 Output: ReferenceError: x is not defined 📌 Reason: Callback doesn’t have access to outer scope unless passed. 🔥 Question #3 (Async Behavior): console.log("Start"); setTimeout(function () { console.log("Callback"); }, 0); console.log("End"); 🧠 Output: Start End Callback 📌 Reason: Event loop pushes callback to queue (async behavior). 🔥 Quick Check Question #4: function execute(cb) { return cb(); } function sayHi() { return "Hi!"; } console.log(execute(sayHi)); 🧠 Output: Hi! ⚡ Key Takeaways: ✔ Callbacks are fundamental to async JS ✔ Execution context matters more than syntax #JavaScript #Frontend #WebDevelopment #InterviewPrep #Callbacks
To view or add a comment, sign in
More from this author
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