Skip One, Sum the Rest: A Smart JavaScript Array Trick

When working with arrays in JavaScript, we often need to calculate the total sum of elements. But what if you want to exclude one specific index while summing?

Let’s understand this with a simple and practical example.


Problem Statement

Given an array:

const a = [1, 2, 3, 4];

If we exclude index 2, the value 3 should be ignored.

πŸ‘‰ So the result becomes:

1 + 2 + 4 = 7

Approach

We need to:

  1. Loop through the array
  2. Skip the given index
  3. Add all other values

Solution 1: Using for Loop (Beginner Friendly)

function sumExceptIndex(arr, excludeIndex) {
let sum = 0;

for (let i = 0; i < arr.length; i++) {
if (i !== excludeIndex) {
sum += arr[i];
}
} return sum;
}

// Example
const a = [1, 2, 3, 4];
console.log(sumExceptIndex(a, 2)); // 7

βœ”οΈ Why this works:

  • We check i !== excludeIndex
  • Only add values that don’t match the excluded index

Solution 2: Using reduce() (Modern JavaScript)

function sumExceptIndex(arr, excludeIndex) {
return arr.reduce((sum, current, index) => {
return index !== excludeIndex ? sum + current : sum;
}, 0);
}

// Example
const a = [1, 2, 3, 4];
console.log(sumExceptIndex(a, 2)); // 7

Why this is powerful:

  • Cleaner and shorter
  • Uses functional programming style
  • Great for interviews and real-world code

Bonus: Random Index Exclusion

Want to make it dynamic?

const a = [1, 2, 3, 4];
const randomIndex = Math.floor(Math.random() * a.length);
const result = sumExceptIndex(a, randomIndex);
console.log("Excluded Index:", randomIndex);
console.log("Result:", result);

Real-World Analogy

Imagine you and your friends are splitting a bill:

  • Total items: [1, 2, 3, 4]
  • One friend didn’t order anything (index 2 β†’ value 3)

So you calculate the bill excluding that friend’s item.

πŸ‘‰ That’s exactly what we’re doing in code!


Edge Cases to Consider

  • ❌ Invalid index (negative or out of range)
  • ❌ Empty array
  • ❌ Non-number values inside array

πŸ‘‰ You can improve your function by adding validations.


Improved Version with Validation

function sumExceptIndex(arr, excludeIndex) {
if (!Array.isArray(arr)) return 0;
if (excludeIndex < 0 || excludeIndex >= arr.length) return 0;
return arr.reduce((sum, val, index) => {
if (typeof val !== "number") return sum;
return index !== excludeIndex ? sum + val : sum;
}, 0);
}

πŸŽ‰ Conclusion

This simple problem teaches you:

  • How to loop through arrays
  • How to skip elements based on conditions
  • How to use powerful methods like reduce()

Small problems like this build strong fundamentals in JavaScript.

Stay Connected

If you found this helpful and want to learn more practical JavaScript tricks like this:

πŸ‘‰ Subscribe to the blog for simple, real-world coding tips that actually make you a better developer.

  • No fluff
  • Just useful concepts
  • Beginner to advanced clarity

πŸ’‘ Don’t miss the next postβ€”you might learn something that saves hours of debugging!

What is React JS? Why is it Efficient? (Beginner-Friendly Guide)

If you are starting frontend development, one of the most popular technologies you’ll hear about is React JS.

But many beginners ask:

πŸ€” What exactly is React?
πŸ€” Why do companies prefer React over other frameworks?

In this guide, you’ll learn:

  • What React JS is
  • How it works
  • Why it is efficient
  • Real-world examples

What is React JS?

React is a JavaScript library used to build user interfaces (UI), especially for web applications.

πŸ‘‰ It was developed by Meta (formerly Facebook).


Simple Definition

React is a library that helps you build fast, interactive, and reusable UI components.


Example of React Code

function App() {
return <h1>Hello, World!</h1>;
}

πŸ‘‰ This renders a heading on the screen.


How React Works

React uses a component-based architecture.


What are Components?

Components are small reusable pieces of UI.

Example:

  • Header
  • Footer
  • Button
  • Form

Example

function Button() {
return <button>Click Me</button>;
}

πŸ‘‰ You can reuse this anywhere in your app.


Why is React Efficient?

This is the most important question πŸ‘‡


1. Virtual DOM (Main Reason)

React uses something called the Virtual DOM.


What is DOM?

DOM = Document Object Model
πŸ‘‰ Represents your webpage structure


Problem with Normal DOM

  • Slow updates
  • Entire UI re-renders

React Solution: Virtual DOM

React creates a lightweight copy of the DOM.

πŸ‘‰ When data changes:

  • React compares old vs new (diffing)
  • Updates only changed parts

Result:

βœ” Faster updates
βœ” Better performance


2. Reusable Components

Instead of writing code again and again:

<Button />
<Button />
<Button />

πŸ‘‰ One component β†’ multiple uses


3. Efficient Rendering

React updates only what is needed:

❌ Not entire page
βœ… Only changed components


4. One-Way Data Flow

React uses unidirectional data flow:

