🚀 Day 5/108 – Type Conversion & Type Coercion in JavaScript Continuing my 108-day JavaScript journey — today I learned how JavaScript handles types 👇 👉 Type Conversion (Explicit) Manually converting a value from one type to another. Examples: • "String(123)" → ""123"" • "Number("456")" → "456" • "Boolean(0)" → "false" 👉 Type Coercion (Implicit) JavaScript automatically converts types during operations. Examples: • ""5" + 2" → ""52"" (string) • ""5" - 2" → "3" (number) • "true + 1" → "2" 💻 Example: let str = String(123); // "123" let num = Number("456"); // 456 console.log("5" + 2); // "52" console.log("5" - 2); // 3 🧠 Key Insight: Type coercion can sometimes lead to unexpected results, so it's safer to use explicit conversion when needed. ⚠️ Pro Tip: Always use "===" instead of "==" to avoid unwanted type coercion. 🔥 Learning step by step — consistency is everything! Have you ever faced a bug because of type coercion? 👇 #JavaScript #WebDevelopment #CodingJourney #LearningInPublic #100DaysOfCode
JavaScript Type Conversion and Coercion Explained
More Relevant Posts
-
**AVOID JAVASCRIPT'S QUIET BUGS:** **Don't use ==, use ===** --- 🔺 **THE PROBLEM: == COERCION** ```js console.log([] == false); // prints true! 😅 ``` **The behind-the-scenes journey:** ``` [] ↓ (empty array) "" ↓ (string) 0 ↓ (number) false ↓ (boolean) 0 ``` Wait, why is that true? JavaScript silently converts types, leading to unexpected results. **This is confusing behavior!** --- 🔺 **THE FIX: STRICT EQUALITY** ```js console.log([] === false); // prints false! 🎉 ``` Uses strict comparison without hidden type conversions. **Predictable and safe.** --- 🔺 **NO HIDDEN CONVERSION!** --- **MAKING YOUR CODE PREDICTABLE: ALWAYS USE ===** Have you encountered confusing JavaScript type coercion? Share your experience! 👇 #javascript #webdevelopment #frontend #coding #developers #mern #learning
To view or add a comment, sign in
-
-
🚀 Day 6/108 – Conditional Statements in JavaScript Continuing my 108-day JavaScript journey — today I learned how to make decisions in code 👇 👉 What are Conditional Statements? They allow us to execute different blocks of code based on conditions. 🧠 Types of Conditional Statements: 🔹 if statement Executes code if a condition is true 🔹 if...else statement Executes one block if true, another if false 🔹 if...else if...else Used to check multiple conditions 🔹 switch statement Used when comparing one value against multiple cases 💻 Example: let age = 18; if (age >= 18) { console.log("You are an adult"); } else { console.log("You are a minor"); } 🧠 Key Insight: Conditions always return either "true" or "false". ⚠️ Quick Note: JavaScript also has truthy and falsy values Falsy values → "false, 0, "", null, undefined, NaN" 🔥 Learning step by step — consistency is everything! How do you usually write conditions — if-else or switch? 👇 #JavaScript #WebDevelopment #CodingJourney #LearningInPublic #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Why Does null Show as an Object in JavaScript? 🤯 While practicing JavaScript, I came across something interesting: let myVar = null; console.log(typeof myVar); // Output: object At first, it feels confusing… why is null an object? 🤔 💡 Here’s the simple explanation: null is actually a primitive value that represents "no value" or "empty". But when JavaScript was first created, there was a bug in the typeof operator. Due to this bug, typeof null returns "object" instead of "null". ⚠️ This behavior has been kept for backward compatibility, so changing it now would break existing code. 🔍 Key Takeaways: null → means "nothing" (intentional empty value) typeof null → returns "object" (this is a historical bug) Objects (like {}) also return "object" 💻 Example: let myObj = { name: "John" }; console.log(typeof null); // object ❌ (bug) console.log(typeof myObj); // object ✅ (correct) 📌 Conclusion: Even though both return "object", they are completely different in meaning. 👉 JavaScript is powerful, but it has some quirky behaviors—this is one of them! #JavaScript #WebDevelopment #CodingJourney #100DaysOfCode #FrontendDevelopment
To view or add a comment, sign in
-
-
🚨 JavaScript Gotcha: When 0 Actually Matters One of the most subtle bugs in JavaScript comes from using the logical OR (||) for default values. const timeout = userTimeout || 3000; Looks fine… until userTimeout = 0. 👉 JavaScript treats 0 as falsy, so instead of respecting your value, it silently replaces it with 3000. 💥 Result? Unexpected behavior. ✅ The Fix: Use Nullish Coalescing (??) const timeout = userTimeout ?? 3000; This only falls back when the value is null or undefined — not when it’s 0. 💡 When does 0 actually matter? ⏱️ Timeouts & delays → 0 can mean run immediately 📊 Counters & stats → 0 is a valid value, not “missing” 💰 Pricing / discounts → Free (0) ≠ undefined 🎚️ Sliders / configs → Minimum values often start at 0 🧠 Rule of thumb: Use || when you want to catch all falsy values (0, "", false, etc.) Use ?? when you only want to catch missing values (null, undefined) ⚡ Small operator. Big difference. Cleaner logic. #reactjs,#nodejs #JavaScript #WebDevelopment #CleanCode #Frontend #ProgrammingTips #DevTips #CodeQuality #SoftwareEngineering
To view or add a comment, sign in
-
-
🧠 JavaScript Hoisting Explained Simply Hoisting is one of those JavaScript concepts that can feel confusing — especially when your code behaves unexpectedly. Here’s a simple way to understand it 👇 🔹 What is Hoisting? Hoisting means JavaScript moves declarations to the top of their scope before execution. But there’s a catch 👇 🔹 Example with var console.log(a); var a = 10; Output: undefined Why? Because JavaScript internally treats it like: var a; console.log(a); a = 10; 🔹 What about let and const? console.log(b); let b = 20; This throws a ReferenceError. Because "let" and "const" are hoisted too — but they stay in a “temporal dead zone” until initialized. 🔹 Function hoisting Functions are fully hoisted: sayHello(); function sayHello() { console.log("Hello"); } This works because the function is available before execution. 🔹 Key takeaway • "var" → hoisted with "undefined" • "let/const" → hoisted but not initialized • functions → fully hoisted 💡 One thing I’ve learned: Many “weird” JavaScript bugs come from not understanding hoisting properly. Curious to hear from other developers 👇 Did hoisting ever confuse you when you started learning JavaScript? #javascript #frontenddevelopment #webdevelopment #reactjs #softwareengineering #developers
To view or add a comment, sign in
-
-
💡 Still confused about call(), apply(), and bind() in JavaScript? Let’s fix that in 60 seconds. If you've ever struggled with how this works in JavaScript… you're not alone. These three methods are your secret weapons to take control of it. 👉 Here’s the simplest way to understand them: 🔹 call() Invokes the function immediately Pass arguments one by one fn.call(thisArg, arg1, arg2) 🔹 apply() Also invokes immediately But takes arguments as an array fn.apply(thisArg, [args]) 🔹 bind() Does NOT run immediately Returns a new function you can call later const newFn = fn.bind(thisArg) 🧠 Think of it like this: call → “Run now, here are the args” apply → “Run now, here’s a list of args” bind → “Save this for later with this context” ✨ Why it matters: Mastering these helps you: ✔ Control this like a pro ✔ Reuse methods across objects ✔ Avoid common bugs in callbacks & event handlers 🔥 Pro tip: In modern JS, apply() is less common thanks to the spread operator: fn.call(thisArg, ...args) 📌 If you're preparing for interviews or leveling up your JS fundamentals — this trio is a must-know. 💬 Which one do you use the most: call, apply, or bind? #JavaScript #WebDevelopment #Frontend #CodingTips #100DaysOfCode
To view or add a comment, sign in
-
-
Day 3: Hoisting — The JavaScript "Magic" That Isn't Magic at All! 🎩✨ Today, I tackled one of the most famous (and often misunderstood) concepts in JavaScript: Hoisting. If you've ever wondered why you can call a function before you even define it in your code, you've witnessed Hoisting in action! 🤔 What is Hoisting? Hoisting is a mechanism where variables and function declarations are moved to the top of their containing scope during the Memory Allocation Phase, before the code even starts executing. 🔍 Under the Hood (The Execution Context) Remember the "Big Box" (Execution Context) from Day 1? Here is what happens during the Memory Phase: Variables (var): JS allocates memory for variables and initializes them with a special value: undefined. Functions: JS stores the entire function body in memory. This is why: Calling a function at Line 1 works perfectly! ✅ Accessing a var at Line 1 returns undefined instead of an error! ⚠️ 💻 The Browser Demo (The Call Stack) Watching this live in the Sources tab of Chrome DevTools was a game-changer. Seeing the Global scope populate with variables before the first line of code executed made everything click. 💡 Interview Tip: When asked "What is Hoisting?", don't just say "it moves code to the top." Better Answer: "Hoisting is the process where the JS Engine allocates memory for variables and functions during the Creation Phase of the Execution Context. This allows us to access functions and variables even before they are initialized in the code, though var will return undefined until the execution reaches its assignment." Next up: Diving into how let and const handle hoisting differently (The Temporal Dead Zone!). Are you a var, let, or const person? Let's discuss below! 👇 #JavaScript #WebDevelopment #Hoisting #NamasteJavaScript #CodingInterviews #FrontendEngineer #ProgrammingLogic #JSFundamentals
To view or add a comment, sign in
-
-
Day 5: The Shortest JavaScript Program — What happens when you write NOTHING? 📄✨ Today I learned that even if you create a totally empty .js file and run it in a browser, JavaScript is already working hard behind the scenes. 🕵️♂️ The "Shortest Program" If your file has zero lines of code, the JavaScript Engine still does three major things: Creates a Global Execution Context. Creates a window object (in browsers). Creates the this keyword. 🪟 What is window? The window is a massive object created by the JS engine that contains all the built-in methods and properties (like setTimeout, localStorage, or console) provided by the browser environment. 🧭 The this Keyword At the global level, JavaScript sets this to point directly to the window object. 👉 Proof: If you type console.log(this === window) in an empty file, it returns true! 🌐 The Global Space I also explored the Global Space—which is any code you write outside of a function. If you declare var x = 10; in the global space, it automatically gets attached to the window object. You can access it using x, window.x, or this.x. They all point to the same memory location! 💡 Key Takeaway: Anything not inside a function sits in the Global Memory Space. Keeping this space clean is vital for performance and avoiding variable name collisions in large apps! It’s fascinating to see that even before we write our first line of code, JavaScript has already set up the entire "universe" for us to work in. #JavaScript #WebDevelopment #NamasteJavaScript #ExecutionContext #WindowObject #JSFundamentals #CodingJourney #FrontendEngineer
To view or add a comment, sign in
-
-
Day 18 of My JavaScript Journey 🚀 Today, I built my second JavaScript project (A Modal Window.) The project works like this: • Clicking show modal button opens a modal (popup box) • Clicking the close button hides it • Pressing the “Escape” key also closes it In this project, I used: • document.querySelector to select elements • addEventListener to handle user actions • classList to show and hide the modal • keydown event to detect when the ESC key is pressed One thing I found interesting: Handling keyboard events made the project feel more interactive and user-friendly. Key takeaway: JavaScript allows you to control both mouse and keyboard interactions on a webpage. #JavaScript #WebDevelopment #LearningInPublic #100DaysOfCode
To view or add a comment, sign in
-
-
You fix an HTML issue… and it takes minutes. You debug CSS… and it tests your patience. But when it comes to JavaScript… that’s where things get real. Because it’s not just about what you see… it’s about logic, flow, and hidden bugs. One small mistake… and everything breaks silently. That’s why: HTML feels simple, CSS feels tricky, but JavaScript challenges your thinking. Debugging isn’t just fixing code… it’s understanding how everything connects. So the real question is — which one slows you down the most? 👇 #WebDevelopment #JavaScript #CSS #HTML #Debugging #DevLife
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