🔍 JavaScript Logic That Looks Simple… But Isn’t! Ever wondered how this works? 👇 if (!isNaN(str[i]) && str[i] % 2 == 0) { console.log(str[i]); } Let’s break it down: Suppose: let str = "a1b2c3d4"; 🔹 Step 1: str[i] Gives each character → "a", "1", "b", "2"... 🔹 Step 2: !isNaN(str[i]) Checks if the character can be converted to a number "2" → valid number ✅ "a" → not a number ❌ 🔹 Step 3: str[i] % 2 == 0 JavaScript converts "2" → 2 Then checks if it’s even ⚡ Hidden Magic: Short-Circuit (&&) If the first condition fails, JavaScript skips the second condition So for "a": !isNaN("a") → false % 2 is never executed 🚫 ✅ Final Output: 2 4 🚀 Key Takeaways: ✔ JavaScript automatically converts strings to numbers in calculations ✔ isNaN() helps filter numeric values ✔ && prevents errors using short-circuiting 💬 Clean logic like this is often used in string parsing & interview problems Would you like more such real-world JS tricks? 👇 #JavaScript #WebDevelopment #Coding #100DaysOfCode #LearnToCode
JavaScript Logic Breakdown: String Parsing with isNaN
More Relevant Posts
-
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
-
-
🔥 var vs let vs const in JavaScript (Explained Simply) Understanding the difference between `var`, `let`, and `const` is essential for writing clean and bug-free JavaScript code. Let’s break it down 👇 🔹 1️⃣ var #Example var name = "Amit"; var name = "Rahul"; // Re-declaration allowed ✅ Function scoped ✅ Can be re-declared and updated ⚠️ Hoisted with `undefined` ❌ Can cause unexpected bugs 👉 Avoid using `var` in modern JavaScript. 🔹 2️⃣ let #Example let age = 25; age = 30; // Update allowed ✅ Block scoped ❌ Cannot be re-declared in same scope ✅ Can be updated ✅ Safer than `var` 👉 Use `let` when the value needs to change. 🔹 3️⃣ const #Example const pi = 3.14; // pi = 3.1415; ❌ Error ✅ Block scoped ❌ Cannot be re-declared ❌ Cannot be updated ✅ Must initialize at declaration 💡 For objects/arrays → You can modify properties, but not reassign the reference. 🚀 Best Practice ✔️ Use `const` by default ✔️ Use `let` when reassignment is required ❌ Avoid `var` Writing cleaner code starts with choosing the right variable declaration. #JavaScript #WebDevelopment #Frontend #Programming #CodingTips #Developers
To view or add a comment, sign in
-
-
A common misconception in JavaScript: “Objects are copied.” Let’s test that: let obj1 = { name: "John" }; let obj2 = obj1; obj2.name = "Doe"; console.log(obj1.name); // "Doe" At first, this feels unexpected. But here’s what’s really happening: JavaScript doesn’t copy the object. It copies the reference to that object. So both obj1 and obj2 point to the same memory location. That’s why changing one reflects in the other. This is one of the most common concepts tested in interviews — often with tricky variations. Understanding this clearly means you won’t rely on guesses anymore. 👉 I’ve broken this and similar concepts step-by-step in the full video (link in comments)
Why JavaScript Objects Don’t Actually “Copy”
To view or add a comment, sign in
-
The most confusing thing in JavaScript every time I go through core JS revision is 'this' Keyword? And the funny part? “this” doesn’t actually mean this. Most people think: " this = current object " Reality: 👉 this = depends on how the function is called Example: const obj = { name: "JS", say() { console.log(this.name); } }; obj.say(); // JS ✅ Now: const fn = obj.say; fn(); // undefined ❌ Same function. Different result. Why? 👉 Because this is decided at call time, not when the function is written. And then arrow functions make it worse: const obj = { name: "JS", say: () => { console.log(this.name); } }; obj.say(); // undefined 😭 👉 Arrow functions don’t have their own this 👉 They inherit it from the surrounding scope 💡 Insight: If you don’t understand this, you’re not debugging JavaScript… you’re guessing. 🎯 Rule of thumb: Regular functions → this depends on how they’re called Arrow functions → this is inherited Detached functions → this gets lost Once this clicks, JavaScript suddenly stops feeling “random”. Save this before this humbles you in production 🙂
To view or add a comment, sign in
-
-
🔍 A small JavaScript detail that can cause unexpected bugs: Object key ordering Many developers assume object keys are always returned in insertion order, but JavaScript actually follows a specific ordering rule when you iterate over object properties (Object.keys, Object.entries, for...in). The order is: • Integer index keys → sorted in ascending order • String keys → insertion order • Symbol keys → insertion order (not included in Object.keys) This is one of the reasons why using Object as a map can sometimes lead to unexpected iteration behavior when numeric keys are involved. If key order matters, Map is usually the more predictable choice since it preserves insertion order for all key types. Small language details like this are easy to overlook, but they often explain those subtle bugs you run into during debugging. #JavaScript #SoftwareEngineering #Frontend
To view or add a comment, sign in
-
-
Day 23/100 of JavaScript Today’s topic : "this" keyword "this" refers to the object that is currently executing the function But its value depends on how the function is called, not where it is written 🔹In object method const user = { name: "Apsar", greet() { console.log(this.name); } }; user.greet(); // Apsar 🔹In regular function function show() { console.log(this); } show(); // global object (or undefined in strict mode) 🔹Arrow function const obj = { name: "Apsar", greet: () => { console.log(this.name); } }; obj.greet(); // undefined 👉 Arrow functions don’t have their own "this", they inherit it 🔹call, apply, bind function greet() { console.log(this.name); } const user = { name: "Apsar" }; greet.call(user); #Day23 #JavaScript #100DaysOfCode
To view or add a comment, sign in
-
🚀 Exploring Blog 9 of the JS series: Map and Set in JavaScript. While developers often rely on objects and arrays, there are specific scenarios where Maps and Sets offer distinct advantages. Understanding when to use these data structures can enhance your coding practices. For insights into these use cases, check out the short blog linked below. Blog link: https://lnkd.in/gWRsZxy6 Hitesh Choudhary Piyush Garg Chai Aur Code #webdevcohort2026 #javascript #jsdatatypes
To view or add a comment, sign in
-
JavaScript is powerful, but also weird sometimes Some things that still surprise developers 👇 1. [] + [] → "" Reason: Arrays are converted to strings → empty string + empty string 2. [] + {} → "[object Object]" Reason: Object gets converted to string 3. {} + [] → 0 Reason: {} is treated as a block, not an object 4. typeof null → "object" Reason: Historical bug in JavaScript (never fixed) 5. NaN === NaN → false Reason: NaN is not equal to anything, even itself 6. 0.1 + 0.2 === 0.3 → false Reason: Floating point precision issue 7. false == '0' → true Reason: Type coercion converts both to number 8. [] == false → true Reason: Both become 0 after coercion 9. '' == 0 → true Reason: Empty string converts to 0 10. null == undefined → true Reason: Special equality rule in JS => Always prefer === over == to avoid surprises
To view or add a comment, sign in
-
💡 Short Circuiting in JavaScript — Explained Simply In JavaScript, I came across a powerful concept called Short Circuiting. 👉 In simple words: JavaScript stops checking further values as soon as the result is decided. 🔹 OR (||) Operator It returns the first TRUE (truthy) value it finds. Example: console.log(false || "Javascript"); ✔️ Output: "Javascript" Another example: console.log(false || 10 || 7 || 15); ✔️ Output: 10 👉 Why? Because JavaScript finds 10 (true value) and stops checking further values 🔹 My Practice Code 👨💻 console.log("Short circuit in OR operator"); console.log(false || "Javascript"); console.log(false || "OR Operator"); console.log(false || 3); console.log(false || 10 || 7 || 15 || 20); // short circuit in OR operator console.log(false || "Javascript - client side scripting language" || "HTML - structure of web page" || "CSS - Cascading Style Sheet" || "Bootstrap - Framework of CSS"); 🔹 Recap: ✔️ JavaScript returns the first truthy value ✔️ It does not check remaining values once result is found ✔️ This makes code faster and efficient 📌 In simple words: Short Circuiting = JavaScript stops early when result is found #JavaScript #WebDevelopment #Coding #Learning #Frontend #100DaysOfCode
To view or add a comment, sign in
-
"If you’re not using "map", "filter", and "reduce" in JavaScript… you're probably writing more code than needed." 😅 These 3 array methods can level up your code instantly 👇 🔹 map() 👉 Transforms each element of an array 👉 Returns a new array 💻 Example: const nums = [1, 2, 3]; const doubled = nums.map(n => n * 2); // [2, 4, 6] 🔹 filter() 👉 Filters elements based on a condition 👉 Returns a new array 💻 Example: const nums = [1, 2, 3, 4]; const even = nums.filter(n => n % 2 === 0); // [2, 4] 🔹 reduce() 👉 Reduces array to a single value 👉 Very powerful (but often misunderstood) 💻 Example: const nums = [1, 2, 3, 4]; const sum = nums.reduce((acc, curr) => acc + curr, 0); // 10 🚀 Pro Tip: Use "map" for transformation, "filter" for selection, and "reduce" for everything else. 💬 Which one do you use the most in your projects? #javascript #webdevelopment #mern #coding #developers
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