DEV Community

Cover image for Understanding Variables and Data Types in JavaScript
Pratham
Pratham

Posted on

Understanding Variables and Data Types in JavaScript

A beginner-friendly guide to the building blocks of every JavaScript program.


When I first started learning JavaScript through ChaiCode's Web Dev Cohort 2026, the very first thing that tripped me up wasn't some complex algorithm or a fancy framework — it was something embarrassingly basic: variables. I kept confusing let with const, wondering why var even existed, and honestly, I didn't fully understand what "data types" even meant in a practical sense.

So if you're in the same boat right now, relax. This article is for you. I'm going to break down variables and data types in the simplest way I know — the way I wish someone had explained them to me on day one.


What Are Variables (And Why Should You Care)?

Let's forget code for a second. Think about a cardboard box.

You grab a box, slap a label on it that says "shoes", and put your sneakers inside. Now whenever you need your shoes, you just look for the box labeled "shoes." You don't need to remember where the shoes physically are — the label does that job for you.

That's exactly what a variable is in JavaScript. It's a labeled container that stores a piece of information (a value) so that your program can use it later.

Without variables, you'd have to hardcode every single value everywhere. Imagine writing the same email address 47 times across your app. Now imagine the user changes their email. Good luck finding and updating all 47 spots. Variables save you from that nightmare.

let userEmail = "pratham@prathamdev.in";

// Now I can use 'userEmail' anywhere instead of typing the actual address
console.log(userEmail); // "pratham@prathamdev.in"
Enter fullscreen mode Exit fullscreen mode

Simple, right? You give it a name, you give it a value, and JavaScript remembers it for you.


Declaring Variables: var, let, and const

JavaScript gives you three keywords to create variables. Let's look at each one.

var — The Old Way

