Variables and Data Types
In this lesson, you'll learn how to store information in variables and work with different types of data. Variables are like labeled boxes where you can store values and use them later in your code.
What You'll Learn
- How to declare variables using
let,const, andvar - The different data types in JavaScript
- How to work with strings, numbers, and booleans
- Type conversion and checking
Declaring Variables
JavaScript has three ways to declare variables:
// let - for variables that can change
let age = 25;
console.log("Age:", age);
age = 26; // We can change it
console.log("New age:", age);
// const - for variables that won't change
const birthYear = 1998;
console.log("Birth year:", birthYear);
// birthYear = 1999; // This would cause an error!
// var - old way (avoid using this)
var name = "Alice";
console.log("Name:", name);
Best Practice: Use const by default. Only use let when you know the variable will change. Avoid var.
Basic Data Types
JavaScript has several built-in data types. Let's explore the most common ones:
Strings
Strings are used for text. You can use single quotes, double quotes, or backticks:
// Different ways to create strings
let greeting = "Hello";
let name = 'JavaScript';
let message = `Welcome to ${name}!`; // Template literal
console.log(greeting);
console.log(name);
console.log(message);
// String concatenation
let fullGreeting = greeting + ", " + name + "!";
console.log(fullGreeting);
Numbers
JavaScript has one number type for both integers and decimals:
// Integers
let count = 42;
console.log("Count:", count);
// Decimals (floating-point)
let price = 19.99;
console.log("Price:", price);
// Mathematical operations
let sum = 10 + 5;
let difference = 10 - 5;
let product = 10 * 5;
let quotient = 10 / 5;
let remainder = 10 % 3;
console.log("Sum:", sum);
console.log("Difference:", difference);
console.log("Product:", product);
console.log("Quotient:", quotient);
console.log("Remainder:", remainder);
Booleans
Booleans represent true or false values:
let isLearning = true;
let isComplete = false;
console.log("Is learning:", isLearning);
console.log("Is complete:", isComplete);
// Comparison operations return booleans
console.log("5 > 3:", 5 > 3);
console.log("5 < 3:", 5 < 3);
console.log("5 === 5:", 5 === 5);
console.log("5 !== 3:", 5 !== 3);
Undefined and Null
Two special values for "nothing":
// undefined - variable declared but not assigned
let notDefined;
console.log("Not defined:", notDefined);
// null - intentionally empty
let empty = null;
console.log("Empty:", empty);
Type Checking
You can check the type of a value using typeof:
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" (this is a JavaScript quirk!)
Recall
Reaching back to Lesson 1, no scrolling: how do you write a comment that spans several lines in JavaScript?
Type Conversion
JavaScript can convert between types:
// String to Number
let strNumber = "42";
let num = Number(strNumber);
console.log("String to number:", num);
console.log("Type:", typeof num);
// Number to String
let number = 42;
let str = String(number);
console.log("Number to string:", str);
console.log("Type:", typeof str);
// Automatic conversion (coercion)
console.log("5" + 3); // "53" (string concatenation)
console.log("5" - 3); // 2 (numeric subtraction)
console.log("5" * "2"); // 10 (numeric multiplication)
Predict
Same two numbers, two different operators. Trace both lines by hand before running. What does this log?
let a = "10" + 5;
let b = "10" - 5;
console.log(a);
console.log(b);Try It Yourself
Reading about types is not the same as working with them. This is a build task: a small program that reports its own pass/fail. You are given three fixed values and three unfinished const declarations, each one leaning on something this lesson taught — typeof, template literals, and a comparison that returns a boolean. Run it as-is and it fails immediately, telling you which value is still wrong. Fill each declaration in until every check passes and it prints All checks passed.
Nothing above spells out all three answers in one place — you've seen typeof, template literals, and comparison operators as separate ideas, so you'll assemble them yourself. The starter already has the data, the placeholders, and the checks; you replace only the right-hand side of each const.
Build
Finish the build. Three const declarations start out as undefined placeholders, and the checks below them fail until each one holds the right value. Run it as-is to see which check fails first, decide what that value should be, then replace each placeholder until it prints 'All checks passed.' The checks run top to bottom, so the first failure you see is TODO 1 — fix it first, then work down.
const assert = require('assert');
// The data: a small set of values to inspect. Do NOT change these.
const sampleNull = null;
const personName = "Alice";
const personAge = 20;
// TODO 1: the type of sampleNull as a string, using typeof.
// typeof null -> "object"
const nullType = undefined; // replace undefined with your code
// TODO 2: a one-line label from personName and personAge, using a template literal.
// "Alice" and 20 -> "Alice is 20 years old"
const label = undefined; // replace undefined with your code
// TODO 3: whether personAge is 18 or older, as a boolean.
// 20 >= 18 -> true
const adult = undefined; // replace undefined with your code
// --- Build checks: these must all pass. Do not edit below this line. ---
assert.strictEqual(
nullType,
"object",
"nullType should be the type of sampleNull as reported by typeof",
);
assert.strictEqual(
label,
"Alice is 20 years old",
"label should combine personName and personAge into one labeled string",
);
assert.strictEqual(
adult,
true,
"adult should be a boolean for whether personAge is 18 or older",
);
console.log("All checks passed.");
console.log("Type of null:", nullType);
console.log("Label:", label);
console.log("Is adult:", adult);Expected output: All checks passed.
Type of null: object
Label: Alice is 20 years old
Is adult: true
Once it passes, try two variations and predict each before running:
- The
typeof nullquirk, turned around. ChangenullTypetotypeof personNameinstead oftypeof sampleNull. Before you run it, decide whattypeofreports for a string and which check breaks — the first assert wants"object", the value this lesson's quirk gives fornull, so a"string"there is an instructive failure that proves you know which value produces"object". - Loose value, strict check. Change
adulttopersonAge === "20"— comparing the number20to the string"20"with strict equality. Predict whetheradultcomes outtrueorfalsebefore running, then check:===compares type as well as value, so a number and a string are never strictly equal, and the boolean check fails.
Key Takeaways
- Use
constfor values that don't change,letfor values that do - JavaScript has several data types: strings, numbers, booleans, undefined, and null
- Strings can be created with quotes or backticks (template literals)
- Use
typeofto check a value's type - JavaScript can automatically convert between types (type coercion)
Next Steps
Now that you understand variables and data types, you're ready to learn about functions - reusable blocks of code that make your programs more organized and powerful!
Pro Tip: Try printing different types of values and see how they behave. Experiment with mathematical operations and string concatenation to get comfortable with how JavaScript handles different data types.
Next lesson
Functions in JavaScript
Learn how to create reusable code with functions
18 min