Let’s talk about a subtle but powerful gem in JavaScript you might be overlooking: The Nullish Coalescing Operator (??). In 2024, with codebases growing more complex, handling “empty” or “absent” values cleanly is more important than ever. And that’s where this operator shines. You’re probably familiar with the OR operator (||) for providing default values. It’s nice, but has a gotcha — it treats falsy values like 0, '', or false as “absent,” which can break your logic unexpectedly: ```javascript const count = 0; const defaultCount = count || 10; console.log(defaultCount); // prints 10, but you might expect 0 here! ``` Oops! Here, 0 is a legitimate value, but || doesn’t see it that way. Enter the nullish coalescing operator ?? — it only catches null or undefined, not other falsy values: ```javascript const count = 0; const defaultCount = count ?? 10; console.log(defaultCount); // prints 0, which is correct ``` Simple but game-changing! Why should you care? - It helps you write safer defaults without accidentally overriding valid falsy values. - It improves code readability by making intent crystal clear. - It pairs beautifully with optional chaining (?.), another modern JS feature, to safely access deeply nested properties: ```javascript const user = { settings: { theme: null } }; const theme = user.settings?.theme ?? 'light'; console.log(theme); // "light" instead of null or error ``` This combo is essential for handling real-world data where some properties might be missing or intentionally null. My takeaway: When you need fallback values, prefer `??` over `||` if you want to preserve meaningful falsy values like 0, false, or ''. Give it a try next time you find yourself writing default values. Small changes like this make your code cleaner, fewer bugs sneak in, and your future self thanks you. Happy coding! #JavaScript #FrontendDev #CodeQuality #WebDevelopment #ProgrammingTips #TechTrends #CleanCode
Why You Should Use the Nullish Coalescing Operator in JavaScript
More Relevant Posts
-
🚀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁’𝘀 𝗠𝗼𝘀𝘁 𝗠𝗶𝘀𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗼𝗼𝗱 𝗞𝗲𝘆𝘄𝗼𝗿𝗱: this If you’ve ever scratched your head wondering why this doesn’t point where you expect — you’re not alone 😅 Let’s break it down 👇 What is this? • In JavaScript, this refers to 𝘁𝗵𝗲 𝗼𝗯𝗷𝗲𝗰𝘁 𝘁𝗵𝗮𝘁’𝘀 𝗲𝘅𝗲𝗰𝘂𝘁𝗶𝗻𝗴 𝘁𝗵𝗲 𝗰𝘂𝗿𝗿𝗲𝗻𝘁 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 — but its value 𝗱𝗲𝗽𝗲𝗻𝗱𝘀 𝗼𝗻 𝗵𝗼𝘄 the function is called (not where it’s written). • In Regular Function Declarations / Expressions function showThis() { console.log(this); } showThis(); // In strict mode → undefined | Non-strict → window (in browser) Here, this is determined by the 𝗰𝗮𝗹𝗹𝗲𝗿. When called directly, it defaults to the global object (window), or undefined in strict mode. • In Object Methods const user = { name: "Alice", greet() { console.log(this.name); } }; user.greet(); // "Alice" ✅ this points to the object 𝗯𝗲𝗳𝗼𝗿𝗲 𝘁𝗵𝗲 𝗱𝗼𝘁 (user in this case). In Arrow Functions const user = { name: "Alice", greet: () => console.log(this.name) }; user.greet(); // ❌ undefined Arrow functions 𝗱𝗼𝗻’𝘁 𝗵𝗮𝘃𝗲 𝘁𝗵𝗲𝗶𝗿 𝗼𝘄𝗻 this — they 𝗶𝗻𝗵𝗲𝗿𝗶𝘁 it from the surrounding (lexical) scope. So here, this refers to the global object, not user. 💡 𝗤𝘂𝗶𝗰𝗸 𝗧𝗶𝗽: Use regular functions for object methods if you need access to the object’s properties. Use arrow functions when you want to preserve the parent scope’s this (like inside a class or callback). 👉 Mastering this is one of the biggest “Aha!” moments in JavaScript. What’s your favorite trick or gotcha with this? #JavaScript #WebDevelopment #Frontend #Coding #LearnToCode #JS #this #software
To view or add a comment, sign in
-
When I first started with JavaScript, I often saw the terms “stateful” and “stateless”, and honestly, they felt abstract. But understanding them completely changed how I write and think about code. Stateless: Stateless components or functions don’t remember anything. They take input, return output, and that’s it. Think of them like vending machines, same input, same result. Example: function add(a, b) { return a + b; } Stateful: Stateful logic, on the other hand, remembers things. It tracks data that changes over time, like user input, API calls, or UI interactions. A stateful object holds data within itself, meaning its behavior can change depending on that internal state. Example: const counter = { count: 0, increment() { this.count++; return this.count; } }; Here, counter remembers its count, so its output depends on past interactions, that’s what makes it stateful. Knowing when to use stateful vs stateless logic keeps your code clean, predictable, and easier to test. #JavaScript #WebDevelopment #React #Nextjs #Frontend #Coding #LearnInPublic #DeveloperCommunity
To view or add a comment, sign in
-
JavaScript Promise.allSettled() — Get Every Result Without Breaking Your Code! Sometimes, you don’t care whether all promises succeed — you just want to know the outcome of each one, success ✅ or failure ❌. That’s exactly what Promise.allSettled() does! 💡 Definition: Promise.allSettled() takes an array of promises and returns a single promise that resolves after all of them finish, no matter if they’re resolved or rejected. 🧩 Example: const task1 = Promise.resolve("✅ Task 1 done"); const task2 = Promise.reject("❌ Task 2 failed"); const task3 = Promise.resolve("✅ Task 3 done"); Promise.allSettled([task1, task2, task3]) .then((results) => console.log(results)); ✅ Output: [ { status: 'fulfilled', value: '✅ Task 1 done' }, { status: 'rejected', reason: '❌ Task 2 failed' }, { status: 'fulfilled', value: '✅ Task 3 done' } ] Each promise gives its own result with a status and value/reason — so you can handle success or failure individually. ⚙️ Why Use It? ✅ Avoids breaking the chain when one fails ✅ Best for batch processing or API results ✅ Gives full visibility of all outcomes 🔖 #JavaScript #PromiseAllSettled #AsyncProgramming #WebDevelopment #Frontend #JSConcepts #CodingTips #KishoreLearnsJS #100DaysOfCode #WebDevCommunity #DeveloperJourney #AsyncAwait
To view or add a comment, sign in
-
🔥 Loop Optimization in JavaScript — Code Smarter, Run Faster (2025 Edition) Loops are the heartbeat of your JavaScript logic and optimizing them can make your entire site feel snappier. Let’s level up your performance game 👇 1️⃣ Stick with the Classic for Loop: It’s old-school but still unbeaten for large datasets. Cache your arr.length and let your loops fly! 2️⃣ Readability Wins Too — Use map(), filter(), reduce(): Not every battle is about speed. These methods make your code clean, modern, and maintainable — perfect for smaller or non-critical processes. 3️⃣ Skip forEach() When Every Millisecond Counts: forEach() looks neat but hides function call overheads. For mission-critical speed, go back to basics. 4️⃣ Flatten Those Nested Loops: Nested iterations are performance black holes. Flatten data structures or rethink your logic to cut unnecessary loops. 5️⃣ Break Big Jobs into Small Wins: Long-running loops freeze the UI. Break them into chunks: function runInSmallBatches(arr, size) { let i = 0; function batch() { const end = Math.min(i + size, arr.length); for (; i < end; i++) {} if (i < arr.length) setTimeout(batch, 0); } batch(); } ⚡ Now your app breathes — smooth, responsive, and lag-free. Benchmark Everything. Don’t just “optimize” — prove it’s faster. Measure before and after. 💬 Final Thought: Write code that’s not just smart — but feels lightning fast. 🚀 #JavaScript #WebPerformance #CodingTips #FrontendDevelopment #SoftwareEngineering #WebOptimization #Programming #CodeBetter #JSPerformance #WebDev #TechTips #CleanCode #DevelopersLife #PerformanceMatters
To view or add a comment, sign in
-
-
🔗 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
-
Memoization in JavaScript — What Really Happens Behind the Scenes It’s a simple yet powerful optimization technique that stores the results of expensive function calls — and returns the cached result when the same inputs appear again. ✅ Why it matters Boosts performance for repetitive computations. Especially useful for recursive functions like fibonacci or factorial. It’s one of the core ideas behind frameworks like React (think of useMemo). Here’s an example 👇 function memoize(fn) { const cache = new Map(); return function(...args) { const key = JSON.stringify(args); if (cache.has(key)) { console.log("Cache hit for:", key); return cache.get(key); } console.log("Cache miss for:", key); const result = fn(...args); cache.set(key, result); return result; }; } 💡 What’s Happening Behind the Scenes Each unique input is stored as a key in a cache. When the function is called again with the same input, the result is fetched instantly — no recalculation. This saves time and CPU cycles, especially for recursive or data-heavy operations. ✨ Tip: Memoization trades memory for speed — so use it wisely when function calls are expensive and inputs repeat often. #JavaScript #WebDevelopment #Performance #Programming #Coding #Memoization #Frontend #TechTips
To view or add a comment, sign in
-
💡 Today I learned how libuv works behind the scenes in Node.js When we talk about Node.js, it mainly has two core parts: 1. ⚙️ V8 Engine – Executes JavaScript code. 2. ⚡ libuv – Handles all the asynchronous, non-blocking I/O operations. Whenever we write JavaScript code in Node.js, the V8 engine runs the synchronous parts line by line. But when Node encounters an async task like: fs.readFile() setTimeout() https.get() …it offloads them to libuv so the main thread doesn’t get blocked. 🔍 What libuv Does? libuv is the superhero that makes Node.js non-blocking. It manages: - A Thread Pool (for file system & network tasks) - Multiple Callback Queues (for timers, I/O, immediates, etc.) - The Event Loop (that decides when each callback should run) 🌀 How the Event Loop Works The event loop in libuv runs continuously in cycles and has four main phases: 1.⏱️ Timer Phase – Executes callbacks from setTimeout() & setInterval(). 2.⚙️ Poll Phase – Executes most I/O callbacks like fs.readFile() or https.get(). 3.🚀 Check Phase – Executes callbacks from setImmediate(). 4.🧹 Close Phase – Handles cleanup tasks like closing sockets. Between every phase, Node checks for microtasks like process.nextTick() and Promise callbacks, which have higher priority and run before moving to the next phase. ⚡ In Short: 1. V8 runs your code synchronously. 2. Async tasks go to libuv. 3. libuv manages them in background threads. 4. The event loop schedules their callbacks efficiently. That’s how Node.js achieves asynchronous, non-blocking I/O even though JavaScript is single-threaded! 🧠✨ #NodeJS #JavaScript #WebDevelopment #Backend #LearningInPublic #libuv #EventLoop #AsyncProgramming
To view or add a comment, sign in
-
Today's Topic: Promise Chaining in JavaScript In JavaScript, Promise chaining allows you to execute asynchronous tasks one after another, ensuring that each step waits for the previous one to finish. Instead of nesting callbacks (callback hell ), promises make your code cleaner and easier to maintain. Example: function step1() { return new Promise((resolve) => { setTimeout(() => { console.log("Step 1 completed ✅"); resolve(10); }, 1000); }); } function step2(value) { return new Promise((resolve) => { setTimeout(() => { console.log("Step 2 completed ✅"); resolve(value * 2); }, 1000); }); } function step3(value) { return new Promise((resolve) => { setTimeout(() => { console.log("Step 3 completed ✅"); resolve(value + 5); }, 1000); }); } // Promise Chaining step1() .then(result => step2(result)) .then(result => step3(result)) .then(finalResult => console.log("Final Result:", finalResult)) .catch(error => console.error("Error:", error)); ✅ Output (after 3 seconds): Step 1 completed ✅ Step 2 completed ✅ Step 3 completed ✅ Final Result: 25 Each .then() runs after the previous promise resolves — making async flow easy to read and manage. --- 🔖 #JavaScript #WebDevelopment #PromiseChain #AsyncProgramming #CodingTips #FrontendDevelopment #Developers #JSConcepts #CodeLearning #100DaysOfCode #WebDevCommunity
To view or add a comment, sign in
-
-
🚀 Day 30/50 – Function Currying in JavaScript Think of Function Currying like building a relationship. You don’t propose directly 😅 First comes the “Hi Hello 👋” phase → then friendship ☕ → and finally… the proposal ❤️ In JavaScript, instead of passing all arguments at once, Function Currying lets us pass them step by step, each step returning a new function until the final output is achieved. Here’s a simple code analogy from my video: function proposeTo(crush) { return function (timeSpent) { return function (gift) { return `Dear ${crush}, after ${timeSpent} of friendship, you accepted my ${gift}! 🥰`; }; }; } console.log(proposeTo("Sizuka")("3 months")("red rose 🌹")); Each function takes one argument and returns another function — making the code modular, flexible, and easy to reuse. 👉 This is Function Currying — one argument, one step, one perfect result. 🎥 Watch the full short video here: 🔗 https://lnkd.in/g-NkeYBc --- 💡 Takeaway: Function Currying isn’t just a JavaScript trick — it’s a powerful pattern for cleaner, more composable functions that enhance reusability and maintainability in modern frontend code. --- Would love to know: 👉 What’s your favorite JavaScript concept that clicked instantly when you saw it explained simply? #javascript #frontenddevelopment #webdevelopment #coding #programming #softwareengineering #learnjavascript #100daysofjavascript #techsharingan #developers #careergrowth
To view or add a comment, sign in
-
*5 Things I Wish I Knew When Starting JavaScript 👨💻* Looking back, JavaScript was both exciting and confusing when I started. Here are 5 things I wish someone had told me earlier: *1. var is dangerous. Use "let" and "const" "var" is function-scoped and can lead to unexpected bugs. "let" and "const" are block-scoped and safer. *2. JavaScript is asynchronous Things like "setTimeout()"and "fetch()" don’t behave in a straight top-down flow. Understanding the *event loop* helps a lot. *3. Functions are first-class citizens* – You can pass functions as arguments, return them, and even store them in variables. It’s powerful once you get used to it. *4. The DOM is slow – avoid unnecessary access* – Repeated DOM queries and manipulations can hurt performance. Use "documentFragment" or batch changes when possible. *5. Don’t ignore array methods* map(), "filter()" , "reduce()", "find()"… they make code cleaner and more readable. I wish I started using them sooner. 💡 *Bonus Tip:* "console.log()" is your best friend during debugging! If you’re starting out with JS, save this. And if you're ahead in the journey — what do *you* wish you knew earlier? #JavaScript #WebDevelopment #CodingJourney #Frontend #LearnToCode #DeveloperTips
To view or add a comment, sign in
More from this author
Explore related topics
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