🌟 Day 56 of JavaScript 🌟 🔹 Topic: Error Handling Best Practices 📌 1. Why Error Handling Matters? Errors are inevitable — but crashing apps aren’t. Good developers don’t avoid errors, they handle them gracefully ✨ Error handling ensures your app stays stable, predictable, and user-friendly even when something breaks. ⸻ 📌 2. Using try...catch try { const data = JSON.parse('{"name":"Pavan"}'); console.log(data.name); } catch (error) { console.error("Invalid JSON format!", error.message); } ✅ Safely runs code that might fail ✅ Prevents complete program crashes ⸻ 📌 3. Always Handle Async Errors async function fetchData() { try { const res = await fetch("https://lnkd.in/gXUzR2fM"); if (!res.ok) throw new Error("Network issue!"); const data = await res.json(); console.log(data); } catch (err) { console.error("Fetch failed:", err.message); } } 💡 Always check for .ok before using res.json(). ⸻ 📌 4. Custom Error Messages throw new Error("User not authorized!"); ✅ Be specific and meaningful ✅ Avoid generic messages like “Something went wrong” ⸻ 📌 5. Logging & Monitoring Use tools like: • 🪵 console.error() for dev logs • 🧠 Sentry, LogRocket, or Datadog for real-time production tracking ⸻ 📌 6. Don’t Hide Errors Avoid empty catch blocks 🚫 try { riskyFunction(); } catch (e) { // ❌ silently ignores problem } Always log or handle them properly. ⸻ 📌 7. Graceful UI Feedback When an error happens, show users a helpful message like: “Something went wrong. Please try again.” Not just a blank screen 🪦 ⸻ 💡 In short: Error handling isn’t just about fixing bugs — it’s about building resilience 🧱 A good developer makes sure their code fails smartly, not silently 💪 ⸻ #JavaScript #100DaysOfCode #ErrorHandling #TryCatch #FrontendDevelopment #WebDevelopment #CodingJourney #JavaScriptLearning #CleanCode #DevCommunity #CodeNewbie #WebDev #BestPractices
NARESH KUMAR MATTA’s Post
More Relevant Posts
-
JavaScript Silent Errors — why they sneak up on you (and how to stop them) 🕵️♂️💥 Silent errors are bugs that don’t crash your app or throw a clear error — they just do the wrong thing and quietly ruin your day. Here are the most common culprits, short examples, and quick fixes you can start using today. What “silent” looks like Your function returns undefined instead of the object you expected. An assignment quietly fails (but code keeps running). A promise rejection never gets handled and silently breaks a flow. You swallow errors in an empty catch block. Tiny examples that bite 1. Forgotten return in arrow with block body const getUser = () => { name: 'Akin' }; // NOT returning the object console.log(getUser()); // undefined — no exception, just wrong // Fix: use parentheses or an explicit return const getUser2 = () => ({ name: 'Akin' }); 2. Assignment to non-writable property (non-strict mode = silent) const o = {}; Object.defineProperty(o, 'x', { value: 1, writable: false }); o.x = 2; // no error in non-strict mode — assignment ignored console.log(o.x); // 1 // Fix: use 'use strict' or check property descriptors 3. Swallowed error try { JSON.parse(badData); } catch (e) { // silently ignored — you never know parsing failed } // Fix: log/handle, or rethrow 4. Unhandled promise rejection (can be quiet) fetch('/api/thing') .then(r => r.json()); // no .catch -> rejection may be missed // Fix: always .catch() or use try/catch with async/await How to catch these earlier (practical checklist) Enable strict mode: use strict (or use modules — they’re strict by default). Use linters: ESLint with rules like no-empty, no-implicit-globals, no-unused-vars. Type safety: adopt TypeScript or Flow to catch wrong shapes/returns. Don’t swallow errors: never leave empty catch blocks — log or handle them. Always handle promises: .catch() or try { await ... } catch (e) { ... }. Add global handlers: window.addEventListener('unhandledrejection', e => console.error(e)); window.onerror = (msg, src, line, col, err) => { ... } DevTools: enable “Pause on exceptions” and break on caught exceptions during debugging. Tests & CI: unit tests + linting in CI stop regressions before they hit users. Error monitoring: Sentry/Rollbar/Bugsnag to surface production silent failures. Quick habits that pay off Log meaningful errors (include stack + context). Fail fast — prefer throwing or returning explicit errors instead of hiding failures. Small focused functions: easier to test and reason about. Code reviews: a second pair of eyes spots “weird but not crashing” issues. Wrap-up Silent errors are the worst because they’re invisible — make noise for them. Add linting + strict mode + promise handling + some basic monitoring and you’ll catch 90% of them early. #codecraftbyaderemi #webdevelopment #javascripterrors #learnJS #javascript
To view or add a comment, sign in
-
-
Understanding React Fragments, Error Boundaries & Pop Method — With Real Life Example When building React applications, we often deal with UI structure, error handling, and data manipulation. Three powerful concepts that make your code cleaner and more stable are Fragments, Error Boundaries, and the Pop() method in JavaScript arrays. Let’s dive in! 🚀 🔹 1. React Fragments — No More Extra Divs! Imagine you want to return multiple elements from a component, but React only allows one parent element. Instead of wrapping everything in unnecessary <div> tags, we can use Fragments. Example: function UserProfile() { return ( <> <h2>Kushi</h2> <p>Full Stack Developer & Dancer 💃</p> </> ); } Real-life analogy: Think of Fragments like carrying multiple small items in your hand without needing a bag. You get everything together, but without the extra wrapper. 🔹 2. Error Boundaries — Catching Mistakes Gracefully Sometimes your app may break due to unexpected errors — and you don’t want the entire UI to crash. That’s where Error Boundaries come in! Example: class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError() { return { hasError: true }; } componentDidCatch(error, info) { console.error("Error caught:", error); } render() { if (this.state.hasError) { return <h2>Something went wrong 😔</h2>; } return this.props.children; } } // Usage <ErrorBoundary> <UserProfile /> </ErrorBoundary> Real-life analogy: Think of it as a helmet while riding your bike 🏍️. Even if you fall (error happens), the helmet (Error Boundary) protects you from total disaster! 🔹 3. The Pop() Method — Removing the Last Item In JavaScript, the pop() method is used to remove the last element of an array. Example: let tasks = ["Dance Practice", "Code Review", "Hackathon Prep"]; tasks.pop(); console.log(tasks); // Output: ["Dance Practice", "Code Review"] Real-life analogy: Like removing the last book you placed on top of a pile 📚 — simple and instant. 💡 Bringing It All Together Let’s imagine you’re building a task tracker app: Use Fragments to neatly return task title and details. Wrap the app with an Error Boundary to handle unexpected errors safely. Use pop() to remove the most recent task added. You’ll get a neat, safe, and efficient React experience ✨ 🔖 #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #CodingCommunity #ErrorBoundary #ReactFragments #PopMethod #DevLife #LearnReact #CodeWithKushi
To view or add a comment, sign in
-
⚙️ Stages of Errors in Node.js Errors in Node.js don’t just happen — they evolve through multiple stages, from the moment they occur to the moment they’re finally resolved. Understanding these stages helps developers write resilient and production-ready applications. 💡 🔸 1️⃣ Error Creation / Occurrence ⚙️ Syntax Errors: Triggered before execution — caused by invalid JavaScript syntax like missing brackets, typos, or misplaced keywords. 🚨 Runtime Errors: Occur while the app is running — like referencing undefined variables, failed I/O operations, or network issues. 🧩 Logical Errors: The sneaky ones — code runs fine but produces wrong results due to flawed logic or bad assumptions. 🔸 2️⃣ Error Flow / Propagation ⏱️ Synchronous Code: Errors bubble up the call stack. Without try...catch, they can crash your application. 🌐 Asynchronous Code: Errors in callbacks, Promises, or async functions must be handled manually — or they disappear quietly. 🔸 3️⃣ Error Capturing & Handling 🧱 try...catch Blocks: Handle both synchronous and async/await-based errors. 🔄 Callback Convention: In Node-style callbacks, the first argument is always the error. ✨ Promises: Use .catch() to handle rejections and prevent unhandled promise errors. 📢 Event Emitters: Some modules throw 'error' events — always attach listeners for them. ⚠️ Global Handlers: process.on('uncaughtException') and process.on('unhandledRejection') act as final catchers (use sparingly — they can mask real bugs). 🔸 4️⃣ Error Logging & Observation 🧾 Logging Tools: Use Winston, Pino, or Morgan for structured logs and detailed error traces. 📊 Monitoring Platforms: Integrate tools like Sentry, Datadog, or LogRocket for real-time alerts and performance insights. 🔸 5️⃣ Error Fixing & Prevention 🔍 Debugging: Follow stack traces, reproduce issues, and isolate faulty logic. 🧠 Code Review: Refactor problem areas and implement proper error boundaries. 🚀 Deployment: Patch, redeploy, and monitor — ensuring your fix holds up in production. 💬 Error handling isn’t just cleanup — it’s the backbone of a reliable backend. Master it, and you’ll spend less time firefighting 🔥 and more time building something great. 💪 #NodeJS #ErrorHandling #JavaScript #Backend #WebDevelopment #ProgrammingLife #CleanCode #10000coders
To view or add a comment, sign in
-
-
Why Asynchronous JavaScript? JavaScript runs on a single thread — it can only execute one task at a time. So how does it handle things like API calls, file reads, or setTimeouts without blocking everything else? That’s where Promises and async/await come in — they let JS manage asynchronous operations gracefully. 💡 What is a Promise? A Promise represents a value that may be available now, later, or never. It has 3 states: ⏳ Pending — waiting for the result ✅ Fulfilled — operation successful ❌ Rejected — operation failed 📘 Example: const getData = new Promise((resolve, reject) => { setTimeout(() => { resolve("✅ Data fetched successfully!"); }, 2000); }); getData .then(result => console.log(result)) .catch(error => console.error(error)); 🧩 Output (after 2s): Data fetched successfully! ⚙️ async/await — The Cleaner Way async and await make writing asynchronous code look synchronous and easy to follow. 📘 Example: async function fetchData() { try { const data = await getData; console.log(data); } catch (error) { console.error(error); } } fetchData(); ✅ No chaining ✅ Easier debugging ✅ Cleaner, more readable code 🧠 Top Interview Question #4: Q: What’s the difference between Promises and async/await? A: Both handle asynchronous operations. Promises use .then() and .catch(), while async/await provides a cleaner, synchronous-looking syntax built on top of Promises. 💡 Key Takeaways: 1️⃣ Promises simplify handling asynchronous operations. 2️⃣ async/await makes async code cleaner and easier to debug. 3️⃣ Both rely on the Event Loop to manage non-blocking behavior. 🙌 Have you ever accidentally mixed .then() and await in the same code? 😅 Share your async blunders (or lessons) below 👇 — let’s learn together! #JavaScript #AsyncJS #Promises #AsyncAwait #WebDevelopment #Frontend #NodeJS #CodingTips #InterviewPreparation #JavaScriptInterviewQuestions #AsyncProgramming #31DaysOfJavaScript
To view or add a comment, sign in
-
🚀 LeetCode #283 — Move Zeroes (JavaScript Edition) This problem teaches array manipulation, in-place updates, and the pointer technique — perfect for frontend interviews. Below are 3 clear ways to solve it (beginner-friendly). I use both the traditional temp, swap and the modern destructuring so learners can pick what they understand best. 🧩 Approach 1 — One Loop (Swapping Elements) function moveZeroes(nums) { let p = 0; // next position for a non-zero for (let i = 0; i < nums.length; i++) { if (nums[i] !== 0) { if (i !== p) { // ✅ Only swap when needed let temp = nums[p]; nums[p] = nums[i]; nums[i] = temp; // traditional swap — beginners find this clear } p++; } } return nums; } ⚙️ Possible Minor Improvements You can simplify the code by avoiding the swap when p === i. This avoids unnecessary swapping when the element is already in the correct position. Cleaner version 👇 var moveZeroes = function(nums) { let p = 0; for (let i = 0; i < nums.length; i++) { if (nums[i] !== 0) { if (i !== p) { // ✅ Only swap when needed [nums[p], nums[i]] = [nums[i], nums[p]]; } p++; } } return nums; }; 💡 Why it’s better: When elements are already in order, this avoids unnecessary writes — a small tweak, but cleaner and slightly more efficient! 💬 For learners [nums[p], nums[i]] = [nums[i], nums[p]]; is called Array Destructuring Assignment in JavaScript. Example: [a, b] = [b, a]; It’s a modern, shorter, and cleaner way to swap two values without using a temporary variable. 🧠 Approach 2 — Two Loops (Copy and Fill) function moveZeroes(nums) { let x = 0; for (let i = 0; i < nums.length; i++) { if (nums[i] !== 0) { nums[x] = nums[i]; x++; } } for (let i = x; i < nums.length; i++) { nums[i] = 0; } return nums; } ✅ How it works: The first loop copies all non-zero values to the front (no swapping needed). The second loop fills the remaining positions with zeros. If zeros are already at the end, the second loop just reassigns them — still simple O(n) work. 🔍 Why Use 2 Loops Instead of Swapping? When you use swapping, each non-zero element is moved one by one — even if it’s already in the correct place. The two-loop version just copies forward, making the logic easier to reason about and the code cleaner. 💡 Fun Fact for Learners Both methods run in O(n) time and use O(1) extra space. Using temp is the traditional swap (slight speed boost). Using [a, b] = [b, a] is the modern JS swap. The two-loop version is cleaner when zeros are already near the end. 💬 In short: 👉 Both methods are correct. 👉 The 2-loop version is cleaner and beginner-friendly. 👉 The 1-loop swap version is efficient and teaches in-place thinking. Which one do you prefer — Classic Swap, Modern Destructuring, or Clean Two-Loop? 😄 Let’s discuss in comments 👇 #JavaScript #CodingJourney #FrontendDevelopment #DeveloperTips #LearnByDoing
To view or add a comment, sign in
-
💥 JavaScript Error Statements — When Things Go "Oops!" in Code 😅 Let’s be honest — we all make mistakes while coding. But the cool part? JavaScript doesn’t just crash and burn; it talks back! 🔊 It throws error statements to tell you what went wrong and where. --- 🧠 What Are Error Statements? Error statements in JavaScript are used to handle runtime errors gracefully. Instead of stopping your entire code, they help you catch issues and respond to them smartly. Example 👇 try { let num = 10 / 0; throw new Error("Division by zero is not allowed!"); } catch (error) { console.log(error.message); } 💬 Output: Division by zero is not allowed! --- ⚙️ Common Error Types You’ll See Here are a few “celebrities” of JavaScript errors: ReferenceError – Using a variable that doesn’t exist. TypeError – Doing the wrong thing with the wrong type. SyntaxError – Messed up your punctuation (oops!). RangeError – You asked for something outside the allowed range. EvalError – Something went wrong inside eval(). --- 💡 Why It Matters Catching errors properly makes your app: ✅ More stable ✅ Easier to debug ✅ User-friendly (no white screens of doom!) --- 🚀 Pro Tip Use try...catch...finally blocks wisely. They make you look like a coding superhero who can fix chaos before it spreads. 🦸♂️ --- 💬 So next time JavaScript screams “Error!”, smile. It’s just trying to help you write smarter code! 💻 #codecraftbyaderemi #webdeveloper #frontend #javascript #webdevelopment #learnJS
To view or add a comment, sign in
-
-
💡 JavaScript Series | Topic 6 | Part 4 — The Spread Operator: Immutable Operations Made Simple 👇 The spread operator (...) is one of the simplest yet most powerful tools in modern JavaScript. It takes an iterable (like an array or object) and spreads it out — as if each item were listed individually. This feature enables clean, immutable updates — essential for React, Redux, and functional programming patterns. 🧩 Array Spread const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; // Combine arrays const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6] // Clone an array const clone = [...arr1]; // [1, 2, 3] ✅ No mutation — arr1 and arr2 remain untouched. ✅ Great for merging and shallow copying arrays. ⚙️ Object Spread const defaults = { theme: 'dark', language: 'en' }; const userPrefs = { language: 'fr' }; // Merge objects const settings = { ...defaults, ...userPrefs }; console.log(settings); // { theme: 'dark', language: 'fr' } ✅ Later spreads overwrite earlier ones (language: 'fr' wins). ✅ Cleanly merges configuration objects or props without side effects. ✅ Perfect for immutable state updates in React: setState(prev => ({ ...prev, isLoading: false })); 💡 Why It Matters 🚀 Enables immutable updates without external libraries 🧩 Works across arrays, objects, and function arguments 💬 Keeps code clean, expressive, and predictable ⚙️ Under the hood, it performs a shallow copy — meaning nested objects remain referenced 💬 My Take: The spread operator is a small syntax with huge impact — it turns mutation-heavy logic into declarative, readable, and safe code. It’s a must-have tool for writing modern, maintainable JavaScript. ⚡ 👉 Follow Rahul R Jain for real-world JavaScript and React interview questions, hands-on coding examples, and performance-focused frontend strategies that help you stand out. #JavaScript #FrontendDevelopment #SpreadOperator #ES6 #Immutability #WebDevelopment #Coding #ReactJS #NodeJS #NextJS #TypeScript #InterviewPrep #ModernJavaScript #WebPerformance #DeveloperCommunity #RahulRJain #TechLeadership #CareerGrowth
To view or add a comment, sign in
-
🚀 Understanding the "Single Number" Problem (LeetCode 136) In JavaScript, there’s always something new to discover — even in simple-looking problems. Recently, I revisited the Single Number challenge and explored two different approaches: using a hash table and using XOR. 💡 Approach 1: Using a Hash Table We create an object that counts how many times each number appears. If a number appears once, that’s our answer. function singleNumber(arr) { let hash = {}; // frequency map for (let i = 0; i < arr.length; i++) { if (!hash[arr[i]]) hash[arr[i]] = 1; else hash[arr[i]]++; } for (let i = 0; i < arr.length; i++) { if (hash[arr[i]] === 1) return arr[i]; } } console.log(singleNumber([2, 2, 1])); // Output: 1 ⚡ Approach 2: Using XOR (bitwise logic) This approach is faster — duplicate numbers cancel each other out, leaving only the single one. function singleNumber(arr) { let xor = 0; for (let i = 0; i < arr.length; i++) { xor = xor ^ arr[i]; } return xor; } console.log(singleNumber([4, 1, 2, 1, 2])); // Output: 4 The XOR trick is elegant . 🧠 Quick Concepts 🔸 Hash Table (Object in JS): Think of it like a locker with labels — each label (key) stores a value. You can easily count or find things using those keys. Example: let hash = {}; hash["apple"] = 2; // apple appears twice 🔸 XOR (Exclusive OR): It’s a bitwise operation that gives: 1 if bits are different 0 if bits are same 👉 Same numbers cancel out: 2 ^ 2 ^ 1 = 1 That’s why XOR is a shortcut for finding the unique number! 🎯 Takeaway: Even a small problem can teach you how counting works in objects and how bitwise logic simplifies code. Learning by doing builds real understanding 💪 #JavaScript #CodingJourney #FrontendDevelopment #DeveloperTips #LearnByDoing
To view or add a comment, sign in
-
💡 Understanding this in JavaScript — Simplified for Every Developer If there’s one word that has confused almost every JS developer at least once… it’s 👉 this 😅 Let’s finally understand it clearly with simple examples 👇 ⸻ 🌍 1️⃣ In Global Scope this refers to the global object. In browsers → it’s the window object. console.log(this); // window ⸻ 🧭 2️⃣ Inside a Regular Function this depends on how the function is called. ✅ Non-strict mode → this becomes window. 🚫 Strict mode → this becomes undefined. function show() { console.log(this); } show(); // window (non-strict) or undefined (strict) ⸻ 🏹 3️⃣ Inside Arrow Functions Arrow functions don’t have their own this. They inherit it from their lexical scope (the place they are defined). const obj = { name: "JS", arrow: () => console.log(this), regular() { console.log(this); } }; obj.arrow(); // ❌ refers to outer scope (not obj) obj.regular(); // ✅ refers to obj ⸻ 🧱 4️⃣ Inside Objects When you call a function as a method, this refers to that object. const user = { name: "Vivek", greet() { console.log(`Hello, ${this.name}`); } }; user.greet(); // Hello, Vivek ⸻ 💬 5️⃣ Inside Event Listeners In event listeners, this refers to the DOM element that received the event. button.addEventListener('click', function() { console.log(this); // the button element }); ⸻ 🧠 In short: this in JavaScript doesn’t depend on where it’s written, it depends on how it’s called! ⚡ ⸻ 🚀 So remember: • Global scope → window • Regular function → depends on call & mode • Arrow function → lexical scope • Object method → that object • Event listener → DOM element ⸻ 💬 What was your “aha!” moment with this in JavaScript? Drop it in the comments 👇 — let’s make this less confusing for everyone 😄 ⸻ #JavaScript #WebDevelopment #Frontend #ReactJS #Coding #Developers #Programming #CodeNewbie #LearningJS #JSInterview #FrontendDevelopment #WebDev #CodingLife #SoftwareEngineering #100DaysOfCode #DevCommunity #JavaScriptTips #Tech #CodeWithVivek #DeveloperHumor #ES6 #AsyncJS #CodingFun #ThisKeyword #JSConcepts
To view or add a comment, sign in
-
-
🚀 #Day6 Challenge — Mastering JavaScript Prototypes & Prototype Chaining. Today’s deep dive was all about one of the core pillars of JavaScript — Prototypes and Prototype Chaining 🧠 I explored how every JavaScript object has an internal link to another object called its prototype, and how properties & methods are inherited through the prototype chain. Here’s what I learned today 👇 ✅ How functions in JS automatically get a .prototype object ✅ How object instances share methods using prototypes (memory-efficient inheritance) ✅ What happens when JS looks for a property — and how it walks up the chain (Prototype Lookup) ✅ The difference between __proto__ and .prototype ✅ How to manually create inheritance using Object.create() ✅ Real-world examples like Library System, E-commerce Product System, and Employee Management System built using prototypes and chaining // Creating a Employee Management System with raise using constructor function and prototype methods function Employee(name, salary, department) { this.name = name; this.salary = salary; this.department = department; } Employee.prototype.getDetails = function() { console.log(`// Name: ${this.name} | Department: ${this.department} | Salary: ₹${this.salary}`); }; Employee.prototype.giveRaise = function(percent){ this.salary += this.salary*percent/100; console.log(`New salary for ${this.name} is ₹${this.salary}`); }; const emp1 = new Employee('Rahul',5000,'IT'); const emp2 = new Employee('Rahul',5000,'IT'); emp2.getDetails(); emp2.giveRaise(10); 💡 Key Takeaway: Prototypes are the backbone of JavaScript’s inheritance — understanding them gives true control over how objects behave and interact. 📘 Next up: Moving toward “Classes & Inheritance in ES6” — where I’ll connect prototypes with modern class syntax for cleaner, scalable code. #JavaScript #Prototypes #PrototypeChaining #Day6Challenge #WebDevelopment #LearnInPublic #FrontendDeveloper #CodingJourney #AsyncJavaScript #Closures #Scopes #LexicalEnvironment #DeveloperGrowth #100DaysOfCode #BuildInPublic
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