DEV Community

Cover image for Understanding Variables and Data Types in JavaScript
Janmejai Singh
Janmejai Singh

Posted on

Understanding Variables and Data Types in JavaScript

JavaScript Variables & Data Types Explained — The Complete Beginner's Guide

Imagine walking into a kitchen with no containers: no jars, no bowls, no bottles.

Flour on the floor. Milk on the counter. Sugar... everywhere.

That's what writing JavaScript without variables looks like.

Variables are containers for your data. They hold values so your program can use them anywhere, anytime — without chaos.

In this guide, you'll learn:

  • ✅ What variables are and why they matter
  • ✅ How to declare variables using var, let, and const
  • ✅ All primitive data types in JavaScript
  • ✅ What scope is and why it matters
  • ✅ Best practices used by real developers

Let's get into it.


📦 What Are Variables and Why Do You Need Them?

A variable is a named storage location that holds a value. You give it a name, assign it data, and use that name to reference the data throughout your code.

let name = "Jai";
let age = 24;

console.log("My name is " + name); // My name is Jai
console.log("My age is " + age);   // My age is 24
Enter fullscreen mode Exit fullscreen mode

Without variables, you'd have to repeat raw values everywhere — and updating them across a large program would be a nightmare.

Why Variables Are Essential

Benefit Description
Reusability Write a value once, use it many times
Readability userName is clearer than "Jai" hardcoded everywhere
Maintainability Change the value in one place, it updates everywhere
Dynamic behavior Programs can respond to user input and changing data

🛠️ How to Declare Variables: var, let, and const

JavaScript gives you three keywords to declare variables. Knowing when to use each one is crucial.


1. var — The Old Way (Avoid in Modern Code)

var city = "Kanpur";
Enter fullscreen mode Exit fullscreen mode

var has been around since the beginning of JavaScript. However, it comes with a quirk called function scoping (more on scope below) that leads to confusing bugs.

⚠️ Avoid var in modern JavaScript. It's still valid, but let and const solve its problems cleanly.


2. let — For Values That Change

let score = 100;
score = 200; // ✅ Allowed — value updated
console.log(score); // 200
Enter fullscreen mode Exit fullscreen mode

Use let when you need to reassign the variable later — for example, a score that increases, a counter that increments, or a status that toggles.


3. const — For Values That Stay Fixed

const pi = 3.14159;
pi = 3; // ❌ TypeError: Assignment to constant variable
Enter fullscreen mode Exit fullscreen mode

const declares a variable whose binding cannot be reassigned. Use it for values that should never change — configuration, constants, fixed references.

💡 Pro Tip: Default to const. Switch to let only when you know the value needs to change. Never use var.


Quick Comparison Table

Feature var let const
Reassignable ✅ Yes ✅ Yes ❌ No
Redeclarable ✅ Yes ❌ No ❌ No
Scope Function Block Block
Hoisted ✅ Yes (as undefined) ⚠️ Yes (TDZ) ⚠️ Yes (TDZ)
Modern Usage Rare Common Very Common

🔢 Primitive Data Types in JavaScript

A data type defines what kind of value a variable can hold. JavaScript has 7 primitive types, but as a beginner, these 5 are the ones you'll use constantly.


1. 🔤 String

A string stores text. Wrap it in single quotes, double quotes, or backticks.

let language = "JavaScript";
let greeting = 'Hello, World!';
let message = `Welcome, ${language}!`; // Template literal
Enter fullscreen mode Exit fullscreen mode

Strings support a rich set of built-in methods like .toUpperCase(), .trim(), .includes(), and more.


2. 🔢 Number

JavaScript uses a single Number type for both integers and decimals.

let age = 24;        // integer
let price = 199.99;  // decimal (float)
let negative = -50;  // negative number
Enter fullscreen mode Exit fullscreen mode

Unlike some languages, there is no separate int or float type in JavaScript.


3. ✅ Boolean

A boolean holds one of exactly two values: true or false.

let isLoggedIn = true;
let isStudent = false;
Enter fullscreen mode Exit fullscreen mode

Booleans are the backbone of conditions and logic:

