How to Find Sum of Array Using reduce() in JavaScript (Step-by-Step Execution Explained)

Finding the sum of array elements is one of the most common tasks in JavaScript.
While there are multiple ways to do it, the reduce() method is the most powerful and preferred approach.

In this post, you’ll learn:

  • What reduce() is ?
  • How to use it to find sum
  • Step-by-step execution (very important)
  • What happens if you don’t provide initial value
  • Common mistakes to avoid

Let’s get started 👇


What is reduce() in JavaScript?

The reduce() method is used to:

Convert an array into a single value

This value can be:

  • Sum
  • Product
  • Object
  • String

Problem Statement

Write a JavaScript program to find the sum of array elements using reduce().


Basic Example

const numbers = [10, 20, 30, 40];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 100

Understanding the Syntax

array.reduce((acc, curr) => acc + curr, initialValue);

Parameters:

  • acc → accumulator (stores result)
  • curr → current element
  • initialValue → starting value (important!)

Step-by-Step Execution (Very Important)

Let’s understand how this works internally.

Input:

[10, 20, 30, 40]

Code:

numbers.reduce((acc, curr) => acc + curr, 0);

Execution Flow Table

StepacccurrOperationResult
10100 + 1010
2102010 + 2030
3303030 + 3060
4604060 + 40100

Final Output

100

How reduce() Works Internally

You can think of reduce() like this:

let acc = 0;for (let i = 0; i < numbers.length; i++) {
acc = acc + numbers[i];
}

👉 It keeps updating the acc value until all elements are processed.


What Happens If You Don’t Provide Initial Value?

numbers.reduce((acc, curr) => acc + curr);

Execution Without Initial Value

StepacccurrResult
Start102030
Next303060
Next6040100

👉 Here:

  • acc starts as first element (10)
  • Loop starts from second element (20)

Problem with Empty Array

[].reduce((acc, curr) => acc + curr);

👉 💥 Error:

TypeError: Reduce of empty array with no initial value

Link : TypeError: Reduce of Empty Array with No Initial Value (Fix Explained)


Best Practice

Always use initial value:

numbers.reduce((acc, curr) => acc + curr, 0);

Common Mistakes

1. Forgetting initial value

👉 Can cause errors


2. Using map() instead of reduce()

👉 Wrong approach for sum


3. Not understanding execution flow

👉 Leads to confusion in interviews


Real-World Use Cases

  • Shopping cart total
  • Marks calculation
  • Financial reports
  • Data aggregation

Interview Tip

If asked:

“How does reduce work?”

Answer:

“It iterates over each element, updates an accumulator value, and finally returns a single result.”


Related Articles (Internal Linking)

👉 You can also check:


Final Summary

  • reduce() converts array → single value
  • acc stores result
  • curr is current element
  • Always use initial value (0)
  • Helps in writing clean and efficient code

💡 Found this helpful? Subscribe to get simple JavaScript explanations, interview questions, and real-world coding tips directly in your inbox. Happy Coding!

TypeError: Reduce of Empty Array with No Initial Value (Fix Explained)

While working with JavaScript arrays, you might have seen this error:

TypeError: Reduce of empty array with no initial value

This error is very common, especially when using the reduce() method.

In this post, we’ll understand:

  • What this error means
  • Why it happens
  • How to fix it properly
  • Best practices to avoid it

All explained in a simple and clear way.


What is reduce()?

Before understanding the error, let’s quickly recap:

reduce() is used to:

Convert an array into a single value (sum, object, etc.)

Example:

const numbers = [10, 20, 30];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 60

The Error

Now look at this:

[].reduce((acc, curr) => acc + curr);

👉 Output:

TypeError: Reduce of empty array with no initial value

Why Does This Error Occur?

To understand this, you must know how reduce() works internally.


Case 1: Without Initial Value

[10, 20, 30].reduce((acc, curr) => acc + curr);

Internally:

  • acc = 10 (first element)
  • curr = 20 (second element)

Then continues…


Problem with Empty Array

Now consider:

[].reduce((acc, curr) => acc + curr);

There is:

  • ❌ No first element
  • ❌ No second element
  • ❌ Nothing to assign to acc

👉 JavaScript gets confused and throws an error.


Root Cause

reduce() needs an initial value or at least one element to start with.

If both are missing → 💥 Error


Solution 1: Always Provide Initial Value

[].reduce((acc, curr) => acc + curr, 0);

👉 Output:

0

Why this works:

  • acc = 0 (initial value)
  • No elements → loop doesn’t run
  • Returns 0

Solution 2: Check Array Before Reduce

function sumArray(arr) {
if (arr.length === 0) return 0;
return arr.reduce((acc, curr) => acc + curr);
}

Solution 3: Safe Reduce Pattern

const sum = (arr || []).reduce((acc, curr) => acc + curr, 0);

👉 Handles:

  • null
  • undefined
  • empty array

Real-World Scenario

Imagine:

const cartItems = [];

You calculate total:

const total = cartItems.reduce((sum, item) => sum + item.price);

