0
0
Javascriptprogramming~3 mins

Why Variable declaration using var in Javascript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could stop rewriting the same number everywhere and just use a simple name instead?

The Scenario

Imagine you want to store a number to use later in your program. Without declaring a variable, you might try to write the number everywhere you need it, or just use it directly without a name.

The Problem

This approach is slow and confusing because you have to change every place manually if the number changes. It also causes mistakes if you forget to update some places. Without a clear name, your code becomes hard to read and understand.

The Solution

Using var lets you give a name to a value. You can store the value once and use the name everywhere. If the value changes, you only update it in one place. This makes your code cleaner, easier to read, and less error-prone.

Before vs After
Before
console.log(10 + 20);
console.log(10 + 30);
After
var x = 10;
console.log(x + 20);
console.log(x + 30);
What It Enables

It enables you to write clear, reusable, and easy-to-update code by naming your data.

Real Life Example

Think of var like labeling a jar of sugar in your kitchen. Instead of guessing or remembering how much sugar to add each time, you just look at the label and use the right amount.

Key Takeaways

Variables let you name and store values.

var is a way to declare variables in JavaScript.

Using variables makes your code easier to manage and less error-prone.