Skip to main content

Command Palette

Search for a command to run...

Variables & Data Types

Updated
β€’7 min read
Variables & Data Types
L
I am a web developer who enjoys creating modern, responsive, and user-friendly web applications. My main technologies include HTML, CSS, JavaScript, React.js, and Node.js, which I use to build clean and efficient web solutions. Currently, I am pursuing my B.Tech at National Institute of Technology Patna, where I continue to strengthen my programming and problem-solving skills. I enjoy turning ideas into practical applications and solving real-world challenges through well-structured code and thoughtful design. I am always interested in learning new technologies, working with other developers, and contributing to meaningful projects. My long-term objective is to develop strong expertise as a full-stack developer and build applications that provide real value to users. πŸš€ Interested in opportunities related to web development, frontend development, and full-stack engineering.

Before you can write any real JavaScript, you need to understand how programs store and remember information. This chapter teaches you exactly that.

What are Variables?

A program needs to remember things. Your name, your score in a game, whether you're logged in or not β€” all of this information needs to live somewhere while the program is running. That's what a variable is: a named storage location in your computer's memory.

πŸ“¦Real life analogy β€” the labelled box

Imagine a cardboard box with a label on it. The label is the variable name (like age or username). The contents inside the box are the value (like 21 or "Kalpesh"). You can open the box, look inside, change what's in it, or use its contents β€” just like you can read, update, and use a variable.

Here's what three variables "look like" as labelled boxes holding different kinds of information:

Each box has a unique label (the variable name), and whatever is inside it is the current value. You can look up the value anytime by using the label. In JavaScript, this is done with the keyword let, const, or var β€” which we'll cover in the next section.

Declaring Variables with var, let, const

To create a variable in JavaScript, you first write a keyword β€” either var, let, or const β€” then a name, then an = sign, then the value you want to store. This is called declaring a variable.

declaring.js

// Using let β€” a value you can change later
let name = "Kalpesh";
let age  = 21;

// Using const β€” a value that stays fixed
const country = "India";

// Using var β€” the old way (still works, but use let/const now)
var city = "Patna";

// Printing to console
console.log(name);    // Kalpesh
console.log(age);     // 21
console.log(country); // India

You can also declare a variable without giving it a value right away. The variable exists but its value is undefined until you assign something:

declare-later.js

let score;             // declared but no value yet
console.log(score);   // undefined

score = 95;            // now we give it a value
console.log(score);   // 95

Changing a variable's value with let is as simple as assigning a new value β€” no keyword needed the second time:

changing-values.js

let points = 10;
console.log(points); // 10

points = 20;           // update the value
console.log(points); // 20

points = 35;           // update again
console.log(points); // 35

// const cannot be updated β€” this causes an error:
const pi = 3.14;
pi = 3; // ❌ TypeError: Assignment to constant variable

⚠ const means constant β€” it cannot be changed

Once you assign a value to a const variable, it's locked. Trying to reassign it throws a TypeError. Use const for values that should never change β€” like your country of birth, a fixed tax rate, or a configuration value.

Primitive Data Types

Not all values are the same kind of thing. A name like "Kalpesh" is different from a number like 21, which is different from a yes/no flag like true. JavaScript has 5 basic (primitive) data types that every beginner needs to know.

// String β€” text wrapped in quotes
let firstName  = "Kalpesh";
let greeting   = "Hello, World!";

// Number β€” integers and decimals, no quotes
let age        = 21;
let price      = 99.99;

// Boolean β€” only two values: true or false
let isStudent  = true;
let isLoggedIn = false;

// Null β€” box exists but intentionally empty
let middleName = null;

// Undefined β€” box exists, nothing put in yet
let score;     // automatically undefined

// typeof tells you what type a value is
console.log(typeof firstName);  // "string"
console.log(typeof age);        // "number"
console.log(typeof isStudent);  // "boolean"
console.log(typeof score);      // "undefined"

πŸ’‘ null vs undefined β€” what's the difference?null

means "I know this variable exists, and I'm deliberately saying it has no value."undefinedmeans "this variable was declared but no one put a value in it yet." Think of null as an empty box you intentionally emptied, and undefined as a box someone forgot to fill.

You can always check what type a value is using the typeof keyword β€” very useful for debugging.

var vs let vs const

JavaScript has three different keywords to declare variables. If that sounds confusing, don't worry β€” by the end of this section you'll know exactly when to use each one, and which to forget about for now.

Keyword Can reassign? Block scoped? Modern style? Use when…
var βœ“ yes βœ— no old Almost never β€” legacy code only
let βœ“ yes βœ“ yes βœ“ yes Value needs to change (score, counter)
const βœ— no βœ“ yes βœ“ yes Value stays fixed (name, tax rate)
// ── var (old way) ─────────────────────────
var score = 10;
score     = 20;   // βœ“ works
var score = 30;   // βœ“ works (can re-declare! bad idea)

// ── let (modern, reassignable) ────────────
let count = 0;
count     = 1;    // βœ“ works β€” just reassign
count     = 2;    // βœ“ works again
let count = 5;    // ❌ error β€” cannot re-declare

// ── const (fixed value) ───────────────────
const PI = 3.14;
PI        = 3;    // ❌ TypeError: Assignment to constant variable

βœ… The modern rule β€” default to const, use let when needed

Start every variable as const. If you find yourself needing to change it later (a counter, a score, a toggle), switch it to let. Avoid var entirely in new code β€” it was the old way and has confusing behavior. Modern JavaScript uses let and const only.

Here's a practical example showing when each keyword is appropriate:

practical-example.js

// Fixed things β†’ const
const username  = "kalpesh_dev"; // username never changes
const birthYear = 2003;          // birth year is permanent
const TAX_RATE  = 0.18;          // 18% GST β€” fixed

// Things that change β†’ let
let score       = 0;    // score changes as you play
let isLoggedIn  = false; // changes when user logs in

// Later in the program:
score      = 50;   // user earned points
isLoggedIn = true; // user just logged in

What is Scope?

Scope refers to where in your code a variable can be seen and used. Think of it like rooms in a building. A variable declared in one room might not be visible from another room. JavaScript has two main scopes for beginners to understand: global scope and block scope.

🏠Real life analogy β€” rooms in a house

Think of your program as a house. Variables declared in the main hall (global scope) can be accessed from every room. Variables declared inside a specific bedroom (block scope β€” inside curly braces { }) can only be used in that bedroom. Once you leave that room, those variables are gone.

// Global scope β€” visible everywhere
let city = "Patna";

if (true) {
  // Block scope β€” only visible inside these { }
  let discount = 10;
  console.log(city);     // βœ“ "Patna" β€” global vars are reachable
  console.log(discount); // βœ“ 10 β€” we're inside the block
}

console.log(city);     // βœ“ "Patna" β€” still accessible outside
console.log(discount); // ❌ ReferenceError: discount is not defined
                        //    (discount only exists inside the if block)

πŸ’‘ var behaves differently β€” it ignores block scope

This is one big reason to avoid var. A variable declared with var inside a block leaks out and is accessible outside it. let and const respect block scope properly β€” which is much more predictable and safer.

// var leaks out of blocks β€” confusing behaviour
if (true) {
  var leaky = "I escaped!";
  let safe  = "I stay inside.";
}

console.log(leaky); // βœ“ "I escaped!" ← var leaked out
console.log(safe);  // ❌ ReferenceError ← let stayed inside

// This is why let and const are preferred β€” predictable scope

Every program ever written starts here β€” a variable and a value.