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!

Don’t Depend Too Much on AI for Coding — It Can Kill Your Skills

AI tools like GitHub Copilot and ChatGPT are changing how we write code.

They help us:

  • Write faster
  • Debug quicker
  • Learn new concepts

But there’s a serious problem many developers are ignoring:

⚠️ Over-dependence on AI can slowly kill your thinking ability.


⚠️ The Hidden Problem

If you use AI tools for everything:

  • Writing code
  • Fixing bugs
  • Understanding logic

👉 Your brain starts doing less work.

Over time:

❌ You stop thinking deeply
❌ You stop solving problems on your own
❌ You rely on suggestions instead of logic


What Happens in the Long Run?

❌ 1. You Lose Problem-Solving Skills

Coding is not about typing code.

It’s about:

  • Thinking
  • Breaking problems
  • Designing solutions

👉 AI removes that struggle — and that’s dangerous.


❌ 2. You Become Dependent

Imagine this:

👉 You’ve been using AI tools daily for months or years

Now suddenly:

  • AI is down ❌
  • No internet ❌
  • Tool not available ❌

👉 What happens?

⚠️ You feel completely blocked.

Even if you knew the concept before…
👉 your brain is no longer used to thinking without help.


❌ 3. False Confidence

AI gives answers quickly.

👉 You feel productive
👉 You feel skilled

But in reality:

❌ You didn’t solve the problem — AI did


❌ 4. Weak Debugging Skills

When something breaks:

👉 You don’t know:

  • Why it happened
  • How to fix it
  • Where to look

Real Truth

💡 AI is powerful — but it should assist your thinking, not replace it.


Developer Mindset You Must Follow

Think like this:

👉 AI = Assistant
👉 YOU = Developer (Decision Maker)


Use AI for:

  • Suggestions
  • Speed
  • Learning

Don’t use AI for:

  • Blind copy-paste
  • Every small problem
  • Thinking replacement

Balanced Approach (Best Practice)

Step 1: Try Yourself First

  • Think about solution
  • Write your approach

Step 2: Use AI

  • Compare solutions
  • Improve your code

Step 3: Understand It

  • Why this works?
  • Can I explain this?

Warning Sign You Are Overdependent

Ask yourself:

  • Can I solve problems without AI?
  • Do I understand what I copy?
  • Can I debug without help?

👉 If “NO” → you are becoming dependent


Strong Advice (Very Important)

💡 “Don’t let your brain become lazy because of powerful tools.”


Final Thoughts

AI is not the enemy.

But blind dependency is.

✔ Use AI wisely
✔ Keep your thinking active
✔ Practice problem-solving

Because in the long run:

💡 Your skill is your real asset — not the tool you use.


💡 If this post made you think, subscribe for more real developer insights. Build skills, not dependency. Happy Coding!

React SVG Import: What Does “ReactComponent as” Mean?

If you’ve worked with React, you might have seen this syntax:

import { ReactComponent as SomeIcon } from 'assets/some-icon.svg';

And wondered:

🤔 What is ReactComponent?
🤔 How is an SVG becoming a React component?
🤔 When should we use this?

Let’s break it down step-by-step in a very simple way 👇


What Does This Syntax Mean?

import { ReactComponent as SomeIcon } from 'assets/some-icon.svg';

👉 This means:

“Import the SVG file and use it as a React component”


Usage

<SomeIcon />

👉 Instead of:

<img src="some-icon.svg" />

How Does This Actually Work?

This is not plain JavaScript behavior.

👉 It is handled by your build tool (like Webpack or Vite).


Behind the Scenes

Tools like:

  • SVGR (SVG to React transformer)

convert your SVG file into:

function SomeIcon(props) {
return (
<svg {...props}>
{/* SVG content */}
</svg>
);
}

👉 So your SVG becomes a React component internally


Normal SVG vs React Component

❌ Traditional Way

<img src="/icon.svg" alt="icon" />

✅ React Component Way

import { ReactComponent as Icon } from './icon.svg';

<Icon />

Why Use SVG as React Component?


1. Easy Styling

<Icon style={{ color: 'red', width: 50 }} />

👉 You can style it like a component


2. Dynamic Props

<Icon width={30} height={30} />

3. Better Control

You can:

  • Change color
  • Animate
  • Add events

