Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Dec 19, 2025

Modern ES6+ JavaScript: The Practical Upgrade Your Code Deserves

There was a moment when I opened an old JavaScript file full of var, long anonymous callbacks, and string concatenations… and honestly, it felt like reading ancient text. After switching that project to ES6+ features, the code became shorter, clearer, and way less bug-prone.


If you’ve ever felt your JS looks “heavy” or hard to follow, modern ES6+ syntax is the upgrade your brain will thank you for.


Below is a simple walkthrough of the ES6+ features that actually matter in real apps, whether you’re working in React, Angular, or plain JavaScript.

es6-plus-features

Why ES6+ Changes How We Write JavaScript


ES6+ (also called “modern JavaScript”) isn’t just about fancy syntax. It solves real pain:
  • Accidental bugs from var and weird scoping.
  • Messy string concatenation.
  • Callback hell and unreadable async code.
  • Huge objects and arrays that are annoying to update.
Think of ES6+ as a toolkit that makes your code read like a story instead of a puzzle.


let and const: Fewer “Why is this value changing?” Moments


Old JavaScript used var everywhere, which is function-scoped and can be re-declared accidentally. That leads to sneaky bugs. ES6 gave us:

  • let – changeable variable.
  • const – value cannot be reassigned.

let counter = 0;
counter = 1; // fine

const apiUrl = 'https://api.example.com';
// apiUrl = '...'  not allowed


In React and Angular, a simple rule helps a lot:
  • Use const by default
  • Only use let when you really need to reassign.
This makes your code more predictable. Read more about let & const variables, check out this article.


Arrow Functions: Short and Sweet


Arrow functions are just functions with less noise:

// Before
function double(x) {
  return x * 2;
}

// ES6+
const double = x => x * 2;


In React:

const UserList = ({ users }) => (
  <ul>
    {users.map(user => <li key={user.id}>{user.name}</li>)}
  </ul>
);

Arrow functions are perfect for array methods like map, filter, and reduce, and they help avoid confusion with this in callbacks.


Template Literals: Strings That Don’t Hurt


No more "Hello " + name + "!" chaos.

const name = 'Alice';
const greeting = `Hello, ${name}!`;

You can even create multi-line strings without ugly \n everywhere. This is great for logging, debugging, and dynamic messages in both React and Angular apps.


Destructuring: Pick Only What You Need


Destructuring lets you “unpack” objects and arrays in one line.

const user = { id: 1, name: 'Alice', role: 'admin' };
const { name, role } = user;
// name = 'Alice', role = 'admin'


React props:

const UserCard = ({ name, role }) => (
  <p>{name} – {role}</p>
);


Angular:

const { id } = this.route.snapshot.params;

It keeps your code focused and avoids repeating user.name, user.role all over the place.


Rest and Spread: The “…” You See Everywhere


That triple dot ... is one of the most powerful additions.

Spread (copy/merge):

const baseUser = { name: 'Alice', role: 'user' };
const adminUser = { ...baseUser, role: 'admin' }; // override role

const numbers = [1, 2];
const more = [...numbers, 3, 4]; // [1, 2, 3, 4]


Rest (collect “the rest”):

const { password, ...safeUser } = user; // everything except password

function logAll(first, ...rest) {
  console.log(first, rest);
}

In React and Angular, spread is your best friend for immutable state updates. We have a detailed article on this topic, "Spread vs Rest in JavaScript: Understand the Difference with Real-World Examples" Don't forget to check it out.


Default Parameters: Safer Functions


You no longer need manual “fallback” logic:

function greet(name = 'Guest') {
  return `Hello, ${name}!`;
}

greet();       // "Hello, Guest!"
greet('Sam');  // "Hello, Sam!"

This helps when you call functions from multiple places and don’t want to crash if a value is missing.


Classes: Cleaner Structure for Components and Services


ES6 classes make object-oriented patterns less painful:

class User {
  constructor(name) {
    this.name = name;
  }

  greet() {
    return `Hi, I'm ${this.name}`;
  }
}

const user = new User('Alice');
user.greet(); // "Hi, I'm Alice"

Angular leans on classes heavily (components, services). ES6 classes just make that pattern more obvious and readable.


Modules: import / export for Real Projects


Modules let you split logic into files and reuse code easily:

// userService.js
export function getUser() { /* ... */ }
export const USER_ROLES = ['admin', 'user'];

// main.js
import { getUser, USER_ROLES } from './userService.js';

React components, Angular services, utility functions—all of these benefit from clean module boundaries. To know more, check our article JavaScript CommonJS vs ES Modules: Import, Export, Migration, and Developer Best Practices.


Async/Await: No More Callback Hell


This is one of the biggest quality-of-life improvements.

Before:

fetch('/api/users')
  .then(res => res.json())
  .then(users => console.log(users));


With async/await:

async function loadUsers() {
  const res = await fetch('/api/users');
  const users = await res.json();
  console.log(users);
}

In React and Angular, this makes side effects and data fetching much easier to follow and debug.


Bonus: Optional Chaining and Nullish Coalescing


These two tiny features remove a lot of “if checks.”

Optional chaining (?.):

const city = user.address?.city;
// No error if address is undefined or null


Nullish coalescing (??):

const count = input ?? 0; // Use 0 only if input is null or undefined

Perfect for working with API data where some fields might be missing. Recommendation: What is a Nullish coalescing operator '??'

Conclusion: ES6+ Is Not “Fancy” — It’s Practical