if (isLoggedIn) {
  console.log("Welcome back!");
} else {
  console.log("Please log in.");
}
Enter fullscreen mode Exit fullscreen mode

4. 🚫 Null

null represents an intentionally empty value. You set it yourself to signal "this has no value right now."

let selectedUser = null; // no user selected yet
Enter fullscreen mode Exit fullscreen mode

Think of it as an empty jar — the jar exists, but it's empty on purpose.


5. ❓ Undefined

undefined means a variable has been declared but never assigned a value.

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

JavaScript sets it automatically. You don't usually assign undefined yourself.


null vs undefined — The Key Difference

This trips up many beginners:

let a = null;      // You explicitly said "empty"
let b;             // JavaScript said "not assigned yet"

console.log(a);    // null
console.log(b);    // undefined
console.log(typeof a); // "object" (quirky legacy behavior!)
console.log(typeof b); // "undefined"
Enter fullscreen mode Exit fullscreen mode
null undefined
Set by You, intentionally JavaScript, automatically
Meaning Intentionally empty No value assigned yet
typeof "object" (historical quirk) "undefined"

🌐 Understanding Scope (Beginner-Friendly)

Scope determines where in your code a variable is accessible.

Think of it like a WiFi signal. Inside the coverage zone — you're connected. Step outside — no signal.


Block Scope (let and const)

A block is any code wrapped in curly braces {}.

{
  let message = "Hello, block!";
  console.log(message); // ✅ Works here
}

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

let and const are block scoped — they live and die inside their block.


Function Scope (var)

var is scoped to the nearest function, not the block. This is why it causes bugs:

function example() {
  if (true) {
    var x = 10; // var leaks out of the if block
  }
  console.log(x); // ✅ 10 — accessible outside the if block
}
Enter fullscreen mode Exit fullscreen mode

With let, this would correctly throw an error. That's the behavior you want.


Scope Rules at a Glance

var    function scoped  (unpredictable, avoid)
let    block scoped     (predictable, modern)
const  block scoped     (predictable, modern)
Enter fullscreen mode Exit fullscreen mode

🗺️ Concept Mind Map

JavaScript Variables
│
├── What Is a Variable?
│     ├── Named storage container
│     ├── Holds a value
│     └── Reusable across the program
│
├── Declaration Keywords
│     ├── var  → old, function-scoped, avoid
│     ├── let  → modern, block-scoped, reassignable
│     └── const → modern, block-scoped, fixed binding
│
├── Primitive Data Types
│     ├── string    → text
│     ├── number    → integers & decimals
│     ├── boolean   → true / false
│     ├── null      → intentionally empty
│     └── undefined → not yet assigned
│
└── Scope
      ├── Where a variable is accessible
      ├── Block scope (let, const)
      └── Function scope (var)
Enter fullscreen mode Exit fullscreen mode

✅ Best Practices Summary

Follow these rules and your code will be cleaner and more professional from day one:

  1. Always use const by default. If the value needs to change, switch to let.
  2. Never use var. It's legacy code and scoping behavior leads to bugs.
  3. Use descriptive names. userAge beats x. isLoggedIn beats flag.
  4. Use camelCase for variable names: firstName, totalPrice, isActive.
  5. Understand null vs undefined. One is intentional; the other is automatic.

🎯 Key Takeaways

  • Variables are named containers that store data.
  • Use const for fixed values, let for changing values, and avoid var.
  • JavaScript has 5 core primitive types: string, number, boolean, null, and undefined.
  • Scope controls where a variable can be accessed — let and const are block scoped.
  • Clean variable practices = readable, maintainable, professional code.

🚀 What's Next?

Now that you understand variables and data types, the next logical steps are:

  • Operators — arithmetic, comparison, logical
  • Conditionalsif, else, switch
  • Loopsfor, while, forEach
  • Functions — reusable blocks of logic

These all build directly on top of what you just learned. Stick with it — you're building real foundations now.


Found this helpful? Drop a ❤️ and follow for more JavaScript fundamentals explained clearly. Got questions? Ask in the comments — happy to help.

Top comments (0)