Variables & Types
⏱ 7 min read📖 Beginner
A variable is a named container for storing a value. JavaScript has three keywords for declaring variables:
var, let, and const.
Variables are how programs remember information. You store a value in a variable, give it a name, and refer to it later. In modern JavaScript, you'll mostly use let and const.
let and const
Use const when the value won't change, and let when it will:
const siteName = "Codecraft"; // can't be reassigned
let score = 0; // can be reassigned later
score = 10; // ✓ fine
siteName = "Other"; // ✗ TypeError
💡
Default to const. Only switch to let when you know the value needs to change. This prevents accidental reassignments and makes code easier to reason about.
Data Types
JavaScript has several built-in data types:
// String — text, wrapped in quotes
const name = "Alice";
const greeting = 'Hello, world!';
const message = `Hello, ${name}!`; // template literal
// Number — integers and decimals
const age = 25;
const price = 9.99;
// Boolean — true or false
const isLoggedIn = true;
const hasError = false;
// null — intentionally empty
const selectedItem = null;
// undefined — variable declared but not assigned
let currentUser;
console.log(currentUser); // undefined
typeof
Use typeof to check what type a value is:
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" ← known quirk in JavaScript
String Operations
const first = "Jane";
const last = "Doe";
// Concatenation
const full = first + " " + last; // "Jane Doe"
// Template literals (preferred)
const full2 = `${first} ${last}`; // "Jane Doe"
// String length
console.log(full.length); // 8
// Access a character
console.log(full[0]); // "J"
// Methods
console.log(full.toUpperCase()); // "JANE DOE"
console.log(full.includes("Jane")); // true
Number Operations
const a = 10;
const b = 3;
console.log(a + b); // 13
console.log(a - b); // 7
console.log(a * b); // 30
console.log(a / b); // 3.333...
console.log(a % b); // 1 (remainder)
console.log(a ** b); // 1000 (exponent)
Arrays
Arrays store ordered lists of values:
const colors = ["red", "green", "blue"];
console.log(colors[0]); // "red"
console.log(colors.length); // 3
colors.push("yellow"); // add to end
colors.pop(); // remove from end
Objects
Objects store key-value pairs:
const user = {
name: "Alice",
age: 25,
isAdmin: false,
};
console.log(user.name); // "Alice"
console.log(user["age"]); // 25
user.age = 26; // update a property
Have anything to say about this lesson?
Your feedback helps improve these tutorials. If something was confusing or missing, let us know.