💥 App crashes if cart is empty!


Correct Approach

const total = cartItems.reduce((sum, item) => sum + item.price, 0);

Common Mistake Developers Make

❌ Forgetting initial value:

arr.reduce((acc, curr) => acc + curr);

✅ Correct:

arr.reduce((acc, curr) => acc + curr, 0);

Best Practice

Always provide an initial value when using reduce()


Simple Analogy

Imagine you are adding numbers:

  • If someone gives you numbers → you can start
  • If no numbers are given → what will you add? 🤔

👉 You need a starting value (like 0)


With vs Without Initial Value

CaseBehavior
With initial valueSafe, works always
Without initial valueFails for empty array

Interview Tip

If asked:

Why does this error occur?

Answer:

The error occurs because reduce() tries to use the first element as the accumulator, but in an empty array, no such element exists. Providing an initial value solves this issue.


🏁 Final Summary

  • reduce() combines array elements into one value
  • Without initial value:
    • Uses first element as accumulator
    • Fails for empty arrays
  • With initial value:
    • Safe and predictable
    • Works for all cases

👉 Always use an initial value to avoid this error

💡 Found this helpful? Subscribe to get real-world coding tips, interview questions, and easy explanations directly in your inbox. Happy Coding!

The Turing Test in 1950 – History of AI

Can Machines Think ?

In 1950, The British mathematician and computer scientist Alan Turing asked the question: Can Machines Think ? in his research paper “Computing Machinery and Intelligence”.

Turing proposed a practical way to test machine intelligence later called as Turing Test.

What Turing Proposed ?

If a machine can behave like a human during a conversation, then it could be considered intelligent.

How the Turing Test Works ?

This test involves three participants

  1. A Human Judge
  2. A Human Participant
  3. A machine (computer program)

The test goes like this:

  • The Judge sends questions to both to the human and machine through text messages only.
  • Both participants respond through text.
  • The judge reads the answers and tries to determine which response came from human or which response came from machine ? The judge can ask follow-up questions to test the responses.
  • If the judge cannot reliably tell the difference between the machine and the human, the machine is said to have Passed the Turing Test.

What Are Polyfills in JavaScript?

Modern JavaScript keeps improving every year.

But here’s the problem:

Not all browsers support new JavaScript features immediately.

So what happens if you use a modern feature like Array.prototype.includes() in an older browser that doesn’t support it?

💥 Your code breaks.

This is where Polyfills come in.


What Is a Polyfill?

A polyfill is a piece of JavaScript code that adds support for newer features in older browsers.

In simple terms:

A polyfill is a fallback implementation of a feature that doesn’t exist in a browser.

It “fills the gap” (poly + fill).


Why Do We Need Polyfills?

Different browsers support different JavaScript features.

Example:

  • Chrome supports modern features quickly
  • Internet Explorer (older versions) doesn’t
  • Some mobile browsers lag behind

If you build an app using modern features:

  • It may work in Chrome
  • It may fail in older browsers

Polyfills make your code work everywhere.


Real Example Without Polyfill

Consider this modern JavaScript method:

const numbers = [1, 2, 3, 4];
console.log(numbers.includes(3));

includes() checks if a value exists in an array.

Works in modern browsers ✅
Fails in older browsers ❌

Error:

TypeError: numbers.includes is not a function

Writing a Simple Polyfill

Let’s write a polyfill for Array.prototype.includes.

if (!Array.prototype.includes) {
Array.prototype.includes = function (value) {
for (let i = 0; i < this.length; i++) {
if (this[i] === value) {
return true;
}
}
return false;
};
}

What’s happening here?

  1. We check if includes exists.
  2. If not, we define it ourselves.
  3. Now older browsers can use includes().

That’s a polyfill 🎉


How Polyfill Works Internally

Imagine:

  • Browser doesn’t know includes
  • We manually add it to Array.prototype
  • Now browser behaves like it supports it

So instead of upgrading the browser,
we simulate the feature.


Another Example: Promise Polyfill Concept

Modern JavaScript has Promise.

Old browsers didn’t.

If you try this:

new Promise((resolve, reject) => {
resolve("Done");
});

Old browsers: ❌ Error

To fix this, developers used libraries that provided Promise polyfills.

Example library:

  • core-js
  • es6-promise

How Polyfills Are Used in Real Projects

In modern projects (React, Angular, Vue), we usually don’t write polyfills manually.

Instead, we use tools like:

  • Babel
  • core-js
  • polyfill.io

What Is core-js?

core-js is a popular polyfill library.

Install:

npm install core-js

Import:

import "core-js/stable";

It automatically adds missing features.


Babel and Polyfills

Babel converts modern JavaScript into older JavaScript.

But Babel alone doesn’t add missing features.

Example:

Babel converts:

const sum = (a, b) => a + b;

Into:

var sum = function(a, b) {
return a + b;
};

But if you use Promise, Babel won’t magically create it.

That’s where polyfills are needed.


Polyfill vs Transpiling (Very Important)

