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!

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.