🚨 JavaScript Brain Teasers That Will Mess With Your Mind. ❓ console.log(["A"] + ["B"]) 👉 Output: "AB" ❓ let arr1 = [1,2,3] let arr2 = [4,5,6] console.log(arr1 + arr2) 👉 Output: "1,2,34,5,6" ❓ console.log(+null) 👉 Output: 0 ❓ console.log(+"hello") 👉 Output: NaN ❓ let arr = [1,2,3] let str = "1,2,3" console.log(arr == str) 👉 Output: true ❓ console.log(10 == [10]) 👉 Output: true ❓ console.log(10 == [[[[10]]]]) 👉 Output: true ❓ var fruits = ["orange", "mango", "banana"] var fruitObj = { ...fruits } console.log(fruitObj) 👉 Output: {0: "orange", 1: "mango", 2: "banana"} ❓ console.log(null ?? true) 👉 Output: true ❓ console.log(undefined ?? true) 👉 Output: true 🔥 Takeaway: Most of this comes down to type coercion and how JS internally converts values. #JavaScript #WebDevelopment #Coding #Frontend #Programming #JavaScriptTips #JavaScriptTricks #JSConcepts #LearnJavaScript #FrontendDevelopment #FrontendDeveloper #WebDevCommunity #CodingTips #CodeNewbie #ProgrammingLife #DeveloperCommunity #DevLife #CodeChallenge #DailyCoding #CodeWithMe #TechContent #SoftwareDevelopment #FullStackDeveloper #JSDevelopers #ProgrammingTips #CodeDaily #DevTips
JavaScript Brain Teasers and Quirks Explained
More Relevant Posts
-
🔁 Understanding the forEach() loop in JavaScript The forEach() method is a simple way to iterate over arrays and perform an action for each element. 👉 Syntax: array.forEach((item, index) => { // logic here }); 👉 Example: const numbers = [1, 2, 3, 4]; numbers.forEach((num, index) => { console.log(`Index: ${index}, Value: ${num}`); }); 💡 Key Points: ✔️ Executes a function for each array element ✔️ Does not return a new array ✔️ Cannot break or use return to stop the loop If you need a return value, consider using map() instead. Small concepts like this build a strong JavaScript foundation 🚀 #JavaScript #WebDevelopment #Frontend #Coding #LearnToCode
To view or add a comment, sign in
-
🚨 JavaScript Gotcha: Objects as Keys?! Take a look at this 👇 const a = {}; const b = { key: 'b' }; const c = { key: 'c' }; a[b] = 123; a[c] = 456; console.log(a[b]); // ❓ 👉 What would you expect? 123 or 456? 💡 Actual Output: 456 🤯 Why does this happen? In JavaScript, object keys are always strings or symbols. So when you use an object as a key: a[b] → a["[object Object]"] a[c] → a["[object Object]"] Both b and c are converted into the same string: "[object Object]" ⚠️ That means: a[b] = 123 sets " [object Object] " → 123 a[c] = 456 overwrites it → 456 So finally: console.log(a[b]); // 456 🧠 Key Takeaways ✅ JavaScript implicitly stringifies object keys ✅ Different objects can collide into the same key ❌ Using objects as keys in plain objects is unsafe 🔥 Pro Tip If you want to use objects as keys, use a Map instead: const map = new Map(); map.set(b, 123); map.set(c, 456); console.log(map.get(b)); // 123 ✅ ✔️ Map preserves object identity ✔️ No unexpected overwrites 💬 Final Thought JavaScript often hides complexity behind simplicity. Understanding these small quirks is what separates a developer from an expert. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #Coding #JavaScriptTips #JSConfusingParts #DevelopersLife #CodeNewbie #LearnToCode #SoftwareEngineering #TechTips #CodeQuality #CleanCode #100DaysOfCode #ProgrammingTips #DevCommunity #CodeChallenge #Debugging #JavaScriptDeveloper #MERNStack #FullStackDeveloper #ReactJS #NodeJS #WebDevTips #CodingLife
To view or add a comment, sign in
-
-
🚀 Dynamic Currying in JavaScript — Why it actually matters At first, currying feels like a trick: sum(1)(2)(3) But the real power isn’t syntax — it’s reusability. 💡 The idea 👉 Fix some arguments now 👉 Reuse the function later 🔧 Example const filter = fn => arr => arr.filter(fn); const filterEven = filter(x => x % 2 === 0); filterEven([1,2,3,4]); // [2,4] Instead of repeating logic everywhere, you create reusable building blocks. ⚡ Real-world uses API helpers → request(baseUrl)(endpoint) Logging → logger("ERROR")(msg) Event handlers → handleClick(id)(event) Validation → minLength(8)(value) 🧠 Key takeaway Currying isn’t about fancy functions. It’s about writing code that is: ✔ Reusable ✔ Composable ✔ Cleaner Libraries like Lodash and Ramda use this pattern heavily. Once this clicks, your approach to writing functions changes completely. #JavaScript #WebDevelopment #FunctionalProgramming #Currying #CleanCode #Frontend #Coding #100DaysOfCode #DeveloperJourney #TechCommunity
To view or add a comment, sign in
-
-
Well, JavaScript is the ocean that has many small fishes in terms of libraries, and sometimes we have to take a deep dive into many libraries, and integrating burns you out to the core, doesn't it? For logging out the time and date? year? along with seconds, it surely makes our mind chaotic, so we just need some fresh air at that time in a way to relax. // Using Moment.js (Legacy) const nextWeek = moment().add(7, 'days'); // Using Day.js (Modern-ish pre-Temporal) const nextWeek = dayjs().add(7, 'day'); Intriguingly, the new JS update eases our lives as coders, even in the next generation AI, we lack empathy. Does the code work, or actually logics making a significant difference? So let's get into it, Temporal Temporal is the advanced update to resolve dependencies like Moment.js or some other hectic libraries. It gives you a smart, intelligent way to add days in the current date flow just by using the syntax below to handle complex logics efficiently. // No more library dependencies like Moment.js or Day.js! const today = Temporal.Now.plainDateISO(); const nextWeek = today.add({ days: 7 }); console.log(nextWeek.toString()); // Clean, predictable, and immutable. #vibeCoding #javascript #angular #react #NextJs #TypeScript #frontendDevelopment
To view or add a comment, sign in
-
JavaScript is easy. Until it isn't. 😅 Every developer has been there. You're confident. Your code looks clean. You hit run. And then: " Cannot read properties of undefined (reading 'map') " The classic JavaScript wall. Here are 7 JavaScript mistakes I see developers make constantly and how to fix them: 1. Not understanding async/await ⚡ → Wrong: | const data = fetch('https://lnkd.in/dMDBzbsK'); console.log(data); // Promise {pending} | → Right: | const data = await fetch('https://lnkd.in/dMDBzbsK'); | 2. Using var instead of let/const → var is function scoped and causes weird bugs → Always use const by default. let when you need to reassign. Never var. 3. == instead of === → 0 == "0" is true in JavaScript 😱 → Always use === for comparisons. Always. 4. Mutating state directly in React → Wrong: user.name = "Shoaib" → Right: setUser({...user, name: "Shoaib"}) 5. Forgetting to handle errors in async functions → Always wrap await calls in try/catch → Silent failures are the hardest bugs to track down 6. Not cleaning up useEffect in React → Memory leaks are real → Always return a cleanup function when subscribing to events 7. Treating arrays and objects as primitives → [] === [] is false in JavaScript → Reference types don't compare like numbers — learn this early JavaScript rewards the developers who understand its quirks. 💡 Which of these caught YOU off guard when you first learned it? 👇 #JavaScript #WebDevelopment #Frontend #FullStackDeveloper #React #Programming #CodingTips #Developer #Tech #Pakistan #LearnToCode #JS #SoftwareEngineering #100DaysOfCode #PakistaniDeveloper
To view or add a comment, sign in
-
-
Day 2: The Secret Life of a Function Call — Global vs. Local Execution Context 🚀 Today, I went deeper into the "Big Box" of JavaScript to understand exactly what happens when we call a function. Using this simple square function as an example, here is the line-by-line magic: 🎭 The Two-Phase Performance Phase 1: Memory Allocation Before a single line of code runs, JavaScript scans everything. n, square2, and square4 are allocated memory and set to undefined. The square function gets its own memory space with the entire function code stored inside. Phase 2: Code Execution Line 1: n is assigned the value 2. Line 6: This is where it gets interesting! A Function Invocation happens. 📦 The "Mini Box": Functional Execution Context When square(n) is called, a New Execution Context is created inside the Global one! Memory Phase: A local variable ans is created (undefined). Code Phase: num becomes 2, ans becomes 4. The Return Statement: This is the exit signal. It returns the value 4 to square2 and destroys the local execution context immediately. 📚 The Call Stack: The Manager of it All How does JS keep track of these nested boxes? The Call Stack. It's a stack (LIFO - Last In, First Out). Bottom of stack: Global Execution Context (GEC). When a function is called, it's pushed onto the stack. When it returns, it's popped off. 💡 Interview Tip: Did you know the Call Stack has many names? It’s also called the Execution Context Stack, Program Stack, Control Stack, Runtime Stack, or Machine Stack. Understanding how the stack grows and shrinks is the key to mastering Recursion and avoiding the dreaded "Stack Overflow"! Drop a "🚀" if you’re also following the Namaste JavaScript series! #JavaScript #WebDevelopment #CallStack #ExecutionContext #ProgrammingLogic #FrontendEngineer #CodingCommunity #JSFundamentals
To view or add a comment, sign in
-
-
🚀 Understanding Factory Functions in JavaScript Ever felt confused using constructors and the new keyword? 🤔 That’s where Factory Functions make life easier! 👉 A Factory Function is simply a function that creates and returns objects. 💡 Why use Factory Functions? ✔️ No need for new keyword ✔️ Easy to understand (perfect for beginners) ✔️ Avoids this confusion ✔️ Helps in writing clean and reusable code ✔️ Supports data hiding using closures 🧠 Example: function createUser(name, age) { return { name, age, greet() { console.log("Hello " + name); } }; } const user = createUser("Sushant", 21); user.greet(); ⚠️ One downside: Methods are not shared (can use more memory) 🎯 Conclusion: Factory Functions are a great way to start writing clean and maintainable JavaScript code without complexity. #JavaScript #WebDevelopment #FrontendDeveloper #CodingJourney #LearnToCode #100DaysOfCode
To view or add a comment, sign in
-
-
🤔 Ever wondered… Why this works: console.log(a) // undefined var a = 10; But this crashes: console.log(b) // ReferenceError let b = 20; Even though both are declared later? 👉 This is where most developers think they understand JavaScript… but they don’t. 🚀 Let’s break it down: Hoisting & Temporal Dead Zone (TDZ) 🧠 Hoisting (What actually happens behind the scenes) JavaScript doesn’t execute your code line by line directly. Before execution, it runs a Memory Creation Phase where: • Variables & functions are registered in memory • Declarations are processed first 👉 This is what we call hoisting 📦 Variable Hoisting With var: • Declaration is hoisted • Initialized with undefined So: • You can access it before declaration • But you won’t get the actual value , since Initialized with undefined in memory creation phase 💡 Key insight: Hoisting ≠ moving code It’s about how memory is allocated internally. ⚠️ let & const → Temporal Dead Zone (TDZ) Yes — let and const are also hoisted. But… They stay in a Temporal Dead Zone from: 👉 start of scope → until declaration line Accessing them early = 💥 ReferenceError 💡 Takeaway: TDZ exists to prevent unpredictable bugs caused by premature access. 👑 Function Hoisting (VIP behavior) Function Declarations are fully hoisted: ✔ You can call them before declaration But Function Expressions behave differently: • var → undefined • let/const → ReferenceError ⚡ Why this actually matters (not just theory) Understanding hoisting + TDZ helps you: • Avoid silent bugs (undefined issues) • Write predictable, cleaner code • Debug scope-related issues faster • Truly understand how JS engine works 💡 Final Thought: Most developers memorize hoisting. Good developers understand execution context. Great developers write code that doesn’t depend on hoisting at all. 📌 I’ll be sharing more deep dives like this as I learn & build in public. Follow along if you’re into JavaScript internals 🚀 #JavaScript #FrontendDevelopment #WebDevelopment #Hoisting #TDZ #LearnJavaScript #CodingTips #BuildInPublic #100DaysOfCode
To view or add a comment, sign in
-
-
⚛️ What is a Prototype in JavaScript? This is the concept that made everything click for me. Every object in JavaScript has a hidden link: 👉 [[Prototype]] 💡 Simple example: const user = { sayHi() { console.log("Hi"); } }; const ahmed = { name: "Ahmed" }; ahmed.__proto__ = user; ahmed.sayHi(); // "Hi" Wait… ahmed doesn’t have sayHi. So how did it work? 👉 JavaScript looks up the prototype chain 🔥 What actually happens: JS looks inside ahmed Not found Goes to its prototype Finds sayHi → executes 🧠 That’s inheritance in JavaScript. Not copying code… but linking objects together. 🚀 My takeaway: Objects in JS don’t stand alone — they’re part of a chain. And understanding that chain changes everything. #JavaScript #Frontend #Programming #OOP
To view or add a comment, sign in
-
Early on, I used var for everything in JavaScript. Then I learned why that's a problem. JavaScript has three ways to declare variables: var — function-scoped, can be re-declared, and has hoisting quirks that cause subtle bugs. Avoid it in modern code. let — block-scoped, can be reassigned. Use it when the value needs to change. const — block-scoped, cannot be reassigned. Use it by default for everything that doesn't change. My rule of thumb: Start with const. If you need to reassign, use let. Never use var. This isn't just style preference — it's about writing predictable, debuggable code. When I open a file and see const everywhere, I immediately know those values shouldn't change. It's self-documenting. In a team environment, readable and predictable code is just as important as working code. Do you still reach for var out of habit? It's worth breaking.
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