Many developers confuse these.

🔹 Transpiling

Converts new syntax to old syntax.

Example:
Arrow functions → normal functions

Tool: Babel


🔹 Polyfill

Adds missing built-in features.

Example:
Promise, includes, fetch

Tool: core-js


When Do You Need Polyfills?

You need them when:

  • Supporting older browsers
  • Supporting older mobile devices
  • Working with enterprise apps
  • Supporting Internet Explorer (legacy systems)

When You DON’T Need Polyfills

If:

  • Your app supports only modern browsers
  • You control the environment (internal app)
  • You are using Node.js latest version

You may not need them.


Final Summary

Polyfill:

  • Is fallback code for unsupported features
  • Makes modern JavaScript work in old browsers
  • Can be written manually or added via libraries
  • Is different from transpiling
  • Is crucial for cross-browser compatibility

Interview-Ready Explanation

If asked:

What is a polyfill?

You can say:

A polyfill is JavaScript code that implements a feature that a browser does not natively support, allowing modern features to work in older environments.

That’s a strong answer.

What is JWT? How It Works & How It Is Used in Authentication ?

Authentication is a core part of modern web applications.
When users log in, the server must remember who they are on future requests.

One of the most popular ways to handle this is using JWT (JSON Web Token).

In this post, we’ll explain everything clearly — even if you’re a frontend developer.


What is JWT?

JWT (JSON Web Token) is a compact, secure way of transmitting information between client and server as a JSON object.

It is commonly used for:

  • Authentication
  • Authorization
  • Secure data exchange

👉 In simple terms:

JWT is a secure digital identity card for a user.


Why Do We Need JWT?

When a user logs in:

  • Server verifies username/password
  • Server must remember the user
  • User makes multiple API requests afterward

Without JWT, server would need:

  • Session storage
  • Database lookups for every request

JWT allows:

  • Stateless authentication
  • No need to store sessions on server

Structure of a JWT

A JWT has 3 parts separated by dots:

HEADER.PAYLOAD.SIGNATURE

Example:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.
eyJ1c2VySWQiOjEyMywicm9sZSI6IkFETUlOIn0
.
abc123signature

Let’s break it down.


1️⃣ Header

Contains:

  • Token type (JWT)
  • Algorithm used for signing (e.g., HS256)

Example:

{
"alg": "HS256",
"typ": "JWT"
}

2️⃣ Payload

Contains user data (called claims).

Example:

{
"userId": 123,
"email": "user@example.com",
"role": "ADMIN"
}

⚠️ Important:
Payload is NOT encrypted.
It is only encoded.

Never store sensitive data like passwords.


3️⃣ Signature

Created using:

  • Header
  • Payload
  • Secret key (stored on server)

This ensures:

  • Token cannot be modified
  • Data integrity is maintained

How JWT Works (Step-by-Step Authentication Flow)

Let’s understand complete login flow.


Step 1: User Logs In

Frontend sends:

{
"email": "user@example.com",
"password": "123456"
}

Step 2: Server Validates Credentials

Server:

  • Checks database
  • Verifies password

If valid → generate JWT


Step 3: Server Generates JWT

Server creates token like:

{
"userId": 123,
"role": "USER",
"exp": 1700000000
}

Signs it with secret key.


Step 4: Server Sends JWT to Client

Response:

{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Step 5: Frontend Stores JWT

Common storage options:

  • LocalStorage
  • SessionStorage
  • HttpOnly Cookie (recommended)

Step 6: User Makes API Requests

Frontend sends JWT in headers:

Authorization: Bearer <token>

Step 7: Server Verifies Token

Server:

  • Checks signature
  • Checks expiration
  • Extracts user info

If valid → allow access
If invalid → reject request


JWT in Authentication vs Authorization

Authentication

Verifying who the user is.

Authorization

Checking what the user is allowed to do.

Example:

  • USER role → read data
  • ADMIN role → delete data

JWT payload often contains role for authorization.


Real-World Example (Frontend Perspective)

Imagine:

You log into a React app.

After login:

  • Server sends JWT
  • React stores it
  • Every API request includes it

Without JWT:

  • User would need to login again on every request

JWT solves this.


Security Best Practices

  1. Never store passwords in JWT
  2. Always set expiration (exp)
  3. Use HTTPS
  4. Prefer HttpOnly cookies
  5. Use short expiry + refresh tokens
  6. Keep secret key secure

What is Refresh Token?

Access token:

  • Short life (15–30 mins)

Refresh token:

  • Longer life
  • Used to generate new access token

Improves security.


Interview-Ready Explanation

If asked:

How does JWT work in authentication?

You can say:

After login, the server generates a signed JWT containing user information and sends it to the client. The client includes this token in future requests. The server verifies the token’s signature and allows access if valid.

That’s a strong answer.


Final Summary

JWT:

  • Is a secure token format
  • Enables stateless authentication
  • Contains header, payload, signature
  • Is widely used in modern web apps
  • Works perfectly for frontend + backend communication