Understanding JavaScript sort() with a Simple Example

Let’s look at this JavaScript code:

const values = [32, 25, 120];
const result = values.sort();
console.log(result);

✅ Output

[120, 25, 32]

At first glance, this output feels wrong, right?
Why didn’t JavaScript sort the numbers in ascending order?

Let’s understand why this happens.


How sort() Actually Works in JavaScript

By default, JavaScript’s sort() method:

Converts elements to strings and compares them lexicographically (dictionary order).

This is the key reason for the unexpected result.


Step-by-Step Explanation

Original array:

[32, 25, 120]

JavaScript internally converts numbers to strings:

["32", "25", "120"]

Now it sorts them alphabetically:

  • "120" comes before "25" → because "1" < "2"
  • "25" comes before "32" → because "2" < "3"

So the final order becomes:

["120", "25", "32"]

Converted back to numbers:

[120, 25, 32]

Important Warning

This behavior can easily cause bugs, especially when sorting numbers.

Do NOT rely on default sort() for numeric sorting.


Correct Way to Sort Numbers

To sort numbers properly, you must provide a compare function.

Ascending Order

values.sort((a, b) => a - b);
console.log(values);

✅ Output:

[25, 32, 120]

Descending Order

values.sort((a, b) => b - a);
console.log(values);

✅ Output:

[120, 32, 25]

Why Does JavaScript Work This Way?

JavaScript was originally designed to sort strings.

So:

  • Sorting names → works perfectly
  • Sorting numbers → needs extra instruction

This is why the compare function exists.


Key Takeaways

  • array.sort() sorts strings by default
  • Numbers are converted to strings internally
  • Always use a compare function for numeric sorting
  • sort() mutates the original array

Interview One-Liner

JavaScript’s sort() method sorts values as strings by default, so numeric sorting requires a custom compare function.


✨ Final Thought

This is one of the most common JavaScript interview traps.

If you understand this:

  • You avoid bugs
  • You write safer code
  • You stand out in interviews

Small detail. Big impact 🚀


Microservices Best Practices (A Practical Guide)

Microservices architecture helps teams build scalable, flexible, and independently deployable systems.
But without the right practices, microservices can quickly become harder than a monolith.

This blog covers proven microservices best practices that work in real-world systems.


1. Keep Services Small and Focused

Each microservice should:

  • Do one business function
  • Have a single responsibility
  • Be easy to understand and maintain

❌ Bad:

One service handling users, orders, and payments

✅ Good:

  • User Service
  • Order Service
  • Payment Service

2. Each Service Owns Its Data

A microservice should own its own database.

❌ Don’t:

  • Share databases between services

✅ Do:

  • One database per service
  • Communicate via APIs

This avoids tight coupling and unexpected failures.


3. Use API-Based Communication

Services should communicate using:

  • REST APIs
  • gRPC
  • Messaging (Kafka, RabbitMQ)

Avoid:

  • Direct database access between services

4. Implement Service Discovery

In microservices, services scale up and down dynamically.

Use service discovery so services can:

  • Find each other automatically
  • Avoid hard-coded IPs or URLs

Examples:

  • Eureka
  • Consul
  • Kubernetes Service Discovery

5. Design for Failure

Failures are normal in distributed systems.

Best practices:

  • Use Circuit Breakers
  • Add timeouts
  • Implement retries with limits

Goal:

Fail fast and recover gracefully


6. Apply Rate Limiting

Protect your services from:

  • Traffic spikes
  • Abuse
  • Overload

Rate limiting ensures:

  • System stability
  • Fair usage

7. Centralized Logging and Monitoring

With many services, debugging becomes difficult.

Use:

  • Centralized logs (ELK, Loki)
  • Metrics (Prometheus)
  • Tracing (Jaeger, Zipkin)

This helps:

  • Identify failures quickly
  • Monitor system health

8. Secure Your Services

Security is critical in microservices.

Best practices:

  • Use API gateways
  • Implement authentication & authorization
  • Secure service-to-service communication (JWT, mTLS)

Never trust internal traffic blindly.


9. Make APIs Idempotent

Clients may retry requests due to network issues.

Design APIs so:

  • Multiple identical requests produce the same result
  • Duplicate actions are avoided

Especially important for:

  • Payments
  • Order creation
  • Updates

10. Use Auto Scaling

Traffic changes over time.

Auto scaling:

  • Adds resources during high load
  • Removes resources during low usage

This improves:

  • Performance
  • Cost efficiency

11. Test Services Independently

Test at multiple levels:

  • Unit tests
  • Integration tests
  • Contract tests

Each service should be:

  • Testable
  • Deployable independently

12. Avoid Over-Engineering

Microservices are powerful, but not always necessary.

Avoid microservices if:

  • Team is very small
  • Application is simple
  • No scaling requirement

Start simple, evolve when needed.


Summary: Microservices Best Practices Checklist

  • ✔ Small, focused services
  • ✔ Independent databases
  • ✔ API-based communication
  • ✔ Service discovery
  • ✔ Fault tolerance
  • ✔ Rate limiting
  • ✔ Centralized logging
  • ✔ Strong security
  • ✔ Idempotent APIs
  • ✔ Auto scaling

🎯 Final Thought

Microservices are not about splitting code —
they are about splitting responsibility wisely.

When designed correctly, microservices bring scalability, resilience, and faster development.


How Optional Chaining (?.) Saves You from Runtime Errors

While working with JavaScript objects, we often access nested properties.
But what if one property doesn’t exist?

👉 That’s where optional chaining (?.) comes to the rescue.


❌ The Common Problem

