Variables and Data Types
Variables are the foundation of programming. Let's master them!
What is a Variable?
A variable is a "box" that stores a value.
javascript
let age = 25;// ↑ ↑// name valuelet, const and var
let - Can be changed
javascript
let score = 0;score = 10; // ✅ Worksscore = 100; // ✅ Worksconst - Cannot be changed
javascript
const PI = 3.14159;PI = 3; // ❌ Error!var - Old way (avoid)
javascript
var name = "Old"; // Works, but prefer letWhen to use what?
constby default (most cases)letwhen the value will changevarnever in new code
Data Types
String (text)
javascript
const name = "Maria";const phrase = 'Hello World';const template = `Hello, ${name}`; // Useful methodsname.length; // 5name.toUpperCase(); // "MARIA"name.toLowerCase(); // "maria"name.includes("ri"); // trueNumber
javascript
const integer = 42;const decimal = 3.14;const negative = -10; // Operations5 + 3; // 810 - 4; // 63 * 4; // 1210 / 2; // 510 % 3; // 1 (remainder) // Useful methodsMath.round(3.7); // 4Math.floor(3.7); // 3Math.ceil(3.2); // 4Math.random(); // 0 to 1Boolean (true/false)
javascript
const active = true;const blocked = false; // Results of comparisons5 > 3; // true10 < 5; // false5 === 5; // true5 !== 3; // trueUndefined and Null
javascript
let variable; // undefined (declared but no value)const empty = null; // null (intentionally empty)Type Conversion
String to Number
javascript
const text = "42";const number = Number(text); // 42const number2 = parseInt("42"); // 42const number3 = parseFloat("3.14"); // 3.14Number to String
javascript
const number = 42;const text = String(number); // "42"const text2 = number.toString(); // "42"Checking Type
javascript
typeof "Hello"; // "string"typeof 42; // "number"typeof true; // "boolean"typeof undefined; // "undefined"Comparison Operators
javascript
// Equality5 == "5"; // true (only value)5 === "5"; // false (value AND type) ← USE THIS! // Inequality5 != "5"; // false5 !== "5"; // true ← USE THIS! // Greater/Less5 > 3; // true5 >= 5; // true3 < 5; // true3 <= 3; // trueImportant: Always use === and !==!
Logical Operators
javascript
// AND (&&) - both truetrue && true; // truetrue && false; // false // OR (||) - at least one truetrue || false; // truefalse || false; // false // NOT (!) - inverts!true; // false!false; // truePractical Exercise
javascript
// Interactive calculationconst name = prompt("What's your name?");const birthYear = Number(prompt("Year born?")); const age = 2026 - birthYear;const adultYear = birthYear + 18; console.log(`${name}, you are ${age} years old.`); if (age >= 18) { console.log("You are an adult!");} else { console.log(`You will be an adult in ${adultYear}.`);}Summary
- ✅
constby default,letwhen it changes - ✅ String, Number, Boolean, Undefined, Null
- ✅ Always
===for comparison - ✅
&&(and),||(or),!(not)
In the next lesson, we'll learn to make decisions with if/else! 🚀