JavaScript Variables & Data Types

Storing and Working with Data

Variables are containers for storing data values. JavaScript has three ways to declare variables: var, let, and const.

JavaScript is a dynamically typed language, meaning variables can hold any type of data.

// Variables
let name = 'John';        // String
const age = 25;           // Number
let isStudent = true;     // Boolean
let hobbies = ['reading', 'coding'];  // Array
let person = { name: 'John', age: 25 };  // Object
let nothing = null;       // Null
let notDefined;           // Undefined

// Variable Declaration
let x;          // Declare
x = 10;         // Assign
let y = 20;     // Declare and assign

// Const (cannot be reassigned)
const PI = 3.14159;
// PI = 3.14;   // Error!

// Let vs Var
let blockScoped = 'accessible in block';
var functionScoped = 'accessible in function';
  • let - Block-scoped, can be reassigned
  • const - Block-scoped, cannot be reassigned
  • var - Function-scoped (old way, avoid)
  • String - Text in quotes
  • Number - Integers and decimals
  • Boolean - true or false
  • Array - List of values
  • Object - Key-value pairs
  • null - Intentionally empty
  • undefined - Not yet defined

Try Variables

<div id="output"></div>
<button onclick="showVariables()">Show Variables</button>

Note: Always use const by default. Use let only when you need to reassign. Avoid var.