Variables and Data Types
Why this matters: Variables are how your program remembers things. Every piece of data your code touches, whether that is a user's name, the price of an item or a list of provinces, lives in a variable. JavaScript's variable system has three keywords, six core data types and a few historical quirks. Once you know what to use when, you have most of what you need to write real programs.
Three keywords for declaring a variable
Modern JavaScript has three ways to declare a variable: let, const and var. You will use the first two constantly and the third one almost never. Here is the decision in one sentence:
| When you need... | Use |
|---|---|
| A value that should never be reassigned (the safe default) | const |
| A value that you genuinely need to reassign later | let |
| Anything else | var is the old keyword. Avoid it. |
const (the safe default)
const declares a constant: once set, the variable cannot be reassigned.
const SCHOOL_NAME = "HardCoded";
const VAT_RATE = 0.15;
const MAX_STUDENTS = 100;
// This would throw an error:
// SCHOOL_NAME = "New Name"; // TypeError: Assignment to constant variable.
Default to const for almost everything. If your code never reassigns the variable, const is the right choice. This is the convention at most modern JavaScript shops.
let (when you need to reassign)
let is the right choice when the variable's value will change.
let studentName = "Thabo";
let attemptsRemaining = 3;
studentName = "Naledi"; // Fine
attemptsRemaining = attemptsRemaining - 1; // Fine
var (the old way, avoid)
var was the only option for the first 20 years of JavaScript. It has historical scoping rules that surprise beginners and produce subtle bugs.
var oldWay = "Don't use this";
The short version: any modern codebase you join will use const and let. Pretend var does not exist.
The six core data types
JavaScript values fall into one of six core types. Get comfortable with these and the rest of the language clicks into place.
1. String
A string is text in quotes. Single, double or backticks all work.
const firstName = "Sipho";
const lastName = 'Nkosi';
const city = `Johannesburg`;
Backtick strings are called template literals and have a superpower: you can embed variables inside them with ${...}.
const greeting = `Hello, my name is ${firstName} ${lastName}`;
console.log(greeting); // Hello, my name is Sipho Nkosi
We will spend a whole lesson on template literals later. For now, just know they exist.
2. Number
JavaScript has one number type that handles both whole numbers and decimals.
const age = 25;
const price = 199.99;
const temperature = -5;
const sum = 10 + 5; // 15
const product = 6 * 7; // 42
const remainder = 17 % 5; // 2
3. Boolean
True or false. The basis for any decision your program makes.
const isStudent = true;
const hasGraduated = false;
const canEnroll = isStudent && !hasGraduated; // true
4. Array
An ordered list of values. Arrays use square brackets.
const provinces = ["Gauteng", "Western Cape", "KwaZulu-Natal"];
const scores = [82, 75, 91, 67];
5. Object
A bag of named values. Objects use curly braces with key: value pairs.
const student = {
name: "Lerato",
age: 21,
course: "JavaScript Essentials",
province: "Gauteng",
};
Objects are how you represent anything with multiple attributes: a user, a product, a database row, a network response. You will see them everywhere.
6. Undefined and null
This is the one part of JavaScript that genuinely catches beginners.
let userName; // undefined (declared but no value yet)
let selectedCourse = null; // null (deliberately empty)
The difference matters:
undefinedmeans "no value has ever been set". JavaScript hands this back when you read a variable that exists but has not been assigned, or look up an object key that does not exist.nullmeans "I deliberately set this to nothing". It is something you write yourself when you want to say "this slot is intentionally empty".
In practice, you use undefined rarely (the language gives it to you automatically) and null when you explicitly want to clear a value.
Checking what type something is
The typeof operator tells you what kind of value you are holding:
console.log(typeof "Hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (yes, this is a famous bug)
That last one is the most famous bug in the JavaScript language. typeof null returns "object" instead of "null", and it has not been fixed because doing so would break millions of existing programs. Live with it.
Variable naming rules
A few rules and conventions:
- Start with a letter, underscore (
_) or dollar sign ($) - Can contain letters, digits, underscores and dollar signs
- Cannot be a JavaScript reserved word (
if,class,return, etc) - Are case sensitive:
userNameandusernameare different variables - Use camelCase for variables and functions:
studentName,attemptsRemaining - Use SCREAMING_SNAKE_CASE for constants you intend to never change:
MAX_STUDENTS,VAT_RATE
const userName = "Thabo"; // camelCase
const MAX_USERS = 100; // SCREAMING_SNAKE_CASE for "true" constants
let attemptsRemaining = 3; // camelCase, mutable
Putting it together
A small example using most of the things in this lesson:
const SCHOOL_NAME = "HardCoded Academy";
let currentStudents = 150;
const student = {
name: "Nomsa Dlamini",
age: 23,
city: "Durban",
enrolled: true,
};
console.log(`${student.name} is enrolled at ${SCHOOL_NAME}`);
console.log(`We have ${currentStudents} students this term.`);
// New student signs up
currentStudents = currentStudents + 1;
console.log(`Now we have ${currentStudents}.`);
What's next
In the next lesson we look at operators: how to combine values, do comparisons and make decisions. You already used a few here (+, *, &&, !). The next lesson maps them all out and shows the modern features (??, ?.) that make JavaScript feel like a different language compared to a decade ago.