Understanding Variables and Data Types in JavaScript

Published: (February 25, 2026 at 10:41 AM EST)
7 min read
Source: Dev.to

Source: Dev.to

Introduction

Welcome to the world of programming! If you are learning to code, mastering variables is essential.

Think of moving from one house to another. You have many cardboard boxes and label them—library for books, foot‑wear for shoes, etc. In programming, variables are those labeled boxes, and data types are the kinds of items you put inside them.

What Is a Variable?

In computer programming, a variable is a named (or symbolic) container used to store data values in memory. It acts as a placeholder or label for information such as:

  • User input
  • Component state
  • Results of calculations

Variables let you read, update, and manipulate data during program execution; without them, handling data would be nearly impossible.

Why Variables Are Essential

ReasonExplanation
Flexible & ReusableInstead of hard‑coding a value like 3 + 5, you can write a + b and reuse the same code with different inputs.
Data Storage & ManipulationPrograms need to remember things (e.g., usernames, game state, file data). Variables store this information in memory for later use.
Readability & MaintainabilityDescriptive names make code easier to read, understand, and modify, reducing bugs during debugging.
Managing Program LogicVariables (e.g., booleans) control flow: they decide which code block runs at runtime.

Tip: Use descriptive names such as user_name or userName instead of vague ones like name. Common naming conventions include camelCase, snake_case, PascalCase, and kebab-case.

Declaring Variables in JavaScript

In JavaScript, “declaring a variable” means creating a box and giving it a name. There are three ways to do this:

var (old‑style)

// Syntax
var userName;

var was the original way to declare variables. Modern code rarely uses it because its quirky behavior can cause bugs.

let (block‑scoped, mutable)

// Syntax
let playerScore = 0;

Use let when the variable’s value needs to change later (e.g., a player’s score).

const (block‑scoped, immutable)

// Syntax
const userDOB = 1990;

const declares a constant—a value that cannot be reassigned after its initial definition.

Note: Prefer let and const; avoid var unless you have a specific reason.

Primitive Data Types

JavaScript provides several primitive types for storing information. Below are the most common ones, with examples.

String

A sequence of characters used to store textual information. Strings are immutable (you cannot change the original string, but you can assign a new one to the same variable).

const userEmail = "something@email.com";

Number

Represents both integers and floating‑point numbers (JavaScript stores all numbers as floating‑point). It also includes special values: Infinity, -Infinity, and NaN (Not‑a‑Number).

const integer   = 10;
const floating  = 10.55;
const negative  = -10;
const infy      = Infinity;
const negInfy   = -Infinity;

Boolean

Represents logical true or false.

const isLogin = true;
const isAdmin = false;

null

Explicitly represents the absence of any object value. It has a single possible value: null.

let data = null;
console.log(typeof data); // "object" (quirk retained for backward compatibility)

undefined

Automatically assigned to a variable that has been declared but not initialized.

let score;
console.log(score); // undefined

Truthy & Falsy Values

When a value is converted to a Boolean, it becomes either truthy (true) or falsy (false). The following values are falsy:

Falsy ValueDescription
falseBoolean false
0 (including -0 and 0.0)Numeric zero
0nBigInt zero
"" or ''Empty string
nullExplicitly empty
undefinedUninitialized
NaNNot‑a‑Number

All other values are truthy.

Exercise: Open your browser’s console, declare variables of different types, and use the ! operator to see how they convert to Boolean.

Scope

Scope determines where variables, functions, or objects are accessible and visible. It defines how the JavaScript engine resolves identifiers (names) throughout your code. Scopes form a hierarchy known as the Scope Chain.

Scope TypeDescription
Global ScopeVariables declared outside any function or block. Accessible everywhere (like a light bulb in a hallway).
Function ScopeVariables declared inside a function are only accessible within that function.
Block ScopeIntroduced in ES6 with let and const. Variables declared inside {} (e.g., loops, if statements) are confined to that block.
// Global scope
let globalVar = "I am global";

function foo() {
    // Function scope
    let funcVar = "I am inside foo";

    if (true) {
        // Block scope
        const blockVar = "I am inside a block";
        console.log(blockVar); // works
    }

    console.log(funcVar); // works
    // console.log(blockVar); // ReferenceError
}

foo();
// console.log(funcVar); // ReferenceError

Understanding scope helps you avoid accidental variable collisions and keeps your code organized.

Recap

  • Variables are labeled containers for data.
  • Use descriptive names and appropriate naming conventions.
  • Prefer let and const; avoid var.
  • Know the primitive data types (string, number, boolean, null, undefined).
  • Recognize truthy vs. falsy values.
  • Master scope to control where variables live.

Happy coding! 🚀

Scope in JavaScript

  • Curly braces {} create a block that is only accessible from inside that block.
  • This includes if statements, loops, and standalone blocks.

Modules (ES6)

When using ES6 modules (import / export), variables declared inside a module are scoped to that file only. They are not global and cannot be accessed from other modules unless they are explicitly exported.

Static (Lexical) Scope

JavaScript uses static (lexical) scope, meaning a variable’s scope is determined by its position in the source code at compile time, not by where it is called at runtime.

When the interpreter looks for a variable it follows the scope chain:

  1. Look in the current (innermost) scope.
  2. If not found, move to the parent scope.
  3. Continue outward until reaching the global scope.
  4. If the variable is still not found, a ReferenceError is thrown.

var, let, and const

Each keyword defines variables with different scoping rules.

var – Function‑Scoped

  • Variables declared with var are scoped to the entire function in which they appear (or to the global scope if declared outside a function).
function varDeclaration() {
    if (true) {
        var x = 10;   // function‑scoped
    }
    console.log(x);   // 10
}

Even though x is declared inside the if block, it is accessible throughout the whole varDeclaration function.

let – Block‑Scoped

  • let limits the variable to the block ({}) where it is defined.
  • This helps prevent accidental hoisting and scope‑related bugs.

Note: Hoisting is JavaScript’s behavior of moving variable/function declarations to the top of their scope during the compilation phase.

function letDeclaration() {
    if (true) {
        let y = 20;   // block‑scoped
    }
    console.log(y);   // ReferenceError: y is not defined
}

y exists only inside the if block; accessing it outside throws a ReferenceError.

const – Block‑Scoped, Immutable Binding

  • const also creates a block‑scoped variable, but the binding cannot be reassigned.
  • The value itself may still be mutable if it’s an object or array.
function constDeclaration() {
    if (true) {
        const z = 30;   // block‑scoped
    }
    console.log(z);   // ReferenceError: z is not defined
}

Attempting to reassign z would result in a TypeError, and accessing it outside its block throws a ReferenceError.

Hands‑On Exercise

  1. Run JavaScript in the browser (e.g., via an HTML file or the console).

  2. Declare variables such as name, age, and isStudent using var, let, and const.

  3. Print them with console.log().

  4. Try to change their values:

    • var and let can be reassigned.
    • const cannot be reassigned (will throw an error).

Observe the different behaviours.

Why It Matters

Understanding the differences between var, let, and const is fundamental for writing reliable, bug‑free JavaScript. Every web developer should master these concepts to manage scope correctly.

Further Reading

  • Variables in JavaScript
  • Scopes in JavaScript
  • Differences between let, const, and var
0 views
Back to Blog

Related posts

Read more »

A Horror Story About JavaScript Promise

Before the Midnight Adventure – What’s a Promise? > “Don’t worry – it’s easier than facing a monster under the bed!” A Promise is an object that represents the...