🚀 WHY CONST AND LET AREN’T LIKE VAR IN JAVASCRIPT If you’ve ever wondered why const “isn’t hoisted”… Here’s the truth 👇 All variables in JavaScript are hoisted, but they’re initialized differently. 🧠 Memory Creation Phase (Before Code Runs) • Keyword Hoisting: Yes, with undefined. • Initialization: Yes. • Access Before Declaration: Allowed, resulting in ReferenceError for `let` and `const`, but undefined for `var`. ReferenceError💡 The time between scope entry and declaration is called the Temporal Dead Zone (TDZ) — the variable exists but can’t be accessed yet. console.log(a); // undefined console.log(b); // ❌ ReferenceError console.log(c); // ❌ ReferenceError var a = 10; let b = 20; const c = 30; ⚙️ What Happens Internally (Visualization) |------------------ JavaScript Execution Context ------------------| | Memory Phase (Hoisting) | var a → undefined | let b → <uninitialized> (TDZ) | const c → <uninitialized> (TDZ) |------------------------------------------------------------------| | Execution Phase | console.log(a) → undefined | console.log(b) → ReferenceError | console.log(c) → ReferenceError | a = 10; b = 20; c = 30; | console.log(a,b,c) → 10 20 30 |------------------------------------------------------------------| ✅ In short: "const and let are hoisted — but remain uninitialized until their declaration is executed." This behavior avoids unexpected bugs and makes JavaScript more predictable 💪 #JavaScript #WebDevelopment #Learning #Programming #CodeNewbie #Frontend
Chirag Sharma’s Post
More Relevant Posts
-
💭 What do you think — will this effect run on every click? const Counter = () => { const [count, setCount] = React.useState(0); const config = { theme: "dark" }; React.useEffect(() => { console.log("Effect ran"); }, [config]); return <button onClick={() => setCount(count + 1)}>Click</button>; }; At first glance, config looks static. But… this effect will run on every single click 🧨 Let’s break down why — from JavaScript memory to React Fiber internals 👇 🧠 1. JS Basics — Reference Types In JavaScript, objects & functions are reference types — compared by memory address, not content. { a: 1 } === { a: 1 } // false () => {} === () => {} // false Every render recreates: const config = { theme: "dark" } → a new object in memory → a new reference. ⚛️ 2. Under the Hood — React Fiber When setCount triggers a re-render: React creates a new Fiber node for the current render. The previous Fiber is kept as the alternate. React compares them during reconciliation. 🔄 3. Effect Dependency Comparison React checks dependencies via: Object.is(prevDep, nextDep) Since each render creates a new config reference, the comparison fails → effect runs again. 🧩 Render 1 → config ref#1 Render 2 → config ref#2 → Object.is(ref#1, ref#2) → false → Effect runs ⚡️ 🧘♂️ 4. The Fix To prevent unnecessary re-runs, stabilize the reference: const config = React.useMemo(() => ({ theme: "dark" }), []); Or, if it’s static, define it outside the component: const config = { theme: "dark" }; ✅ Summary Each render → new Fiber node New objects/functions → new references React compares deps via Object.is(prev, next) Different refs = effect re-runs Use useMemo / useCallback to stabilize references 🔍 Takeaway: Every render isn’t just new JSX — it’s new memory, new references, and a new Fiber snapshot. Understanding that is what separates debugging React from mastering it. 🚀
To view or add a comment, sign in
-
“Why does this behave so weird in JavaScript? 🤯 Let’s finally make sense of it!” If you’ve ever shouted at your screen because this suddenly became undefined — you’re not alone 😅 Let’s break down how this works across different scenarios with simple examples 👇 🧩 1️⃣ Arrow Function Defined Directly in Object const person = { name: "Suverk", greet: () => console.log(`Hi ${this.name}`) }; person.greet(); // ❌ undefined 🧠 Why? Arrow functions don’t have their own this. They lexically inherit this from their surrounding scope — which here is the global (not person). ✅ Fix: Use a regular function: greet() { console.log(`Hi ${this.name}`); } 🧩 2️⃣ Arrow Function Inside a Regular Method const person = { name: "Suverk", greet: function() { const arrow = () => console.log(this.name); arrow(); } }; person.greet(); // ✅ "Suverk" 🧠 Why? The arrow function inherits this from where it was created — inside greet, and this inside greet = person. ✅ Works perfectly because of lexical scoping. 🧩 3️⃣ Regular Function Inside Another Regular Function const person = { name: "Suverk", greet: function() { function inner() { console.log(this.name); } inner(); } }; person.greet(); // ❌ undefined 🧠 Why? When you call inner() as a plain function, it’s not attached to any object. So this defaults to global (or undefined in strict mode). ✅ Fixes: // Option 1 const self = this; function inner() { console.log(self.name); } // Option 2 function inner() { console.log(this.name); } inner.bind(this)(); // Option 3 const inner = () => console.log(this.name); 🧩 4️⃣ Detached Method Reference const person = { name: "Suverk", greet() { console.log(this.name); } }; const use = person.greet; use(); // ❌ undefined 🧠 Why? this depends on how a function is called. You’ve just taken the function reference — the link to person is gone. ✅ Fix: const use = person.greet.bind(person); use(); // ✅ "Suverk" In JavaScript, this depends on how a function is called — except for arrow functions, which depend on where they’re defined. 💬 Have you ever been tricked by this before? Drop your comment below 👇 — let’s make others learn faster than we did 😅 #JavaScript #Frontend #WebDevelopment #Angular
To view or add a comment, sign in
-
Today I revised some of the most essential JavaScript concepts that appear in real-world development. 1️⃣ Higher-Order Function (HOF) ✅ Question: Create a function that runs another function twice 📝 Code: function runTwice(fn) { fn(); fn(); } runTwice(() => console.log("hello")); 🔍 Short Explanation: A HOF is a function that takes another function as input or returns a function. Helps in reusable logic. 2️⃣ Pure Function 📝 Code: function pure(a, b) { console.log(a + b); } pure(2, 3); pure(2, 3); 🔍 Short Explanation: Always gives the same output for the same input. No side effects. 3️⃣ Impure Function 📝 Code: let global = 0; function imPure(a) { global++; console.log(a + global); } imPure(2); imPure(2); 🔍 Short Explanation: Depends on external data → output changes unexpectedly. 4️⃣ Destructuring in Function Parameters 📝 Code: const obj = { name: "Pratik", age: 21 }; function destructuring({ name, age }) { console.log(name, age); } destructuring(obj); 🔍 Short Explanation: Pulls values directly from objects → cleaner code. 5️⃣ Normal Function vs Arrow Function (this difference) 📝 Code: let objTwo = { name: "Pratik", fnc: function () { console.log(this); }, arrowFnc: () => { console.log(this); } }; objTwo.fnc(); objTwo.arrowFnc(); 🔍 Short Explanation: Normal function → owns its own this Arrow function → uses parent this (lexical) 6️⃣ map(): Square each number 📝 Code: let arr = [1, 2, 3, 4, 5]; let newArr = arr.map(e => e * e); console.log(newArr); 🔍 Short Explanation: Transforms each element → returns a new array. 7️⃣ filter(): Get even numbers 📝 Code: let filtered = arr.filter(e => e % 2 === 0); console.log(filtered); 🔍 Short Explanation: Keeps only the elements that match a condition. 8️⃣ reduce(): Total salary 📝 Code: let salary = [10000, 20000, 30000]; let total = salary.reduce((acc, v) => acc + v, 0); console.log(total); 🔍 Short Explanation: Reduces an array into one final value. 9️⃣ some() & every() 📝 Code: let names = ["pratik", "sun", "om", "krish", "vijay"]; let some = names.some(e => e.length > 3); let every = names.every(e => e.length > 3); console.log(some, every); 🔍 Short Explanation: some() → at least ONE matches every() → ALL must match 🔟 Object.freeze() 📝 Code: const users = { name: "Sunny", age: 21 }; Object.freeze(users); users.age = 22; users.city = "Surat"; delete users.name; console.log(users); 🔍 Short Explanation: No add, no delete, no modify → completely locked. 1️⃣1️⃣ Object.seal() 📝 Code: const test = { subject: "Maths", score: 50 }; Object.seal(test); test.score = 60; test.grade = "A"; delete test.subject; console.log(test); 🔍 Short Explanation: You can modify, but cannot add or delete keys. 1️⃣2️⃣ Optional Chaining (?.) 📝 Code: const user = { name: "Pratik", address: { city: "Surat" } }; console.log(user?.address?.city); 🔍 Short Explanation: Avoids errors when accessing nested properties.
To view or add a comment, sign in
-
💡JavaScript Array Methods — Simplified! 🧩 1️⃣ map() Definition: Creates a new array by applying a function to each element of the original array. const nums = [1, 2, 3]; const doubled = nums.map(n => n * 2); console.log(doubled); // [2, 4, 6] 🧩 2️⃣ filter() Definition: Creates a new array with elements that pass the given test condition. const nums = [1, 2, 3, 4]; const even = nums.filter(n => n % 2 === 0); console.log(even); // [2, 4] 🧩 3️⃣ find() Definition: Returns the first element that satisfies the given condition. const nums = [5, 10, 15]; const found = nums.find(n => n > 8); console.log(found); // 10 🧩 4️⃣ findIndex() Definition: Returns the index of the first element that satisfies the condition. const nums = [3, 6, 9]; const index = nums.findIndex(n => n === 6); console.log(index); // 1 🧩 5️⃣ reduce() Definition: Executes a reducer function on each element, resulting in a single output value. const nums = [1, 2, 3, 4]; const sum = nums.reduce((acc, curr) => acc + curr, 0); console.log(sum); // 10 🧩 6️⃣ join() Definition: Joins all elements of an array into a string. const words = ['JavaScript', 'is', 'awesome']; console.log(words.join(' ')); // "JavaScript is awesome" 🧩 7️⃣ split() Definition: Splits a string into an array based on a separator. const sentence = "Hello World"; console.log(sentence.split(' ')); // ['Hello', 'World'] 💬Try combining these methods for powerful one-liners! const result = [1,2,3,4,5].filter(n=>n%2===0).map(n=>n*10); console.log(result); // [20, 40] 💡JavaScript Array Methods in Action! Ever wondered how to turn objects into readable strings, split them back, or calculate totals easily? Here’s a simple example combining map(), join(), split(), and reduce(): const users = [ { id: 1, name: "Emma", age: 22, price: 200 }, { id: 2, name: "Max", age: 32, price: 300 }, { id: 3, name: "Olivia", age: 27, price: 500 }, { id: 4, name: "John", age: 28, price: 300 } ]; // ❌ join() works on arrays of strings, not objects. // ✅ So first, map() to get only names: const nameString = users.map(user => user.name).join(", "); console.log(nameString); // Output: "Emma, Max, Olivia, John" // ✅ split() works on strings, not arrays of objects: const nameArray = nameString.split(", "); console.log(nameArray); // Output: ["Emma", "Max", "Olivia", "John"] // ✅ reduce() to calculate total price: const total = users.reduce((sum, user) => sum + user.price, 0); console.log(total); // Output: 1300 🧠 What’s happening here? map() → Extracts only the names join() → Combines them into a single string split() → Converts the string back into an array reduce() → Sums up all prices #JavaScript #WebDevelopment #Coding Ajay Suneja 🇮🇳 ( Technical Suneja )
To view or add a comment, sign in
-
🚀 𝐌𝐚𝐬𝐭𝐞𝐫𝐢𝐧𝐠 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 𝐢𝐧 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 Ever wondered how JavaScript handles tasks without blocking the main thread? That’s where 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 come into play! ⚙️ 🧩 What is a Callback Function? 𝐀 𝐜𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐢𝐬 𝐚 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐩𝐚𝐬𝐬𝐞𝐝 𝐚𝐬 𝐚𝐧 𝐚𝐫𝐠𝐮𝐦𝐞𝐧𝐭 𝐭𝐨 𝐚𝐧𝐨𝐭𝐡𝐞𝐫 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 — 𝐚𝐧𝐝 𝐢𝐬 𝐢𝐧𝐭𝐞𝐧𝐝𝐞𝐝 𝐭𝐨 𝐛𝐞 “𝐜𝐚𝐥𝐥𝐞𝐝 𝐛𝐚𝐜𝐤” 𝐥𝐚𝐭𝐞𝐫 𝐛𝐲 𝐭𝐡𝐚𝐭 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧. 💡 Since functions in JavaScript are First-Class Citizens, they can be treated like values — passed around, returned, or assigned to variables. 📖 Think of it like this: You give function 𝐗 the responsibility to call function𝐘 later. So,𝐘becomes the callback of𝐗. ----------------------------------------------------- ⏱️ Callbacks in Action: Handling Asynchronous Operations JavaScript is 𝐬𝐢𝐧𝐠𝐥𝐞-𝐭𝐡𝐫𝐞𝐚𝐝𝐞𝐝, but callbacks allow it to perform non-blocking tasks like API calls, timers, or event handling. Here’s a simple example 👇 console.log("Start"); setTimeout(() => { console.log("⏰ This runs after 2 seconds"); }, 2000); console.log("End"); 🧠 Output: Start End ⏰ This runs after 2 seconds 💬 Explanation: When 𝐬𝐞𝐭𝐓𝐢𝐦𝐞𝐨𝐮𝐭 is called, the callback goes into the Web API environment. The JS engine keeps running other code (non-blocking). After the timer expires, the callback moves to the 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤 𝐐𝐮𝐞𝐮𝐞. It’s executed only when the Call Stack is empty, ensuring smooth asynchronous flow. 𝐓𝐡𝐚𝐭’𝐬 𝐭𝐡𝐞 𝐦𝐚𝐠𝐢𝐜 𝐨𝐟 𝐜𝐚𝐥𝐥𝐛𝐚𝐜𝐤𝐬 𝐞𝐧𝐚𝐛𝐥𝐢𝐧𝐠 𝐚𝐬𝐲𝐧𝐜 𝐛𝐞𝐡𝐚𝐯𝐢𝐨𝐫 𝐢𝐧 𝐚 𝐬𝐢𝐧𝐠𝐥𝐞-𝐭𝐡𝐫𝐞𝐚𝐝𝐞𝐝 𝐰𝐨𝐫𝐥𝐝! ✨ -------------------------------------------------- 🔒 𝐂𝐚𝐥𝐥𝐛𝐚𝐜𝐤𝐬 + 𝐂𝐥𝐨𝐬𝐮𝐫𝐞𝐬 = 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐆𝐨𝐥𝐝 💬 Here’s a classic interview problem 👇 𝐏𝐫𝐨𝐛𝐥𝐞𝐦: If you try to use a global counter variable, you risk having it modified by other parts of the code. A better solution is needed to keep the counter private and persistent. 𝐒𝐨𝐥𝐮𝐭𝐢𝐨𝐧 (𝐂𝐥𝐨𝐬𝐮𝐫𝐞): By creating a function that wraps the counter and the event listener attachment, the event handler (the callback) forms a closure over the local variable (count). 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐡𝐚𝐧𝐝𝐥𝐞𝐂𝐥𝐢𝐜𝐤() { 𝐥𝐞𝐭 𝐜𝐨𝐮𝐧𝐭 = 0; 𝐝𝐨𝐜𝐮𝐦𝐞𝐧𝐭.𝐠𝐞𝐭𝐄𝐥𝐞𝐦𝐞𝐧𝐭𝐁𝐲𝐈𝐝("𝐛𝐭𝐧").𝐚𝐝𝐝𝐄𝐯𝐞𝐧𝐭𝐋𝐢𝐬𝐭𝐞𝐧𝐞𝐫("𝐜𝐥𝐢𝐜𝐤", 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧() { 𝐜𝐨𝐮𝐧𝐭++; 𝐜𝐨𝐧𝐬𝐨𝐥𝐞.𝐥𝐨𝐠("𝐁𝐮𝐭𝐭𝐨𝐧 𝐜𝐥𝐢𝐜𝐤𝐞𝐝", 𝐜𝐨𝐮𝐧𝐭, "𝐭𝐢𝐦𝐞𝐬"); }); } 𝐡𝐚𝐧𝐝𝐥𝐞𝐂𝐥𝐢𝐜𝐤(); 🧩 Explanation: The inner callback function forms a closure over the variable count. Even after handleClick() finishes executing, count stays alive in the callback’s Lexical Environment. This keeps the counter private, persistent, and secure — no memory Leaks. #JavaScript #WebDevelopment #LearningInPublic #NamasteJavaScript #FrontendDevelopment #CodingJourney
To view or add a comment, sign in
-
#9: From Loop Newbie to Array Method Pro in JavaScript! 🚀 Today’s journey took me from basic loops to mastering powerful array methods. If you’ve ever wondered when to use for…of, for…in, forEach, map, filter, or reduce — this post is for YOU 👇 🔁 1. for…of – Best for Iterating Over Iterables (Array / Map) ✅ Returns full value ✅ Can use destructuring in Maps for (const [key, value] of myMap) { console.log(key, value); } ❌ Doesn’t work on plain objects (not iterable). 📍 2. for…in – Works on Objects & Arrays (Keys Only) ✅ Best for objects: for (const key in myObject) { console.log(key, myObject[key]); } ⚠ On arrays, it gives indexes, not values. ❌ Doesn’t work on Map. 📦 3. forEach() – Simple, Clean, No Return ✅ Great for looping arrays ✅ Accepts callback (value, index, array) ✅ Can pass an external function coding.forEach((item, index, arr) => console.log(item, index)); ❌ Doesn’t return anything (undefined always). 🗺️ 4. map() – Returns a New Array ✅ 🔹 Used when you want to transform data. const newArr = nums.map(num => num * 2); ✅ map() → RETURNS ❌ forEach() → DOES NOT RETURN 🧽 5. filter() – Keeps Only What Matches ✅ 🔍 Creates an array based on a condition. const filtered = nums.filter(num => num > 4); ✅ Returns only items that meet criteria. ⛓️ 6. Method Chaining = Cleaner Power Moves ⚡ const result = nums .map(num => num * 10) .map(num => num + 1) .filter(num => num > 50); 📉 7. reduce() – Converts Everything to a Single Value Used for totals, sums, or combining data. const total = prices.reduce((acc, curr) => acc + curr, 0); ✅ Perfect for shopping cart totals, analytics, etc. 🎯 Where You Stand Now: Level → Concept 🟢 Beginner → for...in, for...of 🟡 Intermediate → forEach, map, filter 🔴 Pro → reduce, chaining, destructuring in loops ✨My Takeaway: Once you understand array methods like map, filter, and reduce, you write less code, cleaner logic, and think more like a JavaScript pro. 💡 🧠 Which one confused you the most when you started learning loops in JS? Comment below — let’s grow together! 👇🔥 #JavaScript #WebDevelopment #LearningEveryday #Frontend
To view or add a comment, sign in
-
I recently explored how JavaScript’s number type behaves under IEEE 754-and what I found surprised me. While most developers (myself included) focus on ECMAScript compliance, I learned that even standards-compliant code can produce unexpected results in mission-critical systems. Here is what I learned, with real-world examples that show why precision matters. For example, 0.1 + 0.2 === 0.3 returns false in JavaScript due to binary floating-point precision. This is not a bug-it is IEEE 754 doing its job. IEEE 754 in Action: Unsafe comparison const a = 0.1; const b = 0.2; const sum = a + b; console.log(sum); // 0.30000000000000004 console.log(sum === 0.3); // false Safe Comparison Using Tolerance function nearlyEqual(x, y, epsilon = 1e-10) { return Math.abs(x - y) < epsilon; } console.log(nearlyEqual(0.1 + 0.2, 0.3)); // true This method checks if two numbers are close enough, which is the recommended approach for comparing floats. Safer Arithmetic with Integers const priceCents = 10 + 20; // 0.1 + 0.2 -> 10 + 20 const totalCents = priceCents * 100; // 3000 console.log(totalCents / 100); // 30 Use integers for money, counts, and critical logic to avoid rounding surprises. Decimal Libraries for Precision HTML <script type="module"> import Decimal from ''https://lnkd.in/gi4T53Fe'; const x = new Decimal('0.1'); const y = new Decimal('0.2'); const z = x.plus(y); console.log(z.toString()); // "0.3" </script> /* Use Node.js with ES Modules If you're using Node.js, either: Rename your file to .mjs Or add "type": "module" to your package.json */ import Decimal from 'decimal.js'; const x = new Decimal('0.1'); const y = new Decimal('0.2'); const z = x.plus(y); console.log(z.toString()); // "0.3" // Use require() in CommonJS (Node.js) const Decimal = require('decimal.js'); const x = new Decimal('0.1'); const y = new Decimal('0.2'); const z = x.plus(y); console.log(z.toString()); // "0.3" Libraries like decimal.js or Big.js offer exact decimal arithmetic, ideal for financial and mission-critical applications. This got me curious about real-world consequences of precision loss. I came across examples like: Patriot Missile Failure (1991): 0.34 sec drift due to rounding -> 28 lives lost Ariane 5 Rocket Explosion (1996): float-to-int overflow -> $370M loss Knight Capital (2012): float error in trading logic -> $440M loss in 45 mins Medical devices: insulin pumps miscalculating dosage due to float rounding These are not edge cases-they are reminders that even basic arithmetic can be dangerous in the wrong context. I am not an IoT or finance expert, but this learning made me rethink how I handle numbers in code. For critical logic, I now prefer: Using integers (e.g., cents instead of dollars) Leveraging BigInt or libraries like decimal.js Adding runtime checks for IEEE 754 compliance Avoiding implicit float-to-int conversions Have you ever run into float precision issues in your own projects?
To view or add a comment, sign in
-
#4 Just wrapped up an intense session on the backbone of JavaScript: Arrays and Objects. These aren't just data structures; they're the building blocks for everything we do. Here’s a quick rundown of my key takeaways: JavaScript Deep Dive: Taming Arrays & Objects! 🚀 📌 Arrays: The Ordered Lists More than just [1, 2, 3], arrays are powerhouses with methods that can make or break your code. The Mutable vs. Immutable Showdown: slice(): The polite one. It takes a copy of a section without disturbing the original. splice(): The disruptive one. It removes/replaces elements in the original array. (A classic interview question! ✅) Combining Arrays: Forget push(array) which creates nested arrays! Use concat() or the more modern Spread Operator ... to cleanly merge arrays. Powerful Prototypes: Methods like Array.from() to create arrays from array-like objects (like a string) and flat() to flatten nested arrays are game-changers. 📌 Objects: The Key-Value Kings Objects store structured data, and mastering them is non-negotiable. Two Ways to Create: Object Literals: const obj = { key: 'value' } (Most common) Constructor: Object.create() (Creates a singleton) Constructor method with new Object() Accessing Properties: You can use dot notation (obj.key) or bracket notation (obj["key"]). Bracket notation is essential for keys with spaces or dynamically generated keys. Symbol as a Key: You can use a Symbol for a unique, non-enumerable property key. A hidden gem for defining special properties. Object.freeze() vs. Object.seal(): - freeze(): Makes an object immutable. No changes, additions, or deletions. - seal(): Allows modification of existing properties, but prevents adding or removing new ones. 🔥 Leveling Up: Higher-Order Functions & Destructuring Array Methods that Shine: - map(): Transform each element. (Create a new array of doubled values). - filter(): Select elements based on a condition. - reduce(): Boil down the array to a single value (like a sum). - forEach(): Execute a function for each element (but doesn't return a new array like map). Destructuring Magic: This is a syntax superpower! - Arrays: const [first, second] = myArray - Objects: const { name, email } = userObject It makes code incredibly clean and readable, especially in function parameters and React props. 💡 The Big Revelation: Understanding the difference between shallow copy and deep copy is crucial when working with these structures to avoid unintended side effects. It's amazing how much power is packed into these fundamentals. The more you learn, the more you realize how elegant and powerful JavaScript can be. What's your favorite JavaScript array or object method? Any "aha!" moments when you first understood destructuring? Share below! 👇 #JavaScript #Programming #WebDevelopment #Coding #LearnToCode #SoftwareEngineering #Arrays #Objects #Destructuring #LinkedInLearning #Tech
To view or add a comment, sign in
-
Let’s talk about a surprisingly underused but powerful tool in JavaScript: the Nullish Coalescing Operator (??). If you haven’t been using this gem yet, it might just simplify your code and help you avoid some common bugs related to default values. Here’s the problem it solves: often, you want to provide a fallback or default value when a variable is undefined or null. Previously, many of us leaned heavily on the logical OR (||) operator, like this: ```javascript const userInput = ''; const displayName = userInput || 'Guest'; // displayName will be 'Guest' ``` Looks fine, right? But wait—what if the user deliberately entered an empty string, which is a valid input here? The || operator treats empty strings, 0, NaN, and false as falsy and will override those with the fallback value. That can lead to unexpected behavior. Enter the Nullish Coalescing Operator (??): ```javascript const userInput = ''; const displayName = userInput ?? 'Guest'; // displayName will be '' ``` With ??, only null or undefined triggers the fallback. Empty strings, zeros, and false remain untouched. This is a cleaner, more precise way of handling defaults. This operator is especially useful in real-world cases such as: - Config settings, where 0 or false can be valid options. - API responses, where some fields can be omitted (undefined) but others deliberately falsey. - Form inputs, where user data might legitimately be falsey but not null. Here’s a quick snippet comparing the two approaches: ```javascript function getTimeout(config) { // Using OR operator const timeoutOld = config.timeout || 3000; // Using Nullish Coalescing const timeoutNew = config.timeout ?? 3000; console.log('Old:', timeoutOld, 'New:', timeoutNew); } getTimeout({ timeout: 0 }); // Output: // Old: 3000 New: 0 ``` See how ?? correctly respects 0 as a valid value, while || doesn’t? Pro tip: avoid mixing ?? with || in the same expression, as it can cause syntax errors or produce confusing results. Use parentheses if you must combine them. So if you want to write clearer, less bug-prone JavaScript, start using the Nullish Coalescing Operator. It might be a tiny change for your code but a giant leap in clarity and correctness. Have you used ?? in your projects yet? What scenarios made you appreciate it? Let’s swap tips in the comments! #JavaScript #WebDevelopment #CodingTips #TechTrends #Frontend #Programming #DeveloperExperience
To view or add a comment, sign in
-
🍏 JS Daily Bite #11 — Enumerability and Ownership of Properties Understanding Property Classification Every property in JavaScript objects can be classified by three factors: 🧩 Enumerability: Whether the property is enumerable or non-enumerable 🧩 Type: Whether it's a string or symbol property 🧩 Ownership: Whether it's an own property or inherited from the prototype chain 🔍 What Are Enumerable Properties? Enumerable properties have their internal enumerable flag set to true. This is the default for properties created via simple assignment or property initializers. Properties defined via Object.defineProperty() are not enumerable by default. Most iteration methods like for...in loops and Object.keys() only visit enumerable keys. 🧱 Understanding Property Ownership Ownership determines whether a property belongs directly to the object or comes from its prototype chain. All properties can be accessed using dot notation or bracket notation, regardless of their enumerability, type, or ownership. ⚙️ Methods for Checking Property Characteristics 1. propertyIsEnumerable() ✅ Returns true only for enumerable, own properties ❌ Returns false for inherited or non-enumerable properties 2. hasOwnProperty() / Object.hasOwn() ✅ Returns true for both enumerable and non-enumerable own properties ❌ Returns false for inherited properties 3. in operator ✅ Returns true for all properties, regardless of enumerability or ownership Checks both own and inherited properties 🔁 Methods for Traversing Object Properties -- Object.keys() / Object.values() / Object.entries() Visit only enumerable, own string properties -- Object.getOwnPropertyNames() Visits both enumerable and non-enumerable own string properties -- Object.getOwnPropertySymbols() Visits both enumerable and non-enumerable own symbol properties -- Reflect.ownKeys() / Object.getOwnPropertyDescriptors() Visit all own properties (string and symbol, enumerable or not) -- for...in loop Visits enumerable string properties, including inherited ones -- Object.assign() / Object spread (...) Copies only enumerable own properties ⚖️ Function Constructors vs Classes An important distinction between function constructors and ES6 classes relates to method enumerability: 🔴 Function Constructors: Methods added to the prototype are enumerable by default, meaning they appear in for...in loops and Object.keys() 🟢 Classes: All methods defined in a class are non-enumerable by default, matching native JavaScript object behavior This difference is one reason classes are preferred—they produce cleaner, less error-prone inheritance structures. 🔜 Next in series: Exploring Functions — from declarations and expressions to arrow functions, hoisting, and more! #JavaScript #JSDailyBite #WebDevelopment #Programming #FrontendDevelopment #LearnToCode #SoftwareEngineering #JSTips #TechEducation
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