Variables and Data Types

Site Admin · 11 Sep 2026 · 5 views

Variables and Data Types

Variables store data. JavaScript has three ways to declare variables: let, const, and the legacy var. Understanding data types is fundamental to writing correct code.

Declaring Variables

let age = 25;              // Can be reassigned
const PI = 3.14159;        // Cannot be reassigned
var oldWay = "avoid this"; // Function-scoped (avoid)

age = 26;                  // OK
// PI = 3.0;              // TypeError - const is immutable

Always use const by default. Use let only when you need to reassign. Never use var in modern code - its function scoping leads to bugs.

Primitive Data Types

JavaScript has six primitive types plus object:

// String
let name = "Alice";
let greeting = 'Hello';

// Number (integers and decimals)
let count = 42;
let price = 9.99;

// BigInt (arbitrary precision integers)
let huge = 9007199254740991n;

// Boolean
let isActive = true;
let isDeleted = false;

// Undefined (declared but not assigned)
let x;
console.log(x); // undefined

// Null (intentional absence of value)
let result = null;

// Symbol (unique identifier)
let id = Symbol("id");

typeof Operator

Check the type of any value:

typeof "hello"     // "string"
typeof 42          // "number"
typeof true        // "boolean"
typeof undefined   // "undefined"
typeof null        // "object" (historic bug)
typeof {}          // "object"
typeof []          // "object"

Type Coercion

JavaScript automatically converts types in some contexts. This causes surprising bugs:

"5" + 3      // "53" (string concatenation)
"5" - 3      // 2 (numeric subtraction)
true + 1      // 2 (true becomes 1)
false + "0"  // "false0" (string concatenation)

Use strict equality === instead of loose equality == to avoid type coercion surprises.

Key Points

  • Use const by default; use let when reassignment is needed.
  • Avoid var - it has confusing function-scoped behavior.
  • Primitives: string, number, BigInt, boolean, undefined, null, symbol.
  • typeof checks the type of a value (note: null returns "object").
  • Always use === to avoid type coercion bugs.
Share this post:

Comments (0)

Please login or register to comment.