Consider this example:

const user = {};
console.log(user.profile.name);

❌ This throws an error:

Cannot read properties of undefined

Why?
Because profile does not exist, and JavaScript tries to read name from undefined.


✅ The Solution: Optional Chaining (?.)

Now look at this:

const user = {};
console.log(user.profile?.name);

✅ Output:

undefined

No error.
The program continues smoothly.


What Does ?. Actually Do?

In very simple words:

If the value exists → access it
If it doesn’t → stop and return undefined

That’s it. No crash. No exception.


Very Simple Real-Life Analogy

Imagine asking someone:

“If you have my book, please give it.
If not, that’s okay.”

Optional chaining behaves the same way 😄


Simple API Response Example

const response = {
data: {
user: {
name: "Raj"
}
}
};
console.log(response.data?.user?.name); // Raj
console.log(response.data?.user?.age); // undefined

Instead of breaking the app, JavaScript safely returns undefined.


Before vs After Optional Chaining

❌ Old Way (Using &&)

const name = user && user.profile && user.profile.name;

✅ Modern Way (Optional Chaining)

const name = user.profile?.name;

✔ Cleaner
✔ Easier to read
✔ Less error-prone


⚠️ Important Things to Remember

  • Optional chaining only reads values
  • It does not create properties
  • It works only with:
    • Objects
    • Arrays
    • Functions

❌ This is invalid:

user.profile?.name = "Raj";

Optional Chaining with Arrays

const users = [];
console.log(users[0]?.name);

✅ Output:

undefined

No error even if the array is empty.


When Should You Use Optional Chaining?

✅ API responses
✅ Nested objects
✅ Data from backend
✅ Dynamic data

❌ When you are sure the value always exists


Interview One-Liner

Optional chaining (?.) allows safe access to nested properties without throwing errors when values are null or undefined.


Final Thoughts

Optional chaining may look small, but it prevents big runtime crashes.

One operator.
Cleaner code.
Fewer bugs.

That’s the power of ?.


If this post is helpful to you don’t forget to like and subscribe !!

Architectural Concepts that Every Software Developer should know.

  1. Load Balancer

Distributes incoming traffic across multiple servers to ensure no single server gets overwhelmed.

  1. Caching

    Stores frequently accessed data in memory to reduce latency.

    1. Content Delivery Network (CDN)

    Stores static assets across globally distributed edge locations or servers so users download the content from the nearest location

    1. Message Queue

    Decouples components by letting producers enqueue messages that consumers process asynchronously.

    1. Publish-Subscribe

    Enables multiple consumers to receive messages from a topic

    1. API Gateway

    Acts as a single entry point for client requests, handling routing, authentication, rate limiting and protocol translation

    1. Circuit Breaker

    Prevents a system from repeatedly calling a failing service by temporarily stopping requests until the service recovers.

    1. Service Discovery

    Automatically tracks available service instances, enabling components to discover and communicate with each other dynamically.

    1. Sharding

    Sharding splits large datasets across multiple nodes using a shard key to improve scalability and performance.

    1. Rate Limiting

    Rate limiting controls how many requests a client can make within a time window to prevent service overload.

    1. Consistent Hashing

    Consistent hashing is a data distribution technique that minimizes data movement when nodes join or leave the system.

    1. Auto Scaling

    Auto scaling automatically adds or removes compute resources based on demand or predefined metrics.

    Understanding filter(Boolean) in JavaScript

    JavaScript often surprises us with how much we can do using very little code.
    One such powerful and commonly used trick is:

    const arr = ["", null, undefined, false, 0, 1, 2];
    const result = arr.filter(Boolean);
    console.log(result);

    ✅ Output

    [1, 2]

    But why does this happen?
    Let’s break it down in a simple and clear way.


    What Does filter(Boolean) Mean?

    The filter() method creates a new array by keeping only the elements that satisfy a condition.

    This line:

    arr.filter(Boolean)

    is actually shorthand for:

    arr.filter(value => Boolean(value))

    So every element in the array is passed into the Boolean() function.


    How Boolean() Works in JavaScript

    The Boolean() function converts any value into either true or false.

    ❌ Falsy Values

    These values always return false:

    • "" (empty string)
    • null
    • undefined
    • false
    • 0
    • NaN

    ✅ Truthy Values

    Everything else is considered true, including:

    • 1
    • 2
    • "hello"
    • []
    • {}

    🔎 Step-by-Step Execution

    ValueBoolean(value)Included?
    ""false
    nullfalse
    undefinedfalse
    falsefalse
    0false
    1true
    2true

    Only truthy values survive the filter.


    Final Result

    [1, 2]

    ✨ Why Developers Love This Pattern

    Using filter(Boolean):

    • Removes unwanted falsy values
    • Makes code shorter and cleaner
    • Improves readability once understood

    Instead of writing:

    arr.filter(value => value !== null && value !== undefined && value !== "")

    You can simply write:

    arr.filter(Boolean)

    ⚠️ Important Thing to Remember

    This method removes all falsy values, including 0 and false.

    So do not use it if 0 or false are valid values in your data.


    When to Use filter(Boolean)

    ✅ Cleaning API responses
    ✅ Removing empty values from arrays
    ✅ Simplifying data before rendering

    ❌ When 0 or false are meaningful values


    🧠 Interview One-Liner

    filter(Boolean) is a concise way to remove all falsy values from an array in JavaScript.


    📌 Final Thought

    Sometimes, one line of JavaScript can replace multiple lines of code —
    but only if you truly understand why it works.

    Happy coding 🚀

    If this Post helps you don’t forget to like and subscribe !!