💡 JavaScript Tip: The Magical length Property of Arrays 😎 Most developers know that array.length gives the number of elements… But do you know how powerful (and tricky) it actually is? Let’s explore 👇 --- 🔹 1. Length is not read-only const arr = [1, 2, 3, 4]; arr.length = 2; console.log(arr); // [1, 2] 👉 Setting length truncates the array! All elements beyond the new length are removed. --- 🔹 2. You can also extend the array const arr = [1, 2]; arr.length = 5; console.log(arr); // [1, 2, <3 empty items>] 👉 Empty slots are created (they’re not undefined, they’re missing). --- 🔹 3. Length doesn’t always mean “last index + 1” const arr = []; arr[5] = 42; console.log(arr.length); // 6 👉 Sparse arrays have holes — indexes 0 to 4 don’t exist, but length still counts the last index + 1. --- 🔹 4. Deleting items doesn’t reduce length const arr = [10, 20, 30]; delete arr[1]; console.log(arr.length); // 3 console.log(arr); // [10, <1 empty item>, 30] 👉 The hole remains — length ignores deletions! --- ⚡ Quick Recap: Operation Effect on length push() / unshift() Increases pop() / shift() Decreases delete arr[i] No change arr.length = n Trims or extends --- 💭 Takeaway: length is not just a property — it’s a controller of your array’s shape and size. Handle it carefully to avoid silent bugs! --- #JavaScript #WebDevelopment #Frontend #CodingTips #JSArrays
"JavaScript Tip: The Power of Array.length"
More Relevant Posts
-
🔗 JavaScript Polyfill for bind() — Deep Dive Ever wondered how bind() actually works under the hood? Let’s build our own polyfill for Function.prototype.bind() 👇 💡 What does bind() do? It returns a new function with a permanently bound this value (and optional preset arguments). --- 🧠 Native Example const person = { name: 'Prince' }; function greet(greeting) { console.log(`${greeting}, ${this.name}!`); } const sayHello = greet.bind(person, 'Hello'); sayHello(); // Hello, Prince! --- 🧩 Polyfill Implementation if (!Function.prototype.myBind) { Function.prototype.myBind = function (context, ...args1) { if (typeof this !== 'function') { throw new TypeError('Bind must be called on a function'); } const fn = this; return function (...args2) { return fn.apply(context, [...args1, ...args2]); }; }; } ✅ Works like bind() — preserves this and supports partial arguments! --- ⚙️ Example Usage const user = { name: 'Prince' }; function sayHi(time) { console.log(`Hi ${this.name}, good ${time}!`); } const morningGreet = sayHi.myBind(user, 'morning'); morningGreet(); // Hi Prince, good morning! --- 🚀 Key Takeaways bind() returns a new function, doesn’t call immediately. Helps fix this context in callbacks and event handlers. Polyfilling boosts your understanding of function internals. --- #JavaScript #WebDevelopment #Frontend #Coding #LearnInPublic #Polyfill #JSDeepDive #100DaysOfCode
To view or add a comment, sign in
-
💥 JavaScript gotcha of the day: When you think you filled your array with different objects… but JavaScript had other plans 😅 const arr = Array(3).fill({}); // [{}, {}, {}] arr[0].hi = "hi"; console.log(arr); O/p// → [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }] You expected: [{ hi: "hi" }, {}, {}] but you got copy-paste chaos 🤯 🧠 Why? .fill({}) doesn’t create new objects — it fills the array with the same reference in memory. So arr[0].hi = "hi" updates all of them, because they’re all pointing to the same object! 🛠 Fix it: Use map() or Array.from() to create unique objects 👇 // ✅ distinct objects const arr = Array(3).fill().map(() => ({})); (or) const arr = Array.from({ length: 3 }, () => ({})); Now: arr[0].hi = "hi"; console.log(arr); // [{ hi: "hi" }, {}, {}] #JavaScript #CodingGotchas #WebDevelopment #Frontend #LearningEveryday #JSFun
To view or add a comment, sign in
-
-
You think you know React... until you have to clean up a third-party script. I had a major "Aha!" moment building my Financial dashboard project, and it's a perfect example of how React's declarative world meets imperative, real-world JavaScript. The Problem: I'm integrating TradingView's embeddable widgets, which aren't React components. This requires manually creating <script> tags and injecting them into a div using a useEffect hook. The Naive Approach: Just create the script in useEffect and let React unmount the div when it's done. Simple, right? Wrong. This creates massive memory leaks. The third-party script (the "tenant") running inside my div (the "house") has its own background processes: setIntervals, WebSockets, and global event listeners. When React unmounts the div (demolishes the house), it doesn't tell the tenant to clean up. The "ghost" tenant lives on, still fetching data and consuming memory. The Solution & The "Aha!" Moments: 1. The "Stale Ref" Problem: My first attempt at a cleanup function failed because ref.current is null when the cleanup runs! The Fix: You have to snapshot the ref's value inside the effect: const node = ref.current;. The cleanup function's closure then remembers this node, even after ref.current is nullified. 2. The "Tenant Eviction" Model: This was the real lightbulb moment. Why clean the div with node.innerHTML = "" if React is removing it anyway? The Fix: The cleanup is not for React. It's a signal for the third-party script. Setting innerHTML = "" is like "evicting the tenant." The script is built to detect this, triggering its own internal destroy() logic—clearing its timers, closing its connections, and actually preventing the memory leak. Takeaway: React manages its own lifecycle, but we are 100% responsible for the lifecycle of any imperative, non-React code we introduce. This dive was a powerful lesson in JavaScript closures, React's lifecycle, and robust memory management. #reactjs #javascript #webdevelopment #frontend #MERNstack #reacthooks #memorymanagement #learning #coding
To view or add a comment, sign in
-
-
💡 Have you ever wondered why these two JavaScript loops behave differently? for (let i = 0; i < 10; i++) { setTimeout(() => console.log(i), 0); } for (var i = 0; i < 10; i++) { setTimeout(() => console.log(i), 0); } It’s because of the default behavior of how let and var work in JavaScript. If you’re familiar with JavaScript, you may know that let is block-scoped, while var is function/global-scoped. In the case of let, since it’s block-scoped, it creates a new variable i and assigns a value to it during each iteration. So, each i points to a different memory location — kind of like a house with multiple rooms, and each room contains its own variable called i. That’s why it logs 0 to 9 after the wait is over. But in the case of var, since it’s function/global-scoped, the variable is created only once and points to the same memory location. So it logs 10 ten times. It’s similar to writing: var i; for (i = 0; i < 10; i++) { setTimeout(() => console.log(i), 0); } #Javascript #Frontend
To view or add a comment, sign in
-
🧩 How Closures Actually Work In JavaScript, a closure happens when an inner function “remembers” and has access to variables from its outer function, even after that outer function has returned. It’s like a memory capsule that keeps certain data alive beyond its normal lifetime. Closures aren’t something you “create” manually — they naturally form whenever you define a function inside another function. Here’s a simple example: function counter() { let count = 0; return function() { count++; console.log(count); }; } const increment = counter(); increment(); // 1 increment(); // 2 increment(); // 3 Even though counter() has finished executing, the inner function still remembers the variable count. That’s closure in action — the variable lives on because it’s referenced inside the returned function. Closures are the reason why we can build private variables, maintain state, and create modular, reusable logic. They power features like function factories, event handlers, and many design patterns used in frameworks like React and Node.js. Once you grasp closures, you unlock a deeper understanding of how JS manages scope and memory — and you start writing smarter, cleaner code. So the next time someone says “functions in JavaScript are first-class citizens,” remember: closures are what make that statement come alive. #JavaScript #Closures #WebDevelopment #MERNStack #NodeJS #ReactJS #Frontend #CodingCommunity #LearnInPublic #100DaysOfCode #DevCommunity
To view or add a comment, sign in
-
🧠 Why does let create a new closure in every loop iteration in JavaScript? Ever wondered why this works perfectly 👇 for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } // Output: 0, 1, 2 …but this doesn’t 👇 for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } // Output: 3, 3, 3 That’s not “compiler magic” — it’s actually defined in the ECMAScript specification itself. 📜 --- 📘 ECMA Definition From ECMA-262 §13.7.4.8 – Runtime Semantics: ForBodyEvaluation: > If the loop variable is declared with let or const, a new LexicalEnvironment is created for each iteration. The variable is copied (rebound) from the previous environment and used to evaluate the loop body in this new environment. --- 🔍 What This Means Every time the loop runs: JavaScript creates a new environment record (a fresh closure). The loop variable (i) is independent for that iteration. Each callback “remembers” its own copy of i. So effectively: var → single shared binding across all iterations. let / const → new closure per iteration. --- ✅ In short: let is not just about block scoping — it’s about creating predictable closures inside loops by design. #JavaScript #ECMAScript #Closures #Frontend #WebDevelopment #CodingTips #LearnInPublic
To view or add a comment, sign in
-
⚛️ That moment when I just wanted to access an element... and React said “NO re-rendering allowed!” 😂 I was building a simple input box and needed to focus it when a button was clicked. Naturally, I thought: “Easy! I’ll use useState().” So I did something like this 👇 ❌ Before: function InputFocus() { const [input, setInput] = useState(null); const handleClick = () => { input.focus(); }; return ( <> <input ref={setInput} /> <button onClick={handleClick}>Focus</button> </> ); } And then React said: “Wait... you’re updating state just to get a DOM element?” 😩 That’s when I discovered useRef() — my quiet, reliable hook friend that doesn’t trigger re-renders. 🧘♂️ ✅ After using useRef(): function InputFocus() { const inputRef = useRef(null); const handleClick = () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef} /> <button onClick={handleClick}>Focus</button> </> ); } 💡 Lesson learned: useRef() stores a mutable value that survives re-renders. Perfect for accessing DOM elements or saving values without causing updates. No unnecessary renders. No chaos. Just pure focus. 🎯 React hooks each have their own “superpower” — and useRef() is the stealthy one! 🦸♀️ #ReactJS #useRef #ReactHooks #FrontendDeveloper #MERNStack #WebDevelopment #LearningByDoing #JavaScript #ReactTips #CodingJourney
To view or add a comment, sign in
-
🔥 React Tip: Stop Using useEffect for Derived State🔥 Many developers reach for useEffect when they want to compute values based on props or state. This creates unnecessary re-renders and bugs. ❌ Don't do this: function Cart({ items }) { const [total, setTotal] = useState(0); useEffect(() => { setTotal(items.reduce((sum, item) => sum + item.price, 0)); }, [items]); return <div>Total: ${total}</div>; } ✅ Do this instead: function Cart({ items }) { const total = items.reduce((sum, item) => sum + item.price, 0); return <div>Total: ${total}</div>; } Why? → Eliminates an entire render cycle → No synchronization bugs → Simpler mental model → Better performance To improve performance, use memoization: function Cart({ items }) { const total = useMemo( () => items.reduce((sum, item) => sum + item.price, 0), [items] ); return <div>Total: ${total}</div>; } 💡 Rule of thumb: If you can calculate it during render, don't use useEffect to sync it into state. 𝗣𝗦: 𝗗𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗰𝗵𝗲𝗰𝗸 𝗼𝘂𝘁 𝘁𝗵𝗲 𝗺𝗮𝘀𝘀𝗶𝘃𝗲 𝗼𝗳𝗳𝗲𝗿 𝗼𝗳 𝟵𝟯% 𝗱𝗶𝘀𝗰𝗼𝘂𝗻𝘁 𝗼𝗻 𝘁𝗵𝗲 𝗣𝗿𝗼 / 𝗟𝗶𝗳𝗲𝘁𝗶𝗺𝗲 𝗦𝘂𝗯𝘀𝗰𝗿𝗶𝗽𝘁𝗶𝗼𝗻. 𝗟𝗶𝗻𝗸 𝗶𝗻 𝘁𝗵𝗲 𝗰𝗼𝗺𝗺𝗲𝗻𝘁 𝗮𝗻𝗱 𝗶𝗻 𝘁𝗵𝗲 𝗳𝗲𝗮𝘁𝘂𝗿𝗲𝗱 𝘀𝗲𝗰𝘁𝗶𝗼𝗻 𝗼𝗳 𝗺𝘆 𝗟𝗶𝗻𝗸𝗲𝗱𝗜𝗻 𝗽𝗿𝗼𝗳𝗶𝗹𝗲. #javascript #reactjs #nextjs #webdevelopment
To view or add a comment, sign in
-
-
💡 var, let, and const — The Three Musketeers of JavaScript ⚔️ If you’ve ever felt confused about when to use var, let, or const… you’re not alone. Even JavaScript sometimes forgets 😅 Let’s break it down like friends who share the same coffee machine ☕👇 ⸻ 🧓 var — The Old Guy from 1995 “I’ve seen things… global scope, function scope… chaos.” var name = "John"; if (true) { var name = "Doe"; console.log(name); // Doe } console.log(name); // Doe 😬 🧠 var doesn’t care about blocks. It’s function-scoped, gets hoisted, and often causes unexpected overwrites. 👉 Use only if you’re writing code for Internet Explorer 6 (please don’t 😂). ⸻ 🧑💻 let — The Responsible Adult “I respect boundaries.” let fruit = "Apple"; if (true) { let fruit = "Mango"; console.log(fruit); // Mango } console.log(fruit); // Apple ✅ 🧠 let is block-scoped and doesn’t get initialized until it’s declared. Perfect for values that will change later. ⸻ 🧘♀️ const — The Calm Monk “Once decided, I never change.” const pi = 3.14; // pi = 3.14159 ❌ Error 🧠 const is also block-scoped, but you can’t reassign it. (However, you can still mutate objects 👇) const person = { name: "John" }; person.name = "Doe"; // ✅ Allowed ⸻ 💬 My rule of thumb: 🧠 Use const by default → switch to let when you have to change it → forget var exists. ⸻ ✨ What’s your most funny or painful var moment? Drop it below 👇 #JavaScript #WebDevelopment #Frontend #CodingHumor #ReactJS
To view or add a comment, sign in
-
-
🤔 🚨 Ever seen [object Object] in your alert or log? 📌 Alert boxes can only show strings. When you pass an object like 👉 alert({name: 'Jane'}), the object gets converted to a string via toString(). Since no custom toString() is defined, it outputs [object Object]. 📌 Console log’s smarter display It usually shows an interactive object you can inspect in developer tools. But if you do : 👉 console.log("User: " + obj), it coerces obj to a string calling toString() and showing [object Object]. 📌 In short: [object Object] means JavaScript is using the default object-to-string conversion that’s not meant to show you the object’s details. #javascript #frontend #reactJS #angular
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