🚀 *Quick JavaScript Tip: Cleaner Array & Object Checks* Stop using the old-school "length" check to guard your code. ❌ *Old way* : "persona.length > 0 && persona[0]" ✅ *Modern way* (Optional Chaining): "persona?.[0]" 💡 *Why switch?* ✅ *Cleaner* – Less code, better readability ✅ *Safer* – Prevents crashes if "persona" is "null" or "undefined" ✅ *Robust* – Returns "undefined" instead of throwing a "TypeError" 📊 Very useful when working with API responses where data may be unpredictable. 🔹 *Pro Tip* : Works great for deeply nested objects too. Example: "user?.profile?.address?.city" Happy coding! 💻✨
JavaScript Cleaner Array & Object Checks with Optional Chaining
More Relevant Posts
-
Most developers think encapsulation in JavaScript is just about “hiding variables.” It’s more than that. Encapsulation is about controlling access and protecting your logic. 💡 In simple terms: 👉 Keep data safe 👉 Expose only what’s necessary 🔹 1. Using Closures (Classic Way) function createCounter() { let count = 0; return { increment() { count++; console.log(count); }, getCount() { return count; } }; } const counter = createCounter(); counter.increment(); // 1 counter.increment(); // 2 console.log(counter.count); // ❌ undefined ✔ count is private ✔ Accessible only through methods 🔹 2. Using Classes + Private Fields (Modern JS) class BankAccount { #balance = 0; deposit(amount) { this.#balance += amount; } getBalance() { return this.#balance; } } const acc = new BankAccount(); acc.deposit(1000); console.log(acc.getBalance()); // 1000 console.log(acc.#balance); // ❌ Error ✔ True private fields ✔ Cleaner and structured ⚡ Why encapsulation matters: • Prevents accidental data changes • Makes code more secure • Improves maintainability • Creates clear boundaries in your system 🧠 The real shift: Don’t just write code that works. Write code that protects itself. What’s your go-to pattern for encapsulation in JavaScript—closures or private fields? 👇 #JavaScript #WebDevelopment #Programming #Frontend #Coding #SoftwareEngineering
To view or add a comment, sign in
-
Three dots that changed JavaScript: ... The spread operator in action: Arrays: // Copy const copy = [...original] // Merge const all = [...arr1, ...arr2] // Add items const updated = [...items, newItem] Objects: // Copy const clone = { ...user } // Merge const combined = { ...defaults, ...config } // Update const modified = { ...user, age: 30 } Function calls: Math.max(...numbers) fetch(url, { ...defaultOptions, ...customOptions }) Before spread operator: const copy = original.slice() const merged = Object.assign({}, obj1, obj2) fn.apply(null, args) After spread operator: const copy = [...original] const merged = { ...obj1, ...obj2 } fn(...args) The magic: → No mutation (safer code) → Cleaner syntax → Works with any iterable → Essential for React state → Makes immutability easy Three dots. Infinite possibilities.
To view or add a comment, sign in
-
𝗗𝗲𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗶𝗻𝗴 𝗜𝗻 𝗝𝗮 v𝗮𝗦𝗰𝗿𝗶𝗽𝘁 Destructuring in JavaScript reduces code verbosity and speeds up writing array or object data manipulation. You can use it with arrays and objects to see its features and advantages. It is a special syntax for unpacking array items or object property access. This provides a concise way to reduce code verbosity without modifying the original data. To destructure an array, use square brackets on the left side and put the array reference on the right side. You can catch items in variables. - const items = ["apple", "ball", "cat"] - const [first, second, third] = items - console.log(first) // apple - console.log(second) // ball - console.log(third) // cat You can skip values by using extra commas: - const [first, , third] = items - console.log(first) // apple - console.log(third) // cat Object destructuring is similar, but uses curly brackets and catches properties by their actual keys. - const user = {name: "anoop", age: 21} - const {name, age} = user - console.log(name) // anoop - console.log(age) //
To view or add a comment, sign in
-
🧩𝗦𝗶𝗺𝗽𝗹𝗶𝗳𝘆𝗶𝗻𝗴 𝗡𝗲𝘀𝘁𝗲𝗱 𝗗𝗮𝘁𝗮 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 Working with deeply nested arrays is a common challenge in JavaScript- especially when data structures start getting complex. To address this, I explored array flattening in depth and documented my learnings: “𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗔𝗿𝗿𝗮𝘆 𝗙𝗹𝗮𝘁𝘁𝗲𝗻𝗶𝗻𝗴 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁” https://lnkd.in/gdzX7d5Z 🔍 What’s covered in the blog: 🔹 How the .flat() method works in JavaScript 🔹 Handling different levels of nesting effectively 🔹 Writing a custom polyfill to understand the underlying mechanics Hitesh Choudhary Piyush Garg Anirudh J. Chai Aur Code Akash Kadlag Suraj Kumar Jha Nikhil Rathore Jay Kadlag DEV Community #Chaicode #Cohort #JavaScript #WebDevelopment #TechnicalWriting #CleanCode #LearningInPublic #Chaicode
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗨𝗹𝗧𝗶𝗺𝗮𝗧𝗲 𝗚𝗨𝗶𝗱𝗲 𝗧𝗼 𝗔𝗿𝗿𝗮𝗬 𝗙𝗟𝗔𝗧𝗧𝗘𝗡𝗜𝗡𝗚 You work with arrays in JavaScript, but they can get nested and hard to use. That's where array flattening comes in. A nested array is an array inside another array. For example: - `[3, 4]` is a nested array - `[5, [6, 7]]` is a deeply nested array Flattening converts a nested array into a single-level array. You can use array flattening in: - API responses with nested data - Data processing and transformation - Simplifying loops and operations - Preparing data for UI rendering There are different ways to flatten arrays: - Using `flat()` - the easiest way in modern JavaScript - Using recursion - important for interviews - Using a stack - an iterative approach When solving flatten problems, think: - Is recursion needed? - Can I reduce complexity? - What is the depth? - Should I preserve order? Array flattening is a must-know concept in JavaScript. It strengthens recursion skills, improves problem-solving ability, and appears frequently in interviews. Source: https://lnkd.in/grRq_v3K
To view or add a comment, sign in
-
🚀 JavaScript Trick — structuredClone() Native Deep Cloning (No more JSON hacks!) Most developers still do this to deep clone an object: const clone =JSON.parse(JSON.stringify(obj)); But this approach breaks on: ❌ Date objects → converts to string ❌ undefined values → gets removed ❌ Functions → silently dropped ❌ Infinity, NaN → becomes null ❌ Circular references → throws an error ✅ Meet structuredClone() — built into modern JS: const original = { name: "Bob", born: new Date("1995-12-05"), scores: [10, 20, 30], meta: undefined }; const clone = structuredClone(original); clone.scores.push(60); clone.name=“Alice”; console.log(original.name); // "Bob" ✅ not affected console.log(original.scores); // [10, 20, 30] ✅ not affected console.log(clone.born); // Date object ✅ not a string! console.log(clone.meta); // undefined ✅ preserved! structuredClone() handles what JSON.parse() can't: ✅ Dates stay as Date objects ✅ undefined values are preserved ✅ Circular references work fine ✅ Faster performance overall 📦 No lodash. No JSON tricks. Just one clean native method. Available in Node 17+, Chrome 98+, Firefox 94+ #JavaScript #WebDevelopment #JSTips #Frontend #Programming
To view or add a comment, sign in
-
𝗪𝗵𝗮𝘁'𝘀 𝗗𝗧𝗢𝘀 𝗶𝗻 𝗡𝗲𝘀𝘁 𝗷𝘀 In NestJS, a 𝗗𝗧𝗢 (Data Transfer Object) is an object that defines how data is sent over the network. Think of it as a contract or a blueprint that specifies exactly what data a client (like a mobile app or a browser) must send to your server. While DTOs are a general software pattern, NestJS uses them powerfully to handle validation and type safety. 𝟭. 𝗪𝗵𝘆 𝗱𝗼 𝘄𝗲 𝘂𝘀𝗲 𝗗𝗧𝗢𝘀? Without a DTO, your application wouldn't know if the incoming data is correct. If a user tries to register but sends a "username" as a number instead of a string, your database might crash. DTOs help prevent this by: 𝗩𝗮𝗹𝗶𝗱𝗮𝘁𝗶𝗼𝗻: Ensuring the data has the right format, length, and type. 𝗗𝗮𝘁𝗮 𝗧𝗿𝗮𝗻𝘀𝗳𝗼𝗿𝗺𝗮𝘁𝗶𝗼𝗻: Stripping away unwanted data that the client shouldn't be sending (e.g., trying to set their own isAdmin status). 𝗧𝘆𝗽𝗲 𝗦𝗮𝗳𝗲𝘁𝘆: Providing IntelliSense and auto-completion in your code so you know exactly what properties exist on the request body. 𝟮. 𝗖𝗹𝗮𝘀𝘀𝗲𝘀 𝘃𝘀. 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲𝘀 In NestJS, it is highly recommended to use Classes for DTOs rather than Interfaces. 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲𝘀 are removed during JavaScript compilation, meaning NestJS cannot check them at runtime. 𝗖𝗹𝗮𝘀𝘀𝗲𝘀 are preserved in the final code, allowing NestJS to use Pipe validation to check data as it arrives. #Programming #BackendDevelopment #TypeScript #NestJS
To view or add a comment, sign in
-
🚀 Understanding Flattening of Nested Arrays in JavaScript While working on problem-solving, I explored an interesting concept: flattening nested arrays using recursion. 👉 Often, data is not always in a simple structure. We may encounter arrays inside arrays (nested arrays), and to process them effectively, we need to convert them into a single-level array. 💡 Key Concept Used: Recursion ➤Recursion is a technique where a function calls itself. ➤It helps solve problems that can be broken down into smaller, similar sub-problems. 🔍 Approach: ➤Traverse each element of the array. ➤Check whether the current element is an array or a normal value. ➤If it’s a nested array, recursively process it. ➤If it’s a normal value, store it directly. ➤Finally, combine all values into a single flattened array. 📌 Why this is important: ➤Helps in handling complex data structures. ➤Improves problem-solving and logical thinking. ➤Frequently asked in coding interviews (especially for JavaScript developers). 🎯 Example Use Cases: ➤Processing API responses with nested data ➤Data transformation tasks ➤Preparing data for UI rendering ✨ What I learned: ➤How recursion simplifies complex problems ➤Importance of breaking problems into smaller steps ➤Writing clean and reusable logic #JavaScript #Recursion #ProblemSolving #WebDevelopment #FrontendDevelopment #CodingJourney #LearnToCode
To view or add a comment, sign in
-
-
Day 2/30 — JavaScript Journey Data Types + Operators = JavaScript’s Reality Engine If you don’t understand this… JavaScript will feel broken forever. Most developers think: 👉 “JS is weird” Truth: 👉 JS is consistent. You’re just missing the model. 🧠 It’s Simple: 1. Data Types → What you have Primitive → value (safe, copied) Reference → memory (shared, mutable) 2. Operators → What JS does with it ⚡ Where things break: "5" + 2 // "52" "5" - 2 // 3 👉 Same data. Different operator. Different world. ⚡ The Rule: If a string is involved → + becomes concatenation Other operators → force numbers ⚡ The Trap: 0 == false // true 😬 0 === false // false ✅ 👉 == lies (coercion) 👉 === tells truth 💥 The Shift: Stop memorizing syntax. Start tracking data types + operators together 🚀 Final Line: JavaScript isn’t unpredictable… Your understanding is. Master this → You unlock debugging, interviews, and clean code instantly.
To view or add a comment, sign in
-
-
- Temporal API: Replace every date library with this. Immutable, timezone-aware, no zero-indexed months. - using / await using: Stop writing try/finally for resource cleanup. Add [Symbol.dispose] to your resource types. - Error.isError(): Use this instead of instanceof Error in catch blocks, especially in library code. - Array.fromAsync(): Collect async iterables into arrays in one line. - Import attributes: Explicitly type your JSON and CSS imports. - Math.sumPrecise(): Precise floating point summation for when it matters. None of these require rewriting your existing codebase. Start using them in new code, add the polyfills where you need them, and watch the category of bugs each one addresses stop appearing in your projects. https://lnkd.in/gxbwbYgk
To view or add a comment, sign in
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