🚨 JavaScript Array Methods look simple… until they don’t. Most developers learn map(), filter(), and reduce() early. But when you actually practice them deeply, you start noticing small behaviors that can easily trip you up in interviews or real projects. Today I spent time revisiting these core methods, and a few surprisingly tricky edge cases stood out. Here are some that caught my attention 👇 ⚠️ 1️⃣ map() without a return [1,2,3].map(x => { x * 2 }) Output: [undefined, undefined, undefined] Why? Because when you use {} in arrow functions, you must explicitly return the value. ⚠️ 2️⃣ Thinking filter(x => x % 2) returns even numbers [1,2,3,4].filter(x => x % 2) Output: [1,3] Because: odd % 2 → 1 → true even % 2 → 0 → false So this actually returns odd numbers, not even ones. ⚠️ 3️⃣ Using map() when filter() is needed [1,2,3,4].map(x => { if(x % 2 === 0) return x; }) Output: [undefined, 2, undefined, 4] Because map() always keeps the same array length, even when nothing is returned. ⚠️ 4️⃣ The famous parseInt trap [1,2,3].map(parseInt) Output: [1, NaN, NaN] Why this happens: map() passes (element, index) to the callback. So it becomes: parseInt(1,0) parseInt(2,1) parseInt(3,2) Which leads to unexpected results. 💡 Big takeaway: Knowing JavaScript syntax is useful. But understanding how JavaScript actually behaves internally is what makes you a better developer. Small details like these often separate surface knowledge from real mastery. If you're learning JavaScript right now, try experimenting with these methods yourself. You’ll be surprised how much depth there is. 🚀 💬 Which JavaScript behavior confused you the most when you were learning? Let’s share and learn together. #javascript #webdevelopment #frontenddevelopment #softwareengineering #coding #programming #developers #100daysofcode #learninpublic #techcommunity #codingtips #javascriptdeveloper
JavaScript Array Methods: Tricky Edge Cases
More Relevant Posts
-
🚨 Most developers think they understand JavaScript Arrays… until they see these results. 🤯 Today during my JavaScript practice, I realized something important: 👉 JavaScript arrays are easy to use, but tricky to truly understand. Some small examples can completely change how you think about the language. 🔥 1. map() vs forEach() let arr = [1,2,3]; let a = arr.forEach(x => x * 2); let b = arr.map(x => x * 2); console.log(a); // undefined console.log(b); // [2,4,6] ⚡ forEach() executes logic but returns nothing ⚡ map() returns a new transformed array 🔥 2. The famous sort() trap [1,2,10].sort() Result: [1,10,2] Why? 🤔 Because JavaScript sorts values as strings by default, not numbers. Correct way: [1,2,10].sort((a,b)=>a-b) 🔥 3. Removing duplicates from an array let arr = [1,2,3,2,1]; let unique = arr.filter((x,i,a) => a.indexOf(x) === i); console.log(unique); // [1,2,3] 🔥 4. Getting duplicate values let duplicates = arr.filter((x,i,a) => a.indexOf(x) !== i); Output: [2,1] 💡 Big learning from today: JavaScript isn’t just about writing code. It’s about understanding how the language actually behaves under the hood. Small hidden behaviors can make a huge difference in interviews and real-world projects. 📚 Array methods I practiced today ✔ push ✔ pop ✔ shift ✔ unshift ✔ splice ✔ slice ✔ map ✔ filter ✔ reduce ✔ find ✔ findIndex ✔ includes ✔ indexOf ✔ sort ✔ forEach ✔ every Still learning. Still improving. 🚀 If you're learning JavaScript too, which array method confused you the most when you started? 👇 #javascript #webdevelopment #frontenddevelopment #programming #coding #softwaredeveloper #developers #techcommunity #100daysofcode #learninpublic #js #codingjourney #webdev #developerlife
To view or add a comment, sign in
-
I stopped chasing correct answers in JavaScript today… and started chasing why I was wrong. 👇 --- 💥 Mistakes that taught me more than tutorials: ❌ Thought "onclick" supports multiple handlers 👉 It overrides—use "addEventListener" instead ❌ Confused arrow function "this" 👉 Arrow functions don’t have their own "this" ❌ Expected "var" to behave like "let" 👉 Faced hoisting and scope differences ❌ Assumed async code runs in order 👉 Learned: microtasks run before macrotasks ❌ Misunderstood "await" 👉 It pauses execution and resumes via the microtask queue ❌ Ignored shallow copy behavior 👉 Spread operator copies references, not nested objects --- 💡 Big shift: I wasn’t stuck because JavaScript is hard… I was stuck because I wasn’t questioning why. --- 🎯 What changed: ✔ I analyze outputs instead of guessing ✔ I understand how JS behaves under the hood ✔ I debug with clarity, not confusion --- 📌 Lesson: Mistakes in coding aren’t failures. They’re proof that your understanding is evolving. --- 🚀 Next focus: Closures + real-world problem solving --- If you're learning JavaScript: 👉 Which concept confused you the most? 👉 And what finally made it click? Let’s learn together 👇 #JavaScript #LearningInPublic #Frontend #CodingJourney #Debugging
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 9 Functions are powerful… But JavaScript gives you even better ways to write them. 😎 Today let’s understand 3 important concepts that make your code clean, modern, and powerful: 👉 Arrow Functions 👉 Default Parameters 👉 Rest Parameters 🔹 1. Arrow Functions (Short & Clean) Earlier we used to write functions like this: function add(a, b) { return a + b } Now with arrow functions, we can write it in a cleaner way: const add = (a, b) => a + b 👉 Same result, less code 📌 Arrow functions make code short and readable 🔹 2. Default Parameters (No more undefined) Sometimes users don’t pass values 😵 function greet(name) { console.log("Hello " + name) } greet() 👉 Output: Hello undefined ❌ Solution → Default Parameters function greet(name = "Guest") { console.log("Hello " + name) } greet() 👉 Output: Hello Guest ✅ 📌 Default values prevent errors and make code safe 🔹 3. Rest Parameters (Handle multiple inputs) What if you don’t know how many inputs will come? 🤔 That’s where rest parameters come in. function sum(...numbers) { let total = 0 for (let num of numbers) { total += num } return total } console.log(sum(1, 2, 3, 4)) 👉 Output: 10 📌 ...numbers collects all values into an array 🔥 Simple Summary Arrow Function → short syntax Default Parameters → fallback values Rest Parameters → multiple inputs handle 💡 Programming Rule Write less code. Write clean code. Write smart code. If you want to learn JavaScript in a simple and practical way, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Arrays (Next Post) Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
🚀 Day 5 / 100 — JavaScript Concepts That Every Developer Should Understand #100DaysOfCode Today I revised two very important JavaScript concepts that often come up in interviews and real-world debugging: 🔐 1. Closures A closure happens when a function remembers variables from its outer scope even after the outer function has finished executing. In simple words: A function carries its environment with it. Example: function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 Why this works: Even though outer() has finished running, inner() still remembers the variable count. 📌 Common use cases • Data privacy • Function factories • React hooks • Event handlers 🧠 2. Call Stack The call stack is how JavaScript keeps track of function execution. It works like a stack (Last In, First Out). Whenever a function runs: 1️⃣ It gets pushed onto the stack 2️⃣ When it finishes, it gets popped off Example: function one() { two(); } function two() { three(); } function three() { console.log("Hello from the call stack"); } one(); Execution order in the call stack: Call Stack three() two() one() global() Then it unwinds after execution. 📌 Understanding the call stack helps with: • Debugging errors • Understanding recursion • Avoiding stack overflow 💡 Key realization today: JavaScript is single-threaded, and concepts like closures + call stack explain a lot about how the language actually works behind the scenes. Mastering these fundamentals makes async JS, promises, and the event loop much easier later. 🔥 Day 5 completed. 95 days to go. If you're also learning to code, comment “100” and let’s stay consistent together 🤝 #javascript #100daysofcode #webdevelopment #coding #developers #programming #learninpublic #buildinpublic #SheryiansCodingSchool #Sheryians
To view or add a comment, sign in
-
-
🚀 Day 14/100 – Arrays in JavaScript = Small Methods, Big Power! Today I went back to basics and realized something powerful 👇 👉 Mastering array methods = writing cleaner, smarter code. Here’s a quick breakdown of what I revised 👇 💡 Transform & Create split() → turns a string into an array "hello world".split(" ") // ["hello", "world"] 💡 Add Elements push() → add at the end unshift() → add at the beginning let arr = [2,3]; arr.push(4); // [2,3,4] arr.unshift(1); // [1,2,3,4] 💡 Remove Elements pop() → removes last element arr.pop(); // [1,2,3] 💡 Find & Check indexOf() → find position [10,20,30].indexOf(20) // 1 💡 Rearrange reverse() → flips the array [1,2,3].reverse() // [3,2,1] 💡 Convert toString() → array → string join() → array → custom string [1,2,3].join("-") // "1-2-3" ✨ Big Realization: These aren’t just “methods”… they’re tools to think better in code. The more I practice, the more patterns I start seeing 🔁 📈 Consistency > Intensity Day by day, getting sharper. #100DaysOfCode #JavaScript #CodingJourney #LearnInPublic #WebDevelopment #LearningInPublic Sheryians Coding School Sheryians Coding School Community
To view or add a comment, sign in
-
-
🚀 JavaScript Fundamentals: Beyond the Basics Ever shipped a bug that was just == vs ===? Or "copied" an object... only to watch the original mutate anyway? These aren't beginner mistakes — they're traps that catch experienced devs too. Mastering JS core mechanics isn't about interviews. It's about writing predictable, production-ready code. Here are the 4 pillars worth revisiting: 🔵 Null vs. Undefined null = intentional absence. You put it there. undefined = JS saying "nothing was ever assigned here." Same result. Very different meaning. ⚖️ == vs. === == tries to be helpful by converting types first. === doesn't. It checks value and type — no surprises. Default to ===. Always. 🔄 Type Coercion JS will silently convert types behind the scenes. The + operator is the sneakiest of all — it both adds and concatenates depending on context. Know the rules before they bite you. 📦 Deep vs. Shallow Copy { ...spread } only copies the top level. Nested objects? Still pointing to the same reference. structuredClone() is your modern, built-in answer to true deep copying. These four concepts will save you hours of debugging and make your logic significantly more robust. Which one tripped you up the most when you were learning? Drop it below 👇 #JavaScript #WebDevelopment #Frontend #CodingTips #SoftwareEngineering #Programming #InterviewPrep
To view or add a comment, sign in
-
-
𝗟𝗲𝘅𝗶𝗰𝗮𝗹 𝗘𝗻𝘃𝗶𝗿𝗼𝗻𝗺𝗲𝗻𝘁 & 𝗦𝗰𝗼𝗽𝗲 𝗖𝗵𝗮𝗶𝗻 Recently, I focused on one of the most important yet underrated concepts in JavaScript — the Lexical Environment. Most developers learn syntax, but the real power comes when you understand how JavaScript manages memory and variable access internally. 𝗪𝗵𝘆 𝗟𝗲𝘅𝗶𝗰𝗮𝗹 𝗘𝗻𝘃𝗶𝗿𝗼𝗻𝗺𝗲𝗻𝘁 𝗠𝗮𝘁𝘁𝗲𝗿𝘀 Every time JavaScript runs a function, it creates something called a Lexical Environment. It consists of: • Local Memory (Environment Record) → stores variables & functions • Reference to Parent (Outer Environment) → connects to its parent scope This structure is what allows JavaScript to resolve variables correctly. 𝗪𝗵𝗮𝘁 𝗜 𝗟𝗲𝗮𝗿𝗻𝗲𝗱 • Lexical Environment = Local + Parent Link Not just variables, but also a pointer to its parent scope This parent link is what builds the scope chain • Scope Chain = Chain of Lexical Environments If a variable is not found locally → JS searches in parent → then global This lookup mechanism is automatic and fundamental • Lexical Scope is Fixed Defined at the time of writing code, not during execution This is why inner functions can access outer variables 𝗣𝗼𝘄𝗲𝗿𝗳𝘂𝗹 𝗘𝘅𝗮𝗺𝗽𝗹𝗲𝘀 • Accessing global variable inside function works because of parent reference • Nested functions can access variables from outer functions • Variables declared inside a function are not accessible outside 𝗗𝗲𝗲𝗽 𝗜𝗻𝘀𝗶𝗴𝗵𝘁 🤫 • Closures are formed because functions remember their lexical environment • Even after execution, the lexical environment can persist (closure memory) • var, let, const differ in how they behave inside lexical environments • Each execution context = new lexical environment → avoids variable conflicts 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆 The Lexical Environment is the backbone of JavaScript execution. If you understand this, concepts like closures, scope chain, and hoisting become crystal clear. You stop guessing outputs — and start predicting them with confidence. #JavaScript #LexicalEnvironment #ScopeChain #JSInternals #ExecutionContext #JavaScriptScope #WebDevelopment #FrontendDevelopment #Programming #Coding #Developers #SoftwareEngineering #TechSkills #CodingInterview #DeveloperJourney #LearnInPublic #CodingJourney #KeepLearning
To view or add a comment, sign in
-
🚀 JavaScript Operators Are Not As Simple As They Look When we start learning JavaScript, operators seem very basic. +, -, =, >, && — just a few symbols, right? But when I started exploring them deeply, I found some mind-bending behaviors. For example: "5" + 2 → "52" "5" - 2 → 3 true + true → 2 Why does this happen? Because JavaScript has concepts like: • Type coercion • Operator precedence • Logical short-circuiting • Different categories of operators (binary, unary, ternary) Once you understand these concepts, you start seeing how JavaScript actually evaluates expressions behind the scenes. So I wrote a blog explaining JavaScript operators in depth, including: ✅ Arithmetic operators ✅ Assignment operators ✅ Comparison operators ✅ Logical operators ✅ Operator precedence ✅ Some surprising JavaScript behaviors If you're learning JavaScript or want to strengthen your fundamentals, this blog might help. 🔗 Read it here: https://lnkd.in/gc5--7hA 📌 What’s next? In the next blog, I’ll explore decision making in JavaScript by covering: • if • else • else if • switch and how these control the flow of your programs. #JavaScript #WebDevelopment #Programming #Coding #LearningInPublic #100DaysOfCode
To view or add a comment, sign in
-
-
I recently started diving deeper into JavaScript, and honestly… one concept completely changed how I see code execution 🤯 At first, I used to just write code and expect it to “run.” But then I discovered what actually happens behind the scenes 👇 JavaScript doesn’t just execute code directly. It goes through a process: 🔹 First, it creates a Global Execution Context 🔹 Then comes the Memory Phase (where variables get stored as undefined and functions are fully saved) 🔹 After that, the Execution Phase runs code line by line 🔹 And everything is managed using a Call Stack (LIFO — Last In, First Out) Understanding this made things like hoisting, function calls, and even bugs feel way less random. Now when I write code, I don’t just see syntax — I can actually visualize what the JavaScript engine is doing step by step 🧠⚡ Still learning, but this was one of those “aha” moments that made everything clearer. If you're learning JavaScript, don’t skip this part — it’s a game changer 🚀 #JavaScript #WebDevelopment #LearningJourney #Frontend #Programming #Developers
To view or add a comment, sign in
-
-
🚀 Day 7/100 of #100DaysOfCode Today was all about strengthening JavaScript fundamentals — revisiting concepts that seem simple but are often misunderstood. 🔁 map() vs forEach() Both are used to iterate over arrays, but they serve different purposes: 👉 map() Returns a new array Used when you want to transform data Does not modify the original array Example: const doubled = arr.map(num => num * 2); 👉 forEach() Does not return anything (undefined) Used for executing side effects (logging, updating values, etc.) Often modifies existing data or performs actions Example: arr.forEach(num => console.log(num)); ⚔️ Key Difference: Use map() when you need a new transformed array Use forEach() when you just want to loop and perform actions ⚖️ == vs === (Equality in JS) 👉 == (Loose Equality) Compares values after type conversion Can lead to unexpected results Example: '5' == 5 // true 😬 👉 === (Strict Equality) Compares value AND type No type coercion → safer and predictable Example: '5' === 5 // false ✅ 💡 Takeaway: Small concepts like these make a big difference in writing clean, bug-free code. Mastering the basics is what separates good developers from great ones. 🔥 Consistency > Intensity On to Day 8! #JavaScript #WebDevelopment #CodingJourney #LearnInPublic #Developers #100DaysOfCode #SheryiansCodingSchool #Sheryians
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
JavaScript is somewhat different from other programming languages, i was also surprised when i knew array will hold any type of values as in other languages we can only store same type of data and also when we try to sort the numbers in array, it gives priority to the first digit it encountered and doesn't take the other digit into consideration until and unless the first digit is same, but still it checks whether the current digit is small compared to other number's digit or not, Which gives the results in wrong way, to sort them in correct order we need to use compare function. Without a compare function, numbers are sorted as strings, which gives wrong results.