Add Event Handlers

<Icon onClick={() => alert('Clicked')} />

Example (Real Usage)

SVG File

<!-- icon.svg -->
<svg viewBox="0 0 24 24">
<path d="..." />
</svg>

React Usage

import { ReactComponent as Icon } from './icon.svg';

function App() {
return <Icon width={40} height={40} />;
}

Styling with CSS

.icon {
fill: blue;
}
<Icon className="icon" />

Important Note (Color Control)

For dynamic color:

👉 SVG must use:

fill="currentColor"

👉 Then:

<Icon style={{ color: 'green' }} />

Common Mistakes

❌ Using wrong import

import Icon from './icon.svg'; // ❌

👉 This gives image path, not component


❌ Missing configuration

👉 Works only if:

  • CRA (Create React App)
  • Vite (with plugin)
  • Webpack configured

When It Works Automatically

Works out-of-the-box in:

  • Create React App
  • Vite (with SVGR plugin)
  • Next.js (with config)

When to Use <img> vs Component

Use <img> when:

  • Simple display
  • No styling needed

Use React Component when:

  • Need styling
  • Need animations
  • Need dynamic behavior

Interview Tip

If asked:

“What is ReactComponent as in SVG import?”

👉 Answer:

“It converts SVG into a React component using tools like SVGR, allowing us to use it like JSX.”


Final Summary

  • ReactComponent converts SVG → React component
  • Enables styling, events, and dynamic behavior
  • Powered by tools like SVGR
  • Better than <img> for interactive UI

Related Articles


💡 Found this helpful? Subscribe for simple React tips, real-world examples, and developer-friendly tutorials. Happy Coding!

AI Can Make Mistakes: Why Developers Must Always Verify Before Trusting

Artificial Intelligence is transforming the way we write code, debug issues, and build products.

From generating functions to explaining complex concepts, AI tools feel like a superpower.

But here’s the truth that every developer must understand:

⚠️ AI can make mistakes. And sometimes, very confidently.


What Does It Mean That AI Can Make Mistakes?

AI doesn’t “know” things the way humans do.

It doesn’t:

  • Understand truth
  • Verify facts in real-time
  • Guarantee correctness

Instead, it works based on patterns learned from data.

👉 This leads to something called:

AI Hallucination

AI hallucination means generating information that sounds correct but is actually wrong or misleading.


Example of AI Mistake

Imagine asking AI:

👉 “Write a function to sort numbers”

It may give you code that:

  • Works for some cases ✅
  • Fails for edge cases ❌
  • Uses outdated methods ⚠️

👉 If you blindly copy-paste → bugs enter your system


The Real Responsibility Lies with Developers

This is the most important part:

💡 AI is your assistant. You are the decision maker.

Think of it like this:

  • AI = Junior helper
  • Developer = Boss

👉 The assistant suggests
👉 The boss decides


Why You Should Never Blindly Trust AI

❌ 1. AI Can Be Confidently Wrong

AI often gives answers that look perfect—but are incorrect.


❌ 2. No Context Awareness

AI may not fully understand:

  • Your project structure
  • Business logic
  • Edge cases

❌ 3. Outdated Information

Sometimes AI suggestions:

  • Use deprecated APIs
  • Ignore latest best practices

❌ 4. Security Risks

Blindly trusting AI can lead to:

  • Vulnerable code
  • Poor authentication logic
  • Unsafe API usage

What a Good Developer Should Do

1. Always Cross-Check

  • Read the code carefully
  • Verify logic
  • Test different scenarios

2. Test Everything

Never skip testing:

  • Edge cases
  • Error handling
  • Performance

3. Verify with Documentation

Always confirm with:

  • Official docs
  • Trusted sources

4. Use Your Logic

Ask yourself:

  • Does this make sense?
  • Is this optimal?
  • Is there a better way?

5. Think About Security

Before using AI-generated code:

  • Validate inputs
  • Avoid exposing sensitive data
  • Follow best practices

Real-World Analogy

Imagine:

You are a team lead, and AI is a junior developer.

👉 The junior writes code
👉 You review it

Would you deploy it without checking?

👉 No.

Same rule applies here.


What Happens If You Trust AI Blindly?

  • Bugs in production
  • Security vulnerabilities
  • Poor performance
  • Loss of user trust

