Variables and Data Types
Learn how to store and work with data in JavaScript.
3 min read
Variables are containers for storing data values. In JavaScript, we have several ways to declare variables and multiple data types to work with.
Declaring Variables
JavaScript has three keywords for declaring variables:
let
Use let for variables that will change:
let score = 0;
score = 10; // ✓ Can be reassigned
score = 20; // ✓ Can be reassigned again
const
Use const for values that shouldn't change:
const PI = 3.14159;
PI = 3; // ✗ Error! Cannot reassign a const
var (Legacy)
var is the old way of declaring variables. Use let and const instead:
var oldWay = "Don't use this";
Data Types
JavaScript has several primitive data types:
Strings
Text values, enclosed in quotes:
const name = "Alice";
const greeting = 'Hello!';
const template = `Hello, ${name}!`; // Template literal
Numbers
Both integers and decimals:
const age = 25;
const price = 19.99;
const negative = -10;
Booleans
True or false values:
const isLoggedIn = true;
const hasAccess = false;
Undefined and Null
let notYetAssigned; // undefined
const empty = null; // intentionally empty
Type Checking
Use typeof to check a value's type:
console.log(typeof "hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
String Operations
const firstName = "John";
const lastName = "Doe";
// Concatenation
const fullName = firstName + " " + lastName;
// Template literals (preferred)
const greeting = `Hello, ${firstName}!`;
// String methods
console.log(firstName.length); // 4
console.log(firstName.toUpperCase()); // "JOHN"
console.log(fullName.includes("Doe")); // true
Number Operations
const a = 10;
const b = 3;
console.log(a + b); // 13 (addition)
console.log(a - b); // 7 (subtraction)
console.log(a * b); // 30 (multiplication)
console.log(a / b); // 3.333... (division)
console.log(a % b); // 1 (remainder)
console.log(a ** b); // 1000 (exponentiation)
Practice Exercise
Try creating variables for your profile:
const myName = "Your Name";
const myAge = 25;
const isStudent = true;
console.log(`My name is ${myName}.`);
console.log(`I am ${myAge} years old.`);
console.log(`Am I a student? ${isStudent}`);
Summary
- Use
constby default,letwhen you need to reassign - JavaScript has strings, numbers, booleans, undefined, and null
- Template literals make string formatting easier
- Use
typeofto check data types
In the next chapter, we'll learn about operators and how to manipulate data.