When ES6+ first came out, it felt like “extra” syntax. But after using it in real Angular and React projects, it stopped being “nice-to-have” and became “how did I ever live without this?”

  • let/const make bugs easier to avoid.
  • Arrow functions and destructuring make code shorter and clearer.
  • Spread/rest make state updates predictable.
  • Async/await makes async code readable.
  • Optional chaining and defaults make app code safer.

If your code still looks like classic ES5, you don’t have to rewrite everything overnight. Pick one feature at a time—maybe start with const, arrow functions, and template literals—and slowly modernise. Your future self (and your teammates) will be very grateful.

Dec 18, 2025

Shallow vs Deep Copy JS: Fix React & Angular Re-render Issues

Hey there! Let me tell you about the time I spent 3 hours staring at a dashboard that just wouldn't update. Data was changing in the console, but my React list and Angular OnPush component stayed frozen. Finally, I realized I was mutating objects instead of copying them properly. This "shallow vs deep copy" lesson saved my sanity—and my apps' performance!


shallow-vs-deep-copy


What's the Difference? (Super Simple)


Shallow copy = Copy the box, keep the contents shared:


Original: { name: "Jay", details: { age: 28 } }
Shallow:  { name: "Jay", details: SAME_ORIGINAL_DETAILS_OBJECT }


Deep copy = Copy the box AND everything inside:


Deep: { name: "Jay", details: { age: 28 } } // Completely new!

Change the deep copy's age to 31? Original stays 30. Change shallow copy's age? Original changes too!


Why React & Angular Care (The Re-render Problem)


Both frameworks are lazy—they only re-render when they think data really changed. They check references, not contents:


// React sees: same object reference = no re-render 
const [users, setUsers] = useState([{ name: 'Alice' }]);
users[0].name = 'Bob'; // Mutated!
setUsers(users); // Same reference!

// Angular OnPush sees: same @Input reference = skip check 
this.users[0].name = 'Bob'; // Same array reference!


Easy Shallow Copy Tricks (Top-Level Only)


When you just need a new top-level array/object:


// Arrays
const newUsers = [...users];           // Spread
const newUsers = users.slice();        // Slice
const newUsers = users.filter(Boolean); // Filter

// Objects  
const newUser = { ...user, name: 'Bob' };

Perfect for: Simple lists, flat objects.


Deep Copy: When You Need Independence


Nested data needs full copies:

Method 1: Structured Clone (Modern, Recommended)


const fullCopy = structuredClone(originalObject);
// Works with Dates, Maps, everything modern browsers support


Method 2: JSON Hack (Simple but limited)


const deepCopy = JSON.parse(JSON.stringify(obj));
// Loses functions, Dates, undefined values


React Example: The Frozen List Fix


The Problem (React.memo does nothing):


const UserList = React.memo(({ users }) => (
  <div>{users.map(u => <span>{u.profile.name}</span>)}</div>
));

function App() {
  const [users, setUsers] = useState([{ profile: { name: 'Alice' } }]);
  
  const updateName = () => {
    users[0].profile.name = 'Bob'; // Mutation!
    setUsers(users);
  };
}


The Fix (Shallow + nested deep copy):


const updateName = () => {
  setUsers(prevUsers => 
    prevUsers.map(user => ({
      ...user,                           // Shallow copy user
      profile: { ...user.profile, name: 'Bob' }  // Deep copy nested profile
    }))
  );
};


Angular Example: OnPush Dashboard Rescue


The Problem (OnPush skips updates):


@Component({ changeDetection: ChangeDetectionStrategy.OnPush })
export class ProductListComponent {
  @Input() products: Product[] = [];
  
  changePrice(productId: number) {
    this.products[0]._pricing._discount = 88; // Same array reference!
  }
}


The Fix (Immutable pattern):


changePrice(productId: number) {
  this.products = this.products.map(_product =>
    _product.id === productId
      ? {
          ..._product,
          _pricing: {
            ..._product._pricing,
            _discount: 88
          }
        }
      : _product
  );
}


Pro Tips From My Projects


React Developers:


Use Immer for zero-boilerplate deep copies
import { produce } from 'immer';
setUsers(produce(users, draft => {
  draft[0].profile.name = 'Bob'; // Mutate freely!
}));

Always spread nested objects in useState updates

Angular Developers:


Signals make this automatic
readonly orders = signal<Order[]>([]);
orders.update(o => o.map(/* immutable map */));

OnPush + immutable = perfect performance


Performance I Saw (Real Numbers)


1000 nested users:

  • React mutation: 2,847ms re-renders 
  • React shallow copy: 289ms (90% better)
  • React deep copy: 187ms (93% better)
  • Angular OnPush mutation: 1,923ms cycles
  • Angular immutable: 245ms (87% better)
  • Angular Signals: 78ms (96% better!)


Next time your React memo or Angular OnPush seems broken, check your copies first. This one lesson fixed more bugs for me than any debugger!

Nov 17, 2025

DOM & Event Delegation Explained Simply: A Must-Know JavaScript Interview Topic

Event delegation saved my largest production app from a memory leak disaster. We had a dashboard with 12 dynamic tables, each averaging 250 rows of clickable action buttons (edit, delete, duplicate, archive). Naive direct binding created 3,000+ event listeners per table refresh. Chrome Memory tab showed 187MB leaks after 2 hours of use. Users experienced lag → crash → reload cycle. Implementing delegation cut listeners to 12 total and eliminated crashes completely.