πŸ‘‰ Parent β†’ Child

Benefits:

  • Easy debugging
  • Predictable behavior

5. Declarative Approach

Instead of telling β€œhow to update UI”:

πŸ‘‰ You describe β€œwhat UI should look like”

Example:

const isLoggedIn = true;return isLoggedIn ? <Dashboard /> : <Login />;

6. Strong Ecosystem

React has:

  • Huge community
  • Many libraries
  • Easy integrations

Real-World Example

Imagine a shopping app:

πŸ‘‰ When you add an item:

  • Only cart updates
  • Not entire page

πŸ‘‰ This is React efficiency πŸš€


React vs Traditional Approach

FeatureTraditional JSReact
UpdatesFull pagePartial
Code reuseLowHigh
PerformanceSlowerFaster

Common Misconceptions


❌ React is a Framework

πŸ‘‰ It’s actually a library


❌ React is only for big apps

πŸ‘‰ You can use it for small apps too


When to Use React?

Use React when:

  • Building dynamic UI
  • Creating large applications
  • Need reusable components

Interview Tip

If asked:

β€œWhy is React efficient?”

πŸ‘‰ Answer:

β€œBecause it uses Virtual DOM, updates only required parts, and uses reusable components.”


Final Summary

  • React is a UI library
  • Uses components
  • Virtual DOM improves performance
  • Efficient rendering saves time

πŸ‘‰ That’s why React is widely used πŸš€

πŸ’‘ Found this helpful? Subscribe to get simple React tutorials, interview questions, and real-world examples. Happy Coding!

CSS Variables Explained: A Complete Guide with Examples (Beginner to Advanced)

CSS Variables (also called Custom Properties) are one of the most powerful features in modern CSS. They help you write clean, reusable, and maintainable styles.

In this guide, you’ll learn:

  • What CSS Variables are
  • Why we need them
  • How they work
  • Real-world examples
  • Best practices

What Are CSS Variables?

CSS Variables are custom values that you define and reuse in your CSS.

πŸ‘‰ They start with -- and are accessed using var().


Basic Example

:root {
--primary-color: blue;
}button {
background-color: var(--primary-color);
}

πŸ‘‰ Output:

  • Button background becomes blue

Why Do We Need CSS Variables?

Before CSS Variables, we had problems like:

❌ Repeating same values everywhere
❌ Difficult to update styles
❌ No dynamic theming


Example Without Variables

button {
background-color: blue;
}.header {
color: blue;
}

πŸ‘‰ If you want to change blue β†’ red, you must update everywhere ❌


With CSS Variables

:root {
--primary-color: blue;
}button {
background-color: var(--primary-color);
}.header {
color: var(--primary-color);
}

πŸ‘‰ Change once β†’ updated everywhere βœ…


How CSS Variables Work


πŸ”Ή Defining Variables

:root {
--main-color: green;
}

πŸ‘‰ :root = global scope


πŸ”Ή Using Variables

p {
color: var(--main-color);
}

Scope of CSS Variables


πŸ”Ή Global Scope

:root {
--color: red;
}

πŸ‘‰ Available everywhere


πŸ”Ή Local Scope

.card {
--color: blue;
}.card p {
color: var(--color);
}

πŸ‘‰ Only inside .card


Updating Variables Dynamically

You can update variables using JavaScript:

document.documentElement.style.setProperty('--primary-color', 'red');

πŸ‘‰ Instantly updates UI πŸ”₯


Real-World Use Case: Theme Switching


Light Theme

:root {
--bg-color: white;
--text-color: black;
}

Dark Theme

.dark {
--bg-color: black;
--text-color: white;
}

Usage

body {
background-color: var(--bg-color);
color: var(--text-color);
}

πŸ‘‰ Just toggle .dark class β†’ theme changes instantly


Fallback Values (Very Important)

color: var(--primary-color, red);

πŸ‘‰ If variable not defined β†’ fallback to red


Advanced Example

:root {
--spacing: 10px;
}.container {
padding: calc(var(--spacing) * 2);
}

πŸ‘‰ Works with calculations πŸ”₯


πŸ†š CSS Variables vs SCSS Variables

FeatureCSS VariablesSCSS Variables
Runtime changeβœ… Yes❌ No
Works in browserβœ… Yes❌ Precompiled
Dynamic themesβœ… Yes❌ No

Best Practices

  • Use meaningful names (--primary-color)
  • Define global variables in :root
  • Avoid overusing variables
  • Use for themes and reusable values

Where CSS Variables Are Used

  • React (MUI, Tailwind configs)
  • Theming systems
  • Design systems
  • Dark/light mode

Interview Tip

If asked:

β€œWhat are CSS variables?”

πŸ‘‰ Answer:

β€œCSS variables are reusable custom properties that allow dynamic styling and runtime updates in CSS.”


🏁 Final Summary

  • CSS Variables improve maintainability
  • They support dynamic updates
  • Useful for themes and reusable styles
  • Work directly in browser

Related Articles


πŸ’‘ Found this helpful? Subscribe to get simple frontend tutorials, real-world examples, and developer tips. Happy Coding!