var is the original way to declare variables in JavaScript. It's been around since the beginning. You'll still see it in older codebases and tutorials, but modern JavaScript has moved on from it for good reasons (which we'll get to).

var city = "Delhi";
console.log(city); // "Delhi"

var city = "Gurugram"; // No error — var lets you re-declare
console.log(city); // "Gurugram"
Enter fullscreen mode Exit fullscreen mode

let — The Modern, Flexible Choice

let was introduced in ES6 (2015) and is now the go-to for variables whose values might change over time. Unlike var, it won't let you accidentally re-declare the same variable in the same scope.

let score = 0;
console.log(score); // 0

score = 10; // Reassigning is fine
console.log(score); // 10

// let score = 20; // ❌ Error! Can't re-declare with let
Enter fullscreen mode Exit fullscreen mode

const — For Values That Don't Change

If you know a value should stay the same throughout your program, use const. It stands for "constant." Once you assign a value, that's it — no take-backs.

const PI = 3.14159;
console.log(PI); // 3.14159

// PI = 3.14; // ❌ TypeError: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

A good rule of thumb I follow: start with const by default. Only switch to let when you realize the value actually needs to change. And var? Just avoid it unless you have a very specific reason.


Quick Comparison: var vs let vs const

Here's a side-by-side table that clears things up fast:

Feature var let const
Re-declaration ✅ Allowed ❌ Not allowed ❌ Not allowed
Reassignment ✅ Allowed ✅ Allowed ❌ Not allowed
Scope Function-scoped Block-scoped Block-scoped
Introduced in ES1 (1997) ES6 (2015) ES6 (2015)
Best for Legacy code Values that change Values that stay fixed

💡 Pro tip: In 2026, there's almost no reason to use var in new code. let and const are safer, more predictable, and easier to debug.


Primitive Data Types in JavaScript

Alright, so variables are boxes. But what kind of stuff can you put inside those boxes? That's where data types come in.

JavaScript has several primitive (basic) data types. Let's walk through the five you'll use most often:

1. String — Text

Anything wrapped in quotes is a string. Your name, a message, an address — if it's text, it's a string.

let name = "Pratham";
let greeting = 'Hello, World!';
let bio = `I'm learning JavaScript`; // Template literal (backticks)

console.log(name);     // "Pratham"
console.log(greeting); // "Hello, World!"
console.log(bio);      // "I'm learning JavaScript"
Enter fullscreen mode Exit fullscreen mode

2. Number — Numbers (Obviously)

JavaScript doesn't differentiate between integers and decimals. They're all just "numbers."

let age = 22;
let price = 499.99;
let negative = -10;

console.log(age);      // 22
console.log(price);    // 499.99
console.log(negative); // -10
Enter fullscreen mode Exit fullscreen mode

3. Boolean — True or False

Booleans are like yes/no switches. They can only be true or false. Super useful for conditions and decision-making in your code.

let isStudent = true;
let hasGraduated = false;

console.log(isStudent);    // true
console.log(hasGraduated); // false
Enter fullscreen mode Exit fullscreen mode

4. Undefined — "I Exist, But I'm Empty"

When you declare a variable but don't assign it a value, JavaScript gives it undefined by default. It basically means "this variable exists, but nobody told me what to put in it."

let futureProject;
console.log(futureProject); // undefined
Enter fullscreen mode Exit fullscreen mode

5. Null — "Intentionally Empty"

null looks similar to undefined, but there's a key difference: you set it deliberately. It means "I know this variable exists, and I'm intentionally saying it has no value right now."

let selectedUser = null; // No user selected yet
console.log(selectedUser); // null
Enter fullscreen mode Exit fullscreen mode

Quick Reference: Data Types at a Glance

Data Type Example What It Represents
String "Pratham" Text
Number 22, 3.14 Numeric values
Boolean true, false Yes/No, On/Off decisions
Undefined undefined Declared but no value assigned
Null null Intentionally empty

What Is Scope? (A Beginner-Friendly Explanation)

Scope is one of those words that sounds intimidating but is actually pretty intuitive once you see it.

Scope answers one question: "Where can I access this variable?"

Think of it like rooms in a house. If you put a book on your bedroom desk, you can see it from anywhere inside that bedroom. But if you walk into the kitchen, that book isn't visible anymore. The bedroom is the book's scope.

In JavaScript, curly braces { } create a "room" (a block). Variables declared with let and const inside that block are only accessible within it. Variables declared with var are a bit more rebellious — they ignore block boundaries and attach themselves to the nearest function.

Block Scope (let and const)

{
  let secret = "You can't see me outside";
  console.log(secret); // ✅ Works fine here
}

// console.log(secret); // ❌ ReferenceError: secret is not defined
Enter fullscreen mode Exit fullscreen mode

The variable secret only lives inside those curly braces. Once you step outside, it's gone.

Function Scope (var)

function greet() {
  var message = "Hello!";
  console.log(message); // ✅ Works
}

greet();
// console.log(message); // ❌ ReferenceError — var is still function-scoped
Enter fullscreen mode Exit fullscreen mode

A Simple Scope Visualization

🏠 Global Scope (accessible everywhere)
│
├── let appName = "MyApp"        ← visible everywhere
│
├── function login() {           ← Function Scope
│   ├── let username = "pratham" ← only visible inside login()
│   │
│   ├── if (true) {              ← Block Scope
│   │   ├── let token = "abc"    ← only visible inside this if-block
│   │   └── const role = "admin" ← only visible inside this if-block
│   │   }
│   │
│   └── console.log(username)    ← ✅ works
│       console.log(token)       ← ❌ not accessible here
│
└── console.log(appName)         ← ✅ works
    console.log(username)        ← ❌ not accessible here
Enter fullscreen mode Exit fullscreen mode

The simple rule: inner scopes can look outward, but outer scopes can't look inward. A function can access global variables, but the global scope can't peek into a function's local variables.


Let's Practice: A Small Assignment

Here's a quick hands-on exercise to solidify everything we've covered. Try this in your browser console or in VS Code:

Step 1: Declare Variables

// Using different declaration keywords
const name = "Pratham";
let age = 22;
let isStudent = true;
Enter fullscreen mode Exit fullscreen mode

Step 2: Print Them

console.log("Name:", name);         // Name: Pratham
console.log("Age:", age);           // Age: 22
console.log("Is Student:", isStudent); // Is Student: true
Enter fullscreen mode Exit fullscreen mode

Step 3: Try Changing Values

// Changing a 'let' variable — works fine
age = 23;
console.log("Updated Age:", age); // Updated Age: 23

isStudent = false;
console.log("Still a student?", isStudent); // Still a student? false

// Now try changing a 'const' variable
// name = "Someone Else"; // ❌ Uncomment this line and watch it throw a TypeError!
Enter fullscreen mode Exit fullscreen mode

What You'll Observe

  • let variables are happy to be reassigned. No drama.
  • const variables will throw a TypeError the moment you try to change them. They're committed.
  • This is exactly why const is great for values you want to protect from accidental changes.

Key Takeaways

Let me wrap this up with the essentials:

  1. Variables are named containers that store values. They make your code dynamic and reusable.
  2. Use const by default. Switch to let only when you need to reassign. Forget var exists (for now).
  3. JavaScript has five main primitive data types: string, number, boolean, undefined, and null.
  4. Scope determines where a variable is accessible. let and const respect block scope. var only respects function scope.
  5. Practice is everything. Don't just read — open your console and type things out. Break stuff. That's how you learn.

Wrapping Up

Variables and data types might seem too basic to spend time on, but trust me — getting these fundamentals rock-solid pays off massively when you start building real projects. Every React component, every API call, every DOM manipulation you'll ever write relies on these concepts.

I'm currently learning full-stack development through the ChaiCode Web Dev Cohort 2026 under Hitesh Chaudhary and Piyush Garg, and writing articles like this is my way of making sure I actually understand what I'm learning — not just memorize it.

If you found this helpful, feel free to connect with me on LinkedIn or check out my portfolio at PrathamDEV.in. I'll be writing more articles as I go deeper into JavaScript and web development.

Happy coding! 🚀


Written by Pratham Bhardwaj | Web Dev Cohort 2026, ChaiCode

Top comments (0)