Wrote a complete guide on JavaScript Array Methods 📊 The 6 methods every JavaScript developer reaches for daily — explained simply with real examples. Stop writing clunky for loops for everything. Here's what's covered: → push() & pop() — add and remove from the end → shift() & unshift() — add and remove from the front → map() — transform every item, get a new array back → filter() — keep only items that pass a test → reduce() — collapse an entire array to one value → forEach() — loop without needing a result Plus: ✔ Before/after array state for every method ✔ Flowcharts showing exactly how map() and filter() work ✔ for loop vs map/filter side-by-side comparison ✔ A complete shopping cart example using all of them together The one comparison that made it click for me: map() = transform every item filter() = keep some items reduce() = squash everything into one thing forEach() = just do something, don't need a result Link : https://lnkd.in/gs4NGWWj chechout the hashnode profile : https://lnkd.in/gAwxuryw #JavaScript #WebDevelopment #LearnToCode #Frontend #ArrayMethods #chaicode #hiteshchoudhary #piyushgargh
JavaScript Array Methods: A Complete Guide
More Relevant Posts
-
🔍 JavaScript Bug You Might Have Seen (typeof null === "object") You write this: console.log(typeof null); // ? What do you expect? 👉 "null" But you get: 👉 "object" 🤯 Wait… null is NOT an object… So why is JavaScript saying this? This happens because of a historical bug in JavaScript 📌 What’s going on? In the early days of JavaScript: 👉 Values were stored in a low-level format 👉 Objects were identified by a specific type tag Unfortunately… 👉 null was given the same tag as objects So: typeof null === "object" 📌 Important point: 👉 This is NOT correct behavior 👉 But it was never fixed (for backward compatibility) 📌 So how do you check for null? ❌ Don’t do this: typeof value === "null" ✔ Do this instead: value === null 💡 Takeaway: ✔ typeof null returns "object" (bug) ✔ It’s a legacy behavior in JavaScript ✔ Always check null using === null 👉 Not everything in JavaScript makes sense… some things just stayed for history 😄 🔁 Save this before it confuses you again 💬 Comment “null” if this surprised you ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🔍 JavaScript Quirk: Hoisting (var vs let vs const) JavaScript be like: 👉 “I know your variables… before you even write them” 😅 Let’s see the magic 👇 console.log(a); var a = 10; 💥 Output: undefined Wait… no error? 🤯 Why? Because `var` is **hoisted** 📌 What is Hoisting? Hoisting is JavaScript’s behavior of **moving variable and function declarations to the top of their scope before execution**. 👉 JS internally does this: var a; console.log(a); // undefined a = 10; So the variable exists… but has no value yet. Now try with `let` 👇 console.log(b); let b = 20; 💥 Output: ReferenceError ❌ Same with `const` 👇 console.log(c); const c = 30; 💥 Error again ❌ Why? Because `let` & `const` are also hoisted… BUT they live in something called: 👉 “Temporal Dead Zone” (TDZ) Translation: 🧠 “You can’t touch it before it’s declared” --- 💡 Simple Breakdown: ✔ `var` → hoisted + initialized as `undefined` ✔ `let` → hoisted but NOT initialized ✔ `const` → same as let (but must assign value) 💀 Real dev pain: Using `var`: 👉 “Why is this undefined?” Using `let`: 👉 “Why is this error?” JavaScript: 👉 “Figure it out yourself” 😎 💡 Takeaway: ✔ Avoid `var` (legacy behavior) ✔ Prefer `let` & `const` ✔ Understand hoisting = fewer bugs 👉 JS is not weird… You just need to know its secrets 😉 🔁 Save this before hoisting confuses you again 💬 Comment “TDZ” if this finally made sense ❤️ Like for more JS quirks #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🤯 One of the most confusing concepts in JavaScript — 'this' keyword If you've worked with JavaScript, you’ve probably asked: 👉 “What exactly does ‘this’ refer to?” Here’s the simple rule: 👉 “this = Who called me?” Let’s understand with examples 👇 📌 1. Object Method const user = { name: "Vinay", greet() { console.log(this.name); } }; user.greet(); // Vinay 👉 Here, 'this' refers to the user object 📌 2. Normal Function function show() { console.log(this); } show(); // window (in browser) 👉 Here, 'this' refers to the global object 📌 3. Arrow Function const obj = { name: "Vinay", greet: () => { console.log(this.name); } }; obj.greet(); // undefined 👉 Arrow functions don’t have their own 'this' 👉 They inherit it from the parent scope 📌 4. Event Listener button.addEventListener("click", function () { console.log(this); }); 👉 Here, 'this' refers to the clicked element 💥 Final Tip: 👉 “'this' is not about where it’s written, it’s about how it’s called.” Master this concept, and your JavaScript skills will level up 🚀 #JavaScript #WebDevelopment #Coding #DeveloperLife #Frontend #Programming #JSConcepts
To view or add a comment, sign in
-
-
Hoisting in JavaScript (and TypeScript) - Explained So You’ll Never Forget Ever saw this weird behavior? console.log(a); // undefined var a = 10; OR even worse: sayHello(); // Works! function sayHello() { console.log("Hello!"); } How is JavaScript using things before they are declared? 👉 That’s called Hoisting 🏠 Real-Life Example: Hotel Reception Imagine you walk into a hotel… "var" — Pre-registered Guest 📝 Your name is already in the system, but your room is not ready yet. 👉 You exist… but not fully ready 👉 So you get "undefined" "let" / "const" — Walk-in Guest 🚶♂️ You are NOT in the system yet. 👉 Try to access before check-in? ❌ “Sir, you are not registered!” (This is called Temporal Dead Zone) "function" — VIP Guest ⭐ Your room is already booked and ready! 👉 You can directly go in 👉 That’s why functions work before declaration Behind the scenes (Simple terms): JavaScript does 2 steps: 1️⃣ Memory Allocation Phase → Variables & functions are stored 2️⃣ Execution Phase → Code runs line by line Key Takeaways: ✔ "var" is hoisted (initialized as "undefined") ✔ "let" & "const" are hoisted but NOT initialized ✔ Functions are fully hoisted Pro Tip: Avoid confusion → Always declare variables at the top (or just use "let" / "const" properly) 💬 Have you ever faced a bug because of hoisting? #JavaScript #TypeScript #WebDevelopment #Frontend #Coding #LearnToCode
To view or add a comment, sign in
-
-
🚀 Understanding the JavaScript Event Loop (In Simple Terms) If you’ve ever wondered how JavaScript handles multiple tasks at once, the answer lies in the Event Loop. 👉 JavaScript is single-threaded, meaning it can execute one task at a time. 👉 But with the help of the Event Loop, it can handle asynchronous operations efficiently. 🔹 How it works: 1. Call Stack – Executes synchronous code (one task at a time) 2. Web APIs – Handles async operations like setTimeout, API calls, DOM events 3. Callback Queue – Stores callbacks from async tasks 4. Event Loop – Moves tasks from the queue to the call stack when it’s empty 🔹 Microtasks vs Macrotasks: - Microtasks (Promises, MutationObserver) → Executed first - Macrotasks (setTimeout, setInterval, I/O) → Executed later 💡 Execution Order Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); 👉 Output: Start End Promise Timeout 🔥 Key Takeaways: ✔ JavaScript doesn’t run tasks in parallel, but it handles async smartly ✔ Microtasks always run before macrotasks ✔ Event Loop ensures non-blocking behavior Understanding this concept is a game-changer for writing efficient and bug-free JavaScript code 💻 #JavaScript #FrontendDevelopment #WebDevelopment #ReactJS #Programming #EventLoop
To view or add a comment, sign in
-
-
🚀 JavaScript String Optimization You Probably Didn’t Know When you build strings in a loop like this: let bigString = ""; for (let i = 0; i < 1000; i++) { bigString += "chunk" + i; } It looks expensive… but surprisingly, it’s not (at first). 👉 JavaScript engines are smart. Instead of immediately creating a new string every time, they use something called a ConsString (concatenated string) — a lazy structure that avoids copying data. ⚡ This means: String building stays fast and memory-efficient No actual concatenation happens yet But here’s the catch… 💥 The moment you try to access the string (like bigString[0]), JavaScript materializes it — flattening everything into a real string, which can be expensive. 📌 Key Insight: Building strings → cheap Accessing/manipulating them → can trigger hidden cost 💡 Takeaway: Performance isn’t just about what you write — it’s about when the engine does the heavy work. #JavaScript #WebPerformance #CleanCode #Programming #FrontendDevelopment #DevTips #reactjs #webdevelopment
To view or add a comment, sign in
-
-
🚀 JavaScript Object Cheat Sheet Every Developer Should Know Objects are the heart of JavaScript. Almost everything in JavaScript revolves around objects, properties, and methods. If you master objects, you automatically level up your JavaScript skills. Here’s a quick JavaScript Object Cheatsheet to remember the most useful patterns: 🔹 Object Declaration const user = { name: "Profile", followers: 4817 } 🔹 Access Properties user.name // dot notation user["name"] // bracket notation 🔹 Delete Property delete user.name 🔹 Iterate Objects for (const key in user) { console.log(key, user[key]) } 🔹 Copy Object const copy = {...user} // shallow copy const deepCopy = structuredClone(user) // deep copy 🔹 Freeze Object Object.freeze(user) 🔹 Destructuring const { name, followers } = user 🔹 Getter & Setter const user = { name: "Profile", get profile(){ return this.name } } 💡 Pro Tip: Using destructuring, spread operator, and Object.freeze() properly makes your JavaScript code cleaner and safer. 📌 Save this cheat sheet so you can quickly review JavaScript objects anytime. If this helped you: 👍 Like 💬 Comment your favorite JavaScript feature 🔁 Share with a developer friend Follow for more JavaScript Cheat Sheets & Developer Tips 🔗 LinkedIn: mdyousufali205 #javascript #webdevelopment #programming #coding #frontend #softwareengineering #developers #javascriptdeveloper #codingtips #devcommunity #learnprogramming #100DaysOfCode #webdev
To view or add a comment, sign in
-
-
🔍 JavaScript Bug You Might Have Seen (setTimeout vs Promise) You write this code: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); What do you expect? Start Timeout Promise End But actual output is: Start End Promise Timeout This happens because of the Event Loop 📌 What is the Event Loop? 👉 The event loop is the mechanism that decides which task runs next in JavaScript’s asynchronous execution. 📌 Priority order (very important): 1️⃣ Call Stack (synchronous code) 2️⃣ Microtask Queue 3️⃣ Macrotask Queue 📌 What’s inside each queue? 👉 Microtask Queue (HIGH priority): ✔ Promise.then / catch / finally ✔ queueMicrotask ✔ MutationObserver 👉 Macrotask Queue (LOWER priority): ✔ setTimeout ✔ setInterval ✔ setImmediate ✔ I/O tasks ✔ UI rendering events Execution flow: ✔ Step 1: Run all synchronous code 👉 Start → End ✔ Step 2: Execute ALL microtasks 👉 Promise ✔ Step 3: Execute macrotasks 👉 setTimeout So final order becomes: Start End Promise Timeout 💡 Takeaway: ✔ Microtasks run before macrotasks ✔ Promises > setTimeout ✔ setTimeout(fn, 0) is NOT immediate 👉 Understand queues = master async JS 🔁 Save this for later 💬 Comment “event loop” if this made sense ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
Most JavaScript developers use async/await every day without actually understanding what runs it. The Event Loop is that thing. I spent two years writing JavaScript before I truly understood how the Event Loop worked. Once I did, bugs that used to take me hours to debug started making complete sense in minutes. Here is what you actually need to know: 1. JavaScript is single-threaded but not blocking The Event Loop is what makes async behavior possible without multiple threads. 2. The Call Stack runs your synchronous code first, always Anything async waits in the queue until the stack is completely empty. 3. Microtasks run before Macrotasks Promise callbacks (.then) execute before setTimeout, even if the timer is zero. This catches a lot of developers off guard. 4. Understanding this helps you write better async code You stop writing setTimeout hacks and start understanding why certain code runs out of order. 5. It explains why heavy computations block the UI A long synchronous task freezes the browser because nothing else can run until the stack clears. The mindset shift: JavaScript is not magic. It follows a very specific execution order and once you see it clearly, you write code that actually behaves the way you expect. 🧠 The Event Loop is one of those concepts that separates developers who guess from developers who know. When did the Event Loop finally click for you? 👇 If this helped, I would love to hear your experience. #JavaScript #WebDevelopment #EventLoop #Frontend #SoftwareEngineering
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