Smart Way to Use AI

Use AI as:

✅ Idea generator
✅ Code helper
✅ Learning assistant

But not as:

❌ Final decision maker
❌ Source of truth


Developer Mindset (Very Important)

“Don’t copy-paste. Understand and verify.”

This mindset separates:

👉 Average developers
👉 From great developers


🏁 Final Thoughts

AI is powerful. No doubt.

But:

💡 A powerful tool in careless hands can create problems.

As a developer:

  • You are responsible
  • You make the final call
  • You own the product

👉 So don’t go blind.

👉 Think, verify, and then implement.


💡 If this content is helpful to you, please subscribe. More practical developer insights are coming. Happy Coding!

Higher Order Components (HOC) in React: Complete Guide with Examples

When working with React, you’ll often need to reuse logic across multiple components.

That’s where Higher Order Components (HOC) come into the picture.

In this guide, you’ll learn:

  • What a Higher Order Component is
  • Why we need it
  • How it works
  • Multiple real-world examples
  • When to use and when to avoid

What is a Higher Order Component (HOC)?

Simple Definition

A Higher Order Component (HOC) is a function that takes a component and returns a new enhanced component.


Syntax

const EnhancedComponent = higherOrderComponent(WrappedComponent);

Simple Example

function withLogger(Component) {
return function EnhancedComponent(props) {
console.log("Component rendered");
return <Component {...props} />;
};
}

👉 Usage:

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

const EnhancedButton = withLogger(Button);

Why Do We Need HOC?

Without HOC:

❌ Duplicate logic in multiple components

With HOC:

✅ Reuse logic
✅ Cleaner code
✅ Better maintainability


How HOC Works (Step-by-Step)

  1. Take a component as input
  2. Add extra logic
  3. Return a new component
  4. Render original component with props

Scenario 1: Logging (Basic Example)

function withLogger(Component) {
return function (props) {
console.log("Props:", props);
return <Component {...props} />;
};
}

Scenario 2: Authentication (Very Common)

HOC

function withAuth(Component) {
return function (props) {

const { isLoggedIn } = useContext(AuthContext);

if (!isLoggedIn) {
return <h2>Please Login</h2>;
}

return <Component {...props} />;
};
}

Usage

function Dashboard() {
return <h1>Welcome to Dashboard</h1>;
}

export default withAuth(Dashboard);

Scenario 3: API Data Fetching


HOC

import { useEffect, useState } from "react";

function withData(Component, url) {
return function (props) {
const [data, setData] = useState([]);

useEffect(() => {
fetch(url)
.then(res => res.json())
.then(setData);
}, []);

return <Component data={data} {...props} />;

};
}

Usage

function Users({ data }) {
return <div>{data.length} Users</div>;
}

export default withData(Users, "/api/users");

Scenario 4: Loading State

function withLoading(Component) {
return function ({ isLoading, ...props }) {
if (isLoading) return <p>Loading...</p>;
return <Component {...props} />;
};
}

Scenario 5: Reusing Styles

function withStyle(Component) {
return function (props) {
return (
<div style={{ border: "1px solid black", padding: "10px" }}>
<Component {...props} />
</div>
);
};
}

Common Mistakes


❌ Forgetting to pass props

return <Component />; // ❌

👉 Fix:

return <Component {...props} />; // ✅

❌ Mutating original component

👉 Always return a new component


HOC vs Hooks


HOC

  • Works with class components
  • Reusable logic

Hooks

  • Simpler
  • Preferred in modern React

When to Use HOC

Use HOC when:

  • You need reusable logic
  • Working with legacy/class components
  • Cross-cutting concerns (auth, logging)

When to Avoid HOC

Avoid when:

  • Hooks can solve it easily
  • Too many nested HOCs (complexity increases)

🧠 Interview Tip

If asked:

“What is HOC?”

👉 Answer:

“A Higher Order Component is a function that takes a component and returns a new component with added functionality.”


🏁 Final Summary

  • HOC = function that enhances components
  • Helps reuse logic
  • Used for auth, logging, data fetching
  • Hooks are modern alternative

🔗 Related Articles

👉 Add these:


💡 Found this helpful? Subscribe for simple React guides, real-world examples, and interview preparation tips. Happy Coding!