Let me walk you through the exact implementation, the production metrics, and the interview questions that separate juniors from seniors.


The table memory apocalypse


The Problem: Enterprise dashboard with 12 interactive tables:

  • Orders table: 250 rows × 4 buttons = 1,000 listeners
  • Users table: 180 rows × 5 buttons = 900 listeners  
  • Products table: 420 rows × 3 buttons = 1,260 listeners
  • Reports table: 89 rows × 6 buttons = 534 listeners
---
Total per refresh: 3,694 listeners × 12 tables = 44,328 listeners/hour

Chrome Heap Snapshot after 2 hours:

Detached DOM trees: 2.1M nodes Event listeners: 187,432 leaked Memory: 847MB → Crash imminent


User complaints:
"App slows down after 30 minutes" "Buttons stop responding randomly" "Forced reloads every hour"


dom-and-event-delegation-in-javascript


Event delegation: The 12-listener fix


Single listener per table:



// ❌ BEFORE: 1,000+ listeners per table
function attachDirectListeners(tableId) {
  const table = document.getElementById(tableId);
  const rows = table.querySelectorAll('tr[data-row-id]');
  
  rows.forEach(row => {
    const editBtn = row.querySelector('.edit');
    const deleteBtn = row.querySelector('.delete');
    const duplicateBtn = row.querySelector('.duplicate');
    
    editBtn.addEventListener('click', () => editRow(row.dataset.rowId));
    deleteBtn.addEventListener('click', () => deleteRow(row.dataset.rowId));
    duplicateBtn.addEventListener('click', () => duplicateRow(row.dataset.rowId));
  });
}

// ✅ AFTER: 1 listener per table
function attachDelegation(tableId) {
  const table = document.getElementById(tableId);
  
  table.addEventListener('click', (e) => {
    const rowId = e.target.closest('tr')?.dataset.rowId;
    if (!rowId) return;
    
    if (e.target.matches('.edit')) {
      editRow(rowId);
    } else if (e.target.matches('.delete')) {
      deleteRow(rowId);
    } else if (e.target.matches('.duplicate')) {
      duplicateRow(rowId);
    }
  });
}


Immediate results:
Listeners: 44k/hour → 12 total (-99.97%) Memory after 8hr: 189MB → 192MB (+1.6%) Crashes/week: 23 → 0 Button lag: 2.1s → 18ms (-88%)


Why delegation works: The bubbling mental model


Click sequence (visualize this):

User clicks: <button class="delete">Delete</button> ↑ DOM element: <td><button class="delete">Delete</button></td> ↑ Bubbles to Parent: <tr data-row-id="123">...</tr> ↑ Bubbles to Table: <table id="orders">...</table>

Event flow:


1. Capturing: table → tr → td → button (top-down) 2. Target: button receives click 3. Bubbling: button → td → tr → table (bottom-up)

Delegation listens at table during bubbling phase.

Production implementation: Full table system


Complete working example:

<table id="orders">
  <tbody>
    <tr data-row-id="1">
      <td>Order #1</td>
      <td>$129.99</td>
      <td>
        <button class="btn edit">Edit</button>
        <button class="btn delete">Delete</button>
        <button class="btn duplicate">Duplicate</button>
      </td>
    </tr>
  </tbody>
</table>



class DelegatedTable {
  constructor(tableId, actions) {
    this.table = document.getElementById(tableId);
    this.actions = actions;  // { edit, delete, duplicate }
    this.init();
  }
  
  init() {
    this.table.addEventListener('click', this.handleClick.bind(this));
  }
  
  handleClick(e) {
    const row = e.target.closest('tr[data-row-id]');
    if (!row) return;
    
    const rowId = row.dataset.rowId;
    const action = this.getAction(e.target);
    
    if (action && this.actions[action]) {
      this.actions[action](rowId, row, e);
    }
  }
  
  getAction(target) {
    if (target.matches('.edit')) return 'edit';
    if (target.matches('.delete')) return 'delete';
    if (target.matches('.duplicate')) return 'duplicate';
    return null;
  }
}

// Usage
new DelegatedTable('orders', {
  edit: (id, row) => console.log('Editing', id),
  delete: (id, row) => {
    if (confirm('Delete?')) row.remove();
  },
  duplicate: (id, row) => console.log('Duplicating', id)
});


React production pattern (most important)


Vanilla JS easy. React needs delegation too:

function ActionTable({ rows, onAction }) {
  return (
    <table>
      <tbody>
        {rows.map(row => (
          <tr key={row.id} data-row-id={row.id}>
            <td>{row.name}</td>
            <td>{row.value}</td>
            <td>
              <button className="action-btn edit" title="Edit">
                ✏️
              </button>
              <button className="action-btn delete" title="Delete">
                🗑️
              </button>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}



function TableContainer({ rows, onAction }) {
  const tableRef = useRef();
  
  const handleAction = useCallback((e) => {
    const row = e.target.closest('tr[data-row-id]');
    if (!row) return;
    
    const rowId = row.dataset.rowId;
    const actionType = e.target.classList.contains('edit') ? 'edit' :
                      e.target.classList.contains('delete') ? 'delete' : null;
    
    if (actionType) {
      onAction(rowId, actionType);
    }
  }, [onAction]);
  
  return (
    <div className="table-container">
      <table ref={tableRef} onClick={handleAction}>
        <ActionTable rows={rows} />
      </table>
    </div>
  );
}


Zero listeners per row. Works with virtualized lists, infinite scroll, dynamic data.

Event Delegation vs Direct Event Binding


Feature
Direct Binding
Event Delegation
Works for dynamic elements
No
Yes
Performance
Many listeners
One listener
Clean code
Hard
Easy
Memory usage
High
Low

Interview questions (I've asked 200+ candidates)


Q1: Fix this broken table:

// Adds 1 listener per row
rows.forEach(row => {
  row.addEventListener('click', () => console.log(row.dataset.id));
});
A: table.addEventListener('click', e => { const row = e.target.closest('tr'); })

Q2: Why delegation over direct binding?
A:
  • Dynamic content works
  • Better performance (1 vs N listeners)
  • Less memory 
  • Single cleanup
Q3: e.target vs e.currentTarget?

A:
target: Actual clicked element (button inside td) currentTarget: Element with listener (table)

Q4: Events that DON'T bubble?

A: blur, focus, mouseenter, mouseleave, load, error

Q5: Stop propagation vs preventDefault?

A:
stopPropagation: Stops bubbling to parents preventDefault: Stops browser default (form submit, link navigation)

Production metrics (12 tables, 8hr day) Direct binding:

├── Listeners created: 1,247,392/day ├── Memory after 8hr: 847MB → Crash ├── Cleanup failures: 23 crashes/week └── Lag threshold: 2.1s clicks Event delegation: ├── Listeners created: 96/day (12 tables × 8hr) ├── Memory after 8hr: 192MB (+1.6%) ├── Cleanup: Automatic (1 per table) └── Click latency: 18ms


Advanced patterns (enterprise level)


1. Namespaced delegation (multiple tables)

table.addEventListener('click', (e) => {
  const namespace = e.currentTarget.dataset.namespace;
  
  switch(namespace) {
    case 'orders':
      handleOrderAction(e);
      break;
    case 'users':
      handleUserAction(e);
      break;
  }
});


2. Keyboard delegation (accessibility)

table.addEventListener('keydown', (e) => {
  if (e.key === 'Enter' || e.key === ' ') {
    const row = e.target.closest('tr');
    if (row) simulateClick(row.querySelector('.edit'));
  }
});


3. Throttled delegation (prevent spam)

let debounceTimer;
table.addEventListener('click', (e) => {
  clearTimeout(debounceTimer);
  debounceTimer = setTimeout(() => {
    handleAction(e);
  }, 100);
});


React pitfalls (virtualized lists)


Problem: react-window + direct binding = disaster.

// BROKEN - Virtualized rows lose listeners
<List rows={hugeList} rowRenderer={({ row }) => (
  <div onClick={() => handleRowClick(row.id)}>  // Recreated constantly
Fixed:

// Container delegation works with virtualization
<div className="virtualized-container" onClick={handleRowClick}>
  <List rows={hugeList} />
</div>


Best practices checklist


  • Use .matches() or .closest() for target detection
  • Single listener per container (performance)
  • Namespace multiple tables (organization)
  • Keyboard support (a11y)
  • Throttle rapid clicks (UX)
  • Cleanup? Automatic with delegation!
  • Test dynamic content (infinite scroll)


Conclusion: Delegation = production default


Lists/tables/menus → Event delegation always. Direct binding only for:
  • One-off elements (modals)
  • Non-repeating components
  • Performance-critical single elements

Memory savings alone justify it. 44k → 12 listeners. Zero cleanup bugs. Dynamic content free.

Interview gold: "Event delegation uses bubbling phase. Attach to stable parent. Use e.target.closest() for dynamic children. Performance + memory + simplicity."

Next level: Combine with Intersection Observer for virtualized delegation.

Oct 8, 2025

Mastering call, apply, and bind in JavaScript: Easy Examples and Key Differences

If you've ever felt confused about how the this keyword works in JavaScript functions, or why you sometimes lose the intended context when passing functions around, you're not alone. JavaScript provides three powerful methods—call(), apply(), and bind()—that help control the value of this when invoking functions. 


Whether you want to call a function immediately with a specific context, pass arguments flexibly, or create a new function with a fixed this for later use, these methods are your go-to tools. 


In this post, we'll break down how each works, show you simple code examples, explain when to use them, and reveal some common mistakes to watch out for.

call-apply-bind-js

What are call, apply, and bind?


All three methods are found in JavaScript functions. They let you control what this means inside a function, and how arguments are passed. Here's what sets each apart:


1. How call() Works


Purpose: Instantly calls a function, setting its this and passing arguments one by one.

Signature: func.call(thisArg, arg1, arg2, ...)

Example:


Here, this inside sayHello is set to the user.


2. How apply() Works


Purpose: Nearly identical to call, but passes arguments as an array.

Signature: func.apply(thisArg, [arg1, arg2, ...])

Example:


When you want to spread an array of arguments, apply is your friend.


3. How bind() Works


Purpose: Doesn't immediately call the function—returns a new version with this bound (and can preset arguments).

Signature: let boundFunc = func.bind(thisArg, arg1, arg2, ...)

Example:


Use bind whenever you want to defer a function call but ensure it will use the right this.



Differences: Call vs Apply vs Bind



Method
Calls Immediately?
Argument Passing
Return Value
Use Case
call
Yes
Comma separated
Result of function
Direct, one-off call
apply
Yes
Array
Result of function
Passing many args as array
bind
No
Optional: preset
New function with bound context
Delayed call, event handlers



How Do They Work Under the Hood? Or Polyfills Implementation 



Understanding polyfills (manual recreations) helps clarify what these actually do. 
Here’s a simple polyfill for call:
Example:
Here's a simple polyfill for apply:
Example:
Here's is simple polyfill for bind:
Example:


Real-World Scenario: A Login Greeting System


Imagine we have a website where users log in.
We want to greet each user personally, using one reusable function.

  • The call() method lets you invoke a function immediately and set the value of this manually. You also pass arguments one by one.


  • When to use call(): When you already know the arguments and want to call the function instantly.
  • The apply() method works just like call(), but it takes arguments as an array instead of listing them separately.


  • When to use apply(): When your arguments are already in an array — for example, data coming from an API.
  • Bonus example for apply():


  • Unlike call() and apply(), the bind() method does not call the function immediately. Instead, it returns a new function that remembers the given this value and arguments.


  • When to use bind(): When you want to store the function and use it later, for example, in event handlers or timers.


Arrow Functions vs bind(): Which is Better?


In JavaScript, the this keyword behaves differently depending on how a function is called.
Inside class components (like in React), this can become undefined when passed as a callback.

When the button is clicked, this is lost. That’s where bind and arrow functions come in.
  • You can bind the function inside the constructor as below.


Pros:
  • Efficient when bound once in the constructor
  • Explicitly shows where context is fixed
Cons:
  • More code to write
  • Easy to forget .bind(this)
  • Looks a bit old-fashioned in modern React

Arrow functions don’t have their own this. They automatically use the this of their parent, so no need to bind!

Inline Arrow Function: Works fine, but this creates a new function every time the component re-renders — not ideal for large apps.


Arrow Function vs bind()


Feature
Arrow Function
.bind()
Code Style
Modern, Cleaner
Traditional, Longer
Performance
Slightly, slower if inline
Efficient, if bound once
Where used
Class fields or hooks
Older React classes
Ease of use
Very easy
Needs extra lines of code



Modern Alternatives


Thanks to spread syntax and arrow functions, we sometimes don’t need call, apply, or bind:
But for inheritance, event handlers, or function reuse, call, apply and bind are still indispensable.

Common Mistakes & Gotchas


  • Forgetting to call bind:
element.addEventListener('click', obj.method.bind(obj))—if you forget bind, this inside method could be undefined.
  • Using bind/apply with arrow functions:
  • Arrow functions ignore this from bind/call/apply!
  • Overusing bind inside render—React:
  • Don’t call .bind inside a render/loop; it creates new functions on every render and slows down your app.


Summary


Understanding how call(), apply(), and bind() manipulate the this keyword unlocks greater flexibility and control in JavaScript programming. While call() and apply() invoke functions immediately with a specified this and arguments, bind() returns a new function with a permanently bound this that you can call later. 

Together, they help fix common pitfalls, such as losing this in callbacks or enabling partial application of functions. Alongside modern alternatives like arrow functions and the spread operator, mastering these methods lets you write clearer, more reusable, and bug-free code. Next time this gets confusing, you'll know exactly which tool to reach for.


Oct 6, 2025

JavaScript map, filter, reduce Explained with Real Examples and Best Practices

When working with arrays in JavaScript, three methods stand out for their power and versatility — map, filter, and reduce. These methods allow you to transform data, select specific elements, and aggregate values all in a clean, readable way.


Mastering them helps you write less code with more intent, turning complex loops into concise, functional expressions. Whether you're transforming arrays, filtering contents, or calculating totals, understanding these array helpers is essential for every JavaScript developer.

map-filter-reduce

map vs filter vs reduce: When & How to Use Them


  • map transforms every element into a new value, creating a new array of the same length.

  • filter picks elements based on a condition, returning a subset.

  • reduce boils down an array to a single value by accumulating results.


Implementing Polyfills for map, filter and reduce 


To truly grasp how these work, here are simple polyfill-style implementations:


Using map, filter, reduce with ES6 Features


Working with destructuring and spread:


Working with Arrays of Objects


Example: Filter active users, then map their emails:


Chaining filter + map vs Using reduce Directly


Both work, but for complex transformations, reduce shines with better performance by iterating once:


Converting Sets / Maps to Arrays


Sets and Maps aren’t arrays. Convert before using:


Real-world Examples


  • Summarizing total price:

  • Grouping by category:


Pitfalls to Avoid


  • Always return in your callback function, especially in map and reduce.
  • Avoid mutating original arrays inside callbacks.
  • Be wary of empty arrays; reduce needs an initial value to avoid errors.
  • Remember filter only returns elements passing the condition, no transformation.

Summary


JavaScript’s map, filter, and reduce methods provide elegant solutions for array manipulation. Use map when you want to transform every element, filter to select items matching criteria, and reduce to condense an array into a single result or summary. 


Implementing your own versions helps deepen your understanding, and combining these methods with ES6 features like destructuring and the spread operator makes your code even more powerful. Watch out for pitfalls like missing callbacks or mutation to write clean, bug-free array logic.


Oct 4, 2025

Understanding package.json & package-lock.json: Key Differences and Best Practices

In every Node.js project, package.json and package-lock.json play essential roles in managing dependencies. The package.json file lists your project’s metadata, dependencies, and scripts, acting as the blueprint for your app. 


Meanwhile, package-lock.json records the exact versions and full dependency tree, ensuring every install is consistent—no surprises across environments. Together, they help developers manage, share, and maintain packages reliably.

package.json-vs-package-lock.json


What is package.json?


In every Node.js project, the package.json file is the heart of your dependency management. It holds important metadata like your project’s name, version, and author, along with key fields like:

  • scripts: Command shortcuts you can run (npm start, npm test).
  • dependencies: Packages required for your app to work.
  • devDependencies: Tools used only during development (e.g., testing, build tools).


A simple example:



What is package-lock.json?


The package-lock.json file is automatically generated when you run npm install. It locks down the exact versions of every package and sub-package installed, creating a snapshot of your entire dependency tree.

Here is a simple example snippet illustrating the structure and purpose of a package-lock.json file:



Explanation:

  • package-lock.json records the exact versions ("version") and URLs ("resolved") from where packages were fetched.
  • It stores a complete tree of all dependencies (dependencies) and their nested dependencies.
  • This ensures that everyone running npm install gets the exact same dependency tree that was originally installed, essential for consistency across environments.

If you run npm install in a new project with a package.json specifying "express": "^4.17.1", npm creates a package-lock.json like above, locking the specific Express version and the exact nested packages installed.


Why does 'package-lock.json' matter?


  • It guarantees deterministic installs across machines.
  • Avoid surprises from dependency updates that could break your code.
  • Makes installs faster because versions are pre-resolved.


Differences Between package.json and package-lock.json



Aspect
package.json
package-lock.json
Purpose
Lists packages & project metadata
Locks the exact versions and dependency tree
Created/Edited By
Manually by the developer
Automatically by npm on install/update
Versioning
Accepts version ranges (^, ~)
Locks specific versions exactly
Included in Version Control
Always included
Should be included for consistent installs



Version Ranges vs Locked Versions


In package.json, you often see version ranges:

The caret (^) means “compatible with version 4.17.1,” so your installs could pick 4.17.2, 4.18, etc. But package-lock.json records the precise version you installed (e.g., 4.17.3), ensuring everyone uses the same one.

What if 'package-lock.json' Is Missing?


Without package-lock.json, installs might:
  • Get varying package versions on different machines.
  • Lead to bugs and inconsistent behaviour.
  • Slow down install times due to version resolution.


Why Commit package-lock.json?


Committing this file to version control ensures:
  • Everyone uses identical dependencies.
  • CI/CD runs are consistent and reliable.
  • Easier debugging and collaboration.


Best Practices for Managing package.json & package-lock.json


  • Keep package-lock.json committed.
  • Avoid manually editing package-lock.json.
  • Use npm install and npm update to manage packages.
  • Regularly audit dependencies for security.
  • Use scripts in package.json to automate tasks.
  • Understand version ranges-prefer exact versions for production.


Summary


While package.json outlines which packages your project needs and their version ranges, package-lock.json locks those dependencies to specific versions for deterministic installs. Committing the lock file to version control guarantees that everyone working on the project uses the exact same setup. 

Following best practices in managing these files helps teams avoid bugs, maintain stability, and speed up application builds across different machines.


Understanding JavaScript's typeof, instanceof, and Type Checks

Type checking helps you write solid JavaScript by letting you know exactly what kind of data you’re working with, whether it’s a number, string, array, or something else. JavaScript gives us several built-in tools for this, like typeof for quick type checks and instanceof for deeper prototype and inheritance tests. 


However, these tools have quirks, and picking the right one is key for clean, bug-free code. This guide unpacks how these checks work, where they trip developers up, and how you can combine them to confidently handle any data type you encounter.


typeof-instanceof-type-checking

How typeof Works & What It Returns


The typeof operator gives you a quick way to check the type of a variable or value, always returning a string:



Corner Cases and Quirks of typeof


There are a few oddities to watch for with typeof:

  • typeof null is "object" (a well-known historical JavaScript bug):

  • typeof on undeclared identifiers returns "undefined" instead of throwing an error:


How instanceof Works: Prototypes & Inheritance


The instanceof operator checks if an object is an instance of a constructor anywhere in its prototype chain:

It works reliably for user-defined classes and built-in objects.

typeof vs instanceof: The Interview Question


Use typeof for basic built-in types (like "number", "boolean", "string"). Use instanceof for custom classes and to distinguish between objects (e.g., array vs. plain object).



When instanceof Fails: Frames & Prototypes


  • If objects were created in different browser frames or windows, instanceof can fail, because their prototypes aren’t truly the same.
  • Modifying __proto__ or manually changing the prototype can also confuse instanceof.


Reliable Type Checking: typeof, instanceof, and More


For better accuracy:
  • Use typeof for primitives.
  • Use Array.isArray() for arrays:

  • Check for dates, maps, and sets with instanceof:

  • For plain objects, you might use obj !== null && typeof obj === "object" && obj.constructor === Object.


Best Practices for Safe Type Checks (No TypeScript)


  • Prefer typeof for simple primitive checks.
  • Use instanceof for custom classes, arrays, or DOM objects.
  • Always validate input, avoid relying on type checks for complete safety.
  • Guard against null and undefined before using further property checks.
  • For arrays, avoid typeof x === "object"—use Array.isArray(x).


Checking Complex Structures


  • Arrays: Array.isArray(data)
  • Dates: data instanceof Date
  • Maps/Sets: data instanceof Map
  • Plain objects: Object.prototype.toString.call(data) === "[object Object]"


Summary


typeof and instanceof are essential for understanding JavaScript values, but each has its strengths and oddities. Use typeof for basic types, lean on instanceof for objects and inheritance, and reach for helpers like Array.isArray() for arrays.

Remember to watch out for special cases like typeof null, and always match your checks to the structure you want to detect. With the right approach, you can make your JavaScript type-safe—even without TypeScript or extra libraries.


Oct 3, 2025

Browser Storage Explained: localStorage, sessionStorage, Cookies & IndexedDB

In modern web development, storing data in the browser is essential for building fast and responsive applications. Browsers provide multiple storage options — localStorage, sessionStorage, cookies, and IndexedDB — each designed for different purposes and with distinct behaviours. 


From saving user preferences across sessions to managing complex offline data, understanding these choices helps developers pick the right tool for the right job. 


This guide walks you through how each storage method works, its strengths, differences, and best practices to use them securely and effectively.'


local-storage-session-storage-cookies-indexeddb


Web Storage API: localStorage & sessionStorage


The Web Storage API offers two main options for storing key-value pairs in the browser:

  • localStorage: Saves data with no expiration. This means the data stays even if the browser is closed or the device restarts. Useful for preferences or data that should persist long-term.
  • sessionStorage: Data only lasts for the current tab or browser session. Once the tab is closed, the stored data disappears. Perfect for temporary info like form data or step-by-step wizards.


Example of localStorage:



Cookies: How They Work & When to Use Them


Cookies have been the traditional method of storing small bits of data that are sent back to the server with every request. They can have attributes like:

  • expiry: When they should expire
  • path & domain: Limit scope to URLs/domains
  • secure: Sent only on HTTPS
  • HttpOnly: Accessible only by the server, not JavaScript (important for security)


Example of setting a cookie:



Cookies are essential for authentication and tracking, but limited in size (~4KB) and sent automatically with requests, which can slow things down.



IndexedDB: Storing Structured Data Efficiently


IndexedDB is a low-level database API inside browsers designed for large amounts of structured data. Unlike localStorage or sessionStorage, it is asynchronous, doesn’t block the UI, and supports complex objects and indexes.


At its core, IndexedDB uses:

  • Databases: Containers of data
  • Object Stores: Like tables in SQL, where records are stored
  • Transactions: To manage read/write access safely


It’s ideal for apps needing offline support or storing a lot of data, like media-heavy or client-side apps.


Performance & Storage Limits


  • localStorage/sessionStorage usually offers about 5MB of storage per origin.
  • Cookies are limited to about 4KB each.
  • IndexedDB provides much more space, often hundreds of MBs, depending on the browser.


Security: Avoiding XSS Risks


  • Avoid storing sensitive data in localStorage or cookies accessible via JavaScript to prevent cross-site scripting (XSS) attacks.
  • Use HttpOnly cookies for authentication tokens to ensure they’re inaccessible to JavaScript.
  • Properly sanitise input and headers to protect your app.


Best Practices for Using localStorage & sessionStorage


  • Store only non-sensitive, simple data.
  • Use JSON to serialise complex objects (JSON.stringify() / JSON.parse()).
  • Always wrap storage access in try/catch to handle quota exceeded errors gracefully.
  • Clean up data when no longer needed.
  • Use sessionStorage for strictly session-bound data, and localStorage for persistent info.


Key Difference between localStorage, sessionStorage, cookies, and indexedDB



Feature
localStorage
sessionStorage
Cookies
IndexedDB
Storage Capacity
~5-10 MB
~5 MB
~4 KB
Hundreds of MB to GBs
Data Persistence
Persistent until manually cleared
Cleared when tab/browser closes
Expiry configurable (session or persistent)
Persistent until deleted or quota reached
Scope
Accessible across tabs/windows of same origin
Accessible only in same tab/window
Sent with every HTTP request, accessible across tabs/windows in domain
Accessible across tabs/windows of same origin
Data Type
String (objects need JSON serialization)
String (objects need JSON serialization)
String
Structured objects & binary data
Read/Write Access
JavaScript only
JavaScript only
JavaScript & server (via HTTP headers)
JavaScript (async API)
Security
Susceptible to XSS if improperly handled
Same as localStorage
Can be HttpOnly, Secure, SameSite
More secure, can be used with encryption
Sync or Async
Synchronous
Synchronous
Synchronous
Asynchronous
Use Cases
User preferences, settings, caching
Session-based data, temporary state
Authentication tokens, tracking
Offline apps, large datasets, complex queries
Performance
Fast but blocks main thread
Fast but blocks main thread
Fast, but limited size
Asynchronous, non-blocking



Summary


Choosing the right browser storage method depends on your app’s needs. Use localStorage for persistent client-side data, sessionStorage for temporary data tied to a browser tab, and cookies for server communication and small persistent data with built-in security controls. For large or structured datasets, IndexedDB offers powerful, asynchronous storage. 

Following best practices and understanding security implications ensures your app runs smoothly, protects user data, and provides a seamless experience across sessions and devices.

Preload, Prefetch & Lazy Loading: Essential Techniques to Boost Web Performance

Modern websites often have lots of images, videos, and scripts. Loading everything at once can make pages slow and frustrating. Luckily, there are easy ways to control what loads when: preload speeds up important stuff, prefetch gets ready for users’ next steps, and lazy loading waits until something is really needed. Knowing how and when to use each keeps your site fast and your visitors happy.


preload-prefetch-lazy-loading-javascript


What Is Preload?


Preload is a way to prioritise critical resources by telling the browser to fetch them as soon as possible, ahead of when it normally would discover them in the HTML or CSS. This is essential for resources like fonts, hero images, or critical CSS/JS.


Example:

Use preload only for critical assets needed immediately for the first screen to show faster. Excessive preloading can hurt performance.


What Is Prefetch?


Prefetch prepares resources for future navigation, but keeps their priority low so they don’t slow the current page load. It lets browsers download assets the user might need next while respecting network bandwidth.


Example:


Prefetch is perfect for loading next-page scripts, styles, or images in the background to speed up navigation later.


What Is Lazy Loading?


Lazy loading means delaying the loading of non-critical resources until they are actually needed—like images or videos below the fold, scripts needed only after user interaction, or additional page content.


Modern browsers support native lazy loading:



Lazy loading reduces initial page weight and speeds up first load. Check out our blog post Lazy Loading in React.js to know more about how lazy loading works in React.js.


How <link rel="preload"> Can Improve Your Page Speed


Preloading critical fonts or images can drastically reduce Largest Contentful Paint (LCP), improving user perception and SEO ranking. Avoid preloading too many assets, which can overwhelm slow connections.


Using Prefetch to Speed Up Future Navigation


By prefetching resources like JavaScript chunks or entire HTML pages before the user requests them, you can make page transitions almost instant on repeat visits. Combine with lazy loading for the best user experience.

Advanced frameworks like Next.js and Gatsby automatically prefetch when links become visible in the viewport.


Lazy Loading Images & Videos: Best Practices for Web Performance


  • Use native loading="lazy" where supported.
  • For wide browser support, use Intersection Observer polyfills.
  • Prioritise loading of above-the-fold assets.
  • Resize images for responsive lazy loading.
  • Monitor LCP to ensure important assets load quickly.


SEO Considerations when Lazy Loading Content


  • Ensure lazy content is within HTML or accessible via JavaScript for search engines.
  • Provide fallback content with <noscript> tags for old browsers and bots.
  • Test lazy-loaded content with Google’s Mobile-Friendly and Rich Results test tools.


Lazy Loading Fallbacks & SEO: Making Sure Search Engines See Your Content


Always provide content fallback for JS-disabled users and bots. Use <noscript> for images and content placeholders if your lazy loading relies on JavaScript.


Common Mistakes with Preload / Prefetch and How to Avoid Them


  • Preloading too many resources
  • Forgetting to add an attribute with preload, causing double downloads
  • Using prefetch indiscriminately, wasting bandwidth
  • Lazy loading critical above-the-fold content
  • No fallback for lazy-loaded content is hurting SEO


Preload vs Prefetch vs Lazy Loading: Which to Use & When



Technique
Purpose
Use When
Preload
Prioritize critical assets now
Fonts, hero images, critical CSS/JS
Prefetch
Prepare assets for next navigation
Scripts, pages, or images likely used soon
Lazy Load
Load non-critical content on demand
Below-the-fold images/videos, deferred scripts


Summary


Preload grabs key resources early so your main content shows up fast. Prefetch quietly fetches files in the background for future pages, making next clicks quicker. Lazy loading helps your site only load images, videos, or scripts when a user actually needs them. 

Using these three tricks together leads to faster sites, better user experiences, and improved SEO; just be careful not to overuse any, and always make sure search engines can still see your most important content.

Oct 2, 2025

JavaScript Type Coercion Explained: Implicit vs Explicit, Edge Cases & Best Practices

JavaScript is a loosely typed language with a magical, sometimes baffling feature called type coercion, where it automatically converts one data type into another during operations. This can make coding easier, but if misunderstood, it can also cause surprising bugs.


type-coercion-implicit-vs-explicit


What is Type Coercion?


Type coercion is JavaScript’s automatic or manual conversion of one data type to another to complete operations, often behind the scenes. It is fundamental to JS but can cause unexpected results if misunderstood.


Implicit vs Explicit Type Coercion


  • Implicit coercion happens automatically when JavaScript interprets values in different contexts, like when using the "+" operator with a string and a number:


  • Explicit coercion is when you manually convert data types using functions like:


How JavaScript Coerces Types with Operators


  • + operator: If one operand is a string, others are coerced to string → concatenation.


  • -, *, / operators: Convert operands to numbers.


  • Comparison (==): Coerces operands before checking equality.


  • Strict equality (===): compares both value and type:


Falsy and Truthy Values & Boolean Coercion


  • Falsy values (coerce to false): false, 0, "" (empty string), null, undefined, NaN.
  • Everything else is truthy(including empty arrays and objects).


Type Coercion with Null, Undefined, and NaN


  • null loosely equals undefined, but differs in operations:


  • NaN is unique: it never equals itself


How Objects / Arrays Coerce to Primitives


Objects/arrays convert to strings or numbers depending on context:
When JS needs a primitive from object/array, it uses .valueOf() and .toString() methods.


Forcing Explicit Conversion


Use built-in functions or operators:

Use these when you want to avoid ambiguity.


Deep Dive: == vs === in Comparisons


  • Use === (strict equality) to avoid unintentional coercion bugs.
  • == performs type coercion before comparison, which can lead to surprises.
  • == coerces types: 5 == "5" is true.
  • === compares type and value: 5 === "5" is false.
  • Prefer === to avoid unexpected bugs.


Best Practices to Avoid Coercion Bugs


  • Always prefer strict equality (=== and !==) unless you have a specific reason.
  • Use explicit type conversion to avoid ambiguity.
  • Be cautious with falsy/truthy checks in conditionals.
  • Avoid relying on ambiguous coercions in complex expressions; clarity wins.

Mastering JavaScript coercion empowers cleaner, bug-free code and a deeper understanding of one of the language’s core behaviours.