🌙 Evening Post — Why This if Block Always Runs This morning’s code was: let a = []; if (a) { console.log("Yes"); } else { console.log("No"); } 💡 Correct Output Yes This surprises many people 😄 Let’s understand why step by step. 🧠 Simple Explanation : 🔹 Key Rule in JavaScript 👉 In JavaScript, all objects are truthy. And: [] // is an object Even though the array is empty, it still exists in memory. So JavaScript treats it as: true 🔹 What happens in the if condition? if (a) Here: a is [] [] is truthy So the if block runs 👇 console.log("Yes"); That’s why the output is: Yes ❗ Common Mistake Beginners Make Many people think: Empty array [] → falsy ❌ Empty object {} → falsy ❌ But actually: [] → truthy ✅ {} → truthy ✅ Only these are falsy in JS: false 0 "" (empty string) null undefined NaN 🎯 Key Takeaways : Empty arrays are truthy Empty objects are truthy Truthy/falsy is about type, not size This question appears often in interviews 📌 If you want to check if an array is empty, do this instead: a.length === 0 💬 Your Turn Did you expect "Yes" or "No"? 😄 Comment “Got confused 😅” or “Clear now ✅” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #Basics #TechWithVeera #WebDevelopment
JavaScript Truthy Arrays in If Statements Explained
More Relevant Posts
-
The Journey of an Embedded Object in JavaScript (Recursion in Action) Today I explored a simple but powerful concept in JavaScript: traversing nested objects using recursion. When working with deeply embedded objects (like API responses or application state), it’s important to understand how to navigate through multiple levels dynamically. 💡 What’s happening? We loop through each key in the object. If the value is another object → we call the function again (recursion). If it’s a primitive value → we print it. This is a Depth-First Search (DFS) approach applied to objects. This concept is extremely useful for: Parsing JSON responses Building form validators State inspection (NgRx / Redux) Creating flatten utilities Deep comparison algorithms 📂 I’ve added more JavaScript pattern exercises in this repository: 👉 https://lnkd.in/ej4fNeZs I’m currently strengthening my fundamentals in JavaScript, recursion, and problem-solving patterns. If you're also sharpening your JS skills, let’s connect and grow together 💪 #JavaScript #Recursion #WebDevelopment #Frontend #ProblemSolving #LearningInPublic
To view or add a comment, sign in
-
-
𝗪𝗲𝗹𝗰𝗼𝗺𝗲 𝘁𝗼 𝗗𝗮𝘆 𝟵 Have you ever updated one variable… and another one changed automatically? 𝙋𝙖𝙪𝙨𝙚 𝙛𝙤𝙧 𝙖 𝙨𝙚𝙘𝙤𝙣𝙙 — 𝙬𝙤𝙪𝙡𝙙 𝙮𝙤𝙪 𝙚𝙭𝙥𝙚𝙘𝙩 𝙩𝙝𝙞𝙨 𝙘𝙤𝙙𝙚 𝙩𝙤 𝙢𝙪𝙩𝙖𝙩𝙚 𝙗𝙤𝙩𝙝 𝙫𝙖𝙡𝙪𝙚𝙨? { 𝚕𝚎𝚝 𝚞𝚜𝚎𝚛𝟷 = { 𝚗𝚊𝚖𝚎: "𝙰𝚕𝚎𝚡" }; 𝚕𝚎𝚝 𝚞𝚜𝚎𝚛𝟸 = 𝚞𝚜𝚎𝚛𝟷; 𝚞𝚜𝚎𝚛𝟸.𝚗𝚊𝚖𝚎 = "𝙹𝚘𝚑𝚗"; 𝚌𝚘𝚗𝚜𝚘𝚕𝚎.𝚕𝚘𝚐(𝚞𝚜𝚎𝚛𝟷.𝚗𝚊𝚖𝚎); // "𝙹𝚘𝚑𝚗" } Why did user1 change? Because: • Both variables point to the same memory address • No copy was created • Only the reference was shared 𝘛𝘩𝘪𝘴 𝘪𝘴 𝘑𝘢𝘷𝘢𝘚𝘤𝘳𝘪𝘱𝘵’𝘴 𝘝𝘢𝘭𝘶𝘦 𝘷𝘴 𝘙𝘦𝘧𝘦𝘳𝘦𝘯𝘤𝘦 𝘣𝘦𝘩𝘢𝘷𝘪𝘰𝘳 — 𝘢𝘯𝘥 𝘪𝘵’𝘴 𝘥𝘦𝘦𝘱𝘭𝘺 𝘵𝘪𝘦𝘥 𝘵𝘰 𝘮𝘦𝘮𝘰𝘳𝘺. 𝙏𝙝𝙚 𝙈𝙚𝙣𝙩𝙖𝙡 𝙈𝙤𝙙𝙚𝙡 (𝙈𝙚𝙢𝙤𝙧𝙮 𝙁𝙞𝙧𝙨𝙩) JavaScript mainly uses two memory areas: -> Stack Memory • Stores primitive values • Fixed size • Fast access -> Heap Memory • Stores objects, arrays, functions • Dynamic size • Accessed via references 𝙒𝙝𝙚𝙣 𝙥𝙖𝙨𝙨𝙚𝙙 𝙗𝙮 𝙫𝙖𝙡𝙪𝙚: A copy of the actual value is passed. Primitives (number, string, boolean, null, undefined, symbol) are always passed by value. 𝙒𝙝𝙚𝙣 𝙥𝙖𝙨𝙨𝙚𝙙 𝙗𝙮 𝙧𝙚𝙛𝙚𝙧𝙚𝙣𝙘𝙚: A memory address (reference) is passed, not the object itself. Objects & arrays live in heap memory. #JavaScript #JSFundamentals #MemoryManagement #FrontendDevelopment #ReactJS #BugFixing #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
𝗛𝗮𝘃𝗲 𝘆𝗼𝘂 𝗲𝘃𝗲𝗿 𝗵𝗲𝗮𝗿𝗱 𝘁𝗵𝗲 𝘄𝗼𝗿𝗱 "𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲" 𝗮𝗻𝗱 𝘄𝗼𝗻𝗱𝗲𝗿𝗲𝗱 𝗶𝗳 𝗶𝘁 𝘄𝗮𝘀 𝗷𝘂𝘀𝘁 𝗳𝗮𝗻𝗰𝘆 𝗱𝗲𝘃-𝘀𝗽𝗲𝗮𝗸? 🧐 I used to wonder: How does a simple list or a piece of text suddenly have "powers" like .map() or .length()? I didn't write those functions, so where do they come from? The secret lies in the JavaScript Prototype Chain. 𝗧𝗵𝗲 "𝗛𝗶𝗱𝗱𝗲𝗻 𝗟𝗶𝗻𝗸" 🔗 In JavaScript, almost everything—Arrays, Strings, Functions—is actually an Object under the hood. When you create something, JS gives it a "secret parent" called a 𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲. Think of it like this: • You don't need to teach every baby how to breathe; they inherit that "function" from their DNA. • In JS, your Array doesn't "know" how to sort itself. It just asks its parent: "Hey, do you have the instructions for this?" 𝗪𝗵𝘆 "𝗘𝘃𝗲𝗿𝘆𝘁𝗵𝗶𝗻𝗴 𝗶𝘀 𝗮𝗻 𝗢𝗯𝗷𝗲𝗰𝘁"? Because if you keep following that secret link (__proto__) up the family tree, almost every path leads back to the Grandparent Object. This is Prototypal Inheritance. Instead of wasting memory by giving every variable its own set of tools, they all just share one master toolbox. Understanding this "behind the scenes" magic changed how I look at my code. It’s not just typing commands; it’s navigating a beautifully connected web of logic. Each day when I learn a topic of JS and find how it works behind the scenes, every day i fall in love with it more and more. ❤️ #JavaScript #Coding #WebDev #TechLearning #ProgrammingConcepts
To view or add a comment, sign in
-
🔄 Understanding the sort() Method in JavaScript Sorting is one of the most common operations in programming — whether you're organizing user data, ranking products, or displaying results. JavaScript provides a built-in sort() method that makes this task simple and efficient. 💡 What is sort()? The sort() method is used to arrange elements of an array in place, meaning it modifies the original array. ⚠️ Key Things Every Developer Should Know ✅ sort() mutates the original array ✅ Default sorting treats elements as strings ✅ Always use a compare function for numbers ✅ Efficient for quick data organization 🎯 When Should You Use sort()? 🔹 Displaying ranked data 🔹 Ordering prices or scores 🔹 Alphabetizing lists 🔹 Preparing structured UI data The real power of sort() lies in the compare function — once you master it, you can sort almost anything in JavaScript. #JavaScript #WebDevelopment #Frontend #CodingTips #LearnJavaScript #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 Process vs Thread – Simple Explanation (With JavaScript Twist) Many developers confuse Process and Thread. Let’s understand this in the simplest way. 🧠 What is a Process? A Process is an independent running program. Example: VS Code is a process. Chrome is another process. If Chrome crashes, VS Code does not stop. Why? Because both have separate memory space. ⚙️ What is a Thread? A Thread is a worker inside a process. One process can have multiple threads. All threads share the same memory. Think of it like: Process = Company Threads = Employees inside the company 🔥 JavaScript – Single Threaded? Yes. JavaScript is single-threaded. But that does NOT mean it handles only one request at a time. It means: ➡️ It executes one instruction at a time in the call stack. JavaScript uses: Event Loop Callback Queue Web APIs This makes it non-blocking and asynchronous. So JS supports concurrency, even though it runs on a single thread. 🦀 What about Rust / C++? Languages like Rust and C++ support true multi-threading. That means: Multiple threads Real parallel execution Better CPU core utilization 💡 Final Understanding Process = Independent program Thread = Worker inside process JavaScript = Single-threaded but async Rust/C++ = Multi-threaded with real parallelism Understanding this clears a lot of backend and system design confusion. #SystemDesign #JavaScript #Multithreading #BackendDevelopment #Rust #WebDevelopment
To view or add a comment, sign in
-
🧠 99% of JavaScript devs fall into this trap 👀 (Even with years of experience) No frameworks. No libraries. Just core JavaScript fundamentals. 🧩 Output-Based Question (parseInt + map) console.log(["1", "2", "3"].map(parseInt)); ❓ What will be printed? ❌ Don’t run the code 🧠 Think like the JavaScript engine A. [1, 2, 3] B. [1, NaN, NaN] C. [1, 2, NaN] D. Throws an error 👇 Drop ONE option in the comments Why this matters Most developers assume: parseInt only takes one argument map passes only the value Both assumptions are wrong. When fundamentals aren’t clear: bugs slip into production data parsing breaks silently debugging turns into guesswork Strong JavaScript developers don’t guess. They understand how functions are actually called. 💡 I’ll pin the full explanation after a few answers. #JavaScript #JSFundamentals #CodingInterview #WebDevelopment #FrontendDeveloper #FullStackDeveloper #DevelopersOfLinkedIn #DevCommunity #JavaScriptTricks #VibeCode
To view or add a comment, sign in
-
-
Day 67 of me reading random and basic but important dev topicsss..... Today I read about the Advanced JavaScript Range Properties & Methods..... Yesterday, I looked at the fundamentals of creating a Range in the DOM. Today, I explored the properties and convenience methods that make traversing and building these ranges highly efficient. When integrating raw DOM logic into frameworks like React, knowing these native shortcuts saves us from writing manual, bug-prone offset calculations. Core Range Properties: When we inspect a Range object, it gives us crucial contextual data: * startContainer / startOffset: The exact node and position where the range begins. * endContainer / endOffset: The node and position where the range ends. * collapsed: A boolean. true if the start and end are at the exact same point (think of a blinking text cursor with no characters highlighted). * commonAncestorContainer: The deepest parent element that fully wraps the entire range. (Incredibly useful for validating if a user's selection is contained within a specific UI component!). Pro Methods (Skip the math!): Instead of calculating exact indexes with setStart and setEnd, you can leverage semantic methods: * setStartBefore(node) / setStartAfter(node): Drops the boundary right outside a target node. * selectNode(node): Creates a range that encompasses the entire node, including its outer HTML tags. * selectNodeContents(node): Selects only the inside of the node......perfect for instantly capturing all the text inside a <div> or <p>. * collapse(toStart): Instantly shrinks the range to just its starting or ending cursor point. Keep Learning!!!!!! #JavaScript #WebDevelopment #DOM #FrontendDev
To view or add a comment, sign in
-
-
🧠✨ JavaScript Cheat Sheet: Because My Brain Has a Tiny Cache Ever open a JS file and suddenly forget whether it’s let, const, or “panic”? Same. So I saved this JavaScript CheatSheet as a quick “copy / paste / keep moving” reference. What’s inside (high-level): Basics: variables, data types, type conversion Control structures: if/else, switch, loops Operators & functions: arrow functions, default params, rest params Arrays & objects: common methods + quick patterns ES6+ goodies: destructuring, spread/rest, optional chaining, nullish coalescing DOM basics: selecting, creating, and wiring events Async JS: callbacks, promises, async/await Advanced topics: closures, this, prototypes/classes + useful methods If you want the PDF version, comment “JS” and I’ll send it. 🙂 #JavaScript #JS #WebDevelopment #Frontend #SoftwareEngineering #Programming #Coding #ES6 #AsyncAwait #DOM #Developers #LearningToCode #CheatSheet #DevTips #100DaysOfCode
To view or add a comment, sign in
-
✨ 𝗗𝗮𝘆 𝟳 𝗼𝗳 𝗠𝘆 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗝𝗼𝘂𝗿𝗻𝗲𝘆 🚀 Today I took a deep dive into 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗔𝗿𝗿𝗮𝘆𝘀, and it was fascinating to uncover how they really work under the hood. At first glance, arrays seem like a standard data structure, but in JavaScript, they are actually special types of objects. This means: • They have numbered indices like arrays, but they’re technically keys on an object • They come with powerful built-in methods like push(), pop(), map(), filter(), reduce() • Their “length” property updates dynamically based on the highest index Learning this helps me understand why arrays in JS behave differently from arrays in other languages, and why knowing the inner workings is crucial for writing efficient and bug-free code. Every day, as I explore deeper, I realize that mastering the fundamentals is what builds a solid foundation as a developer. Step by step, my understanding of JavaScript is getting stronger and more confident! 💪 #JavaScript #100DaysOfCode #WebDevelopment #LearningJourney #FrontendDevelopment #CodingFundamentals
To view or add a comment, sign in
-
-
Reversing a string in JavaScript can be done in more than one way. I revisited this problem today and tried three approaches, each with a different mindset: // 1. Using built-in methods const reverse1 = (str) => str.split("").reverse().join(""); // 2. Using a loop (more control) function reverse2(str) { let result = ""; for (let i = str.length - 1; i >= 0; i--) { result += str[i]; } return result; } // 3. Using reduce (functional style) const reverse3 = (str) => str.split("").reduce((acc, char) => char + acc, ""); console.log(reverse1("hello")); //"olleh" console.log(reverse2("hello")); //"olleh" console.log(reverse3("hello")); //"olleh" Methods I used: • Built-in methods → concise and readable • Loop → full control and clarity • reduce → functional and expressive This reminded me that in real projects, how you think about a problem matters as much as the answer itself. Still learning, still building, still showing up. #JavaScript #FrontendDevelopment #LearningInPublic #JuniorDeveloper
To view or add a comment, sign in
Explore related topics
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