Variables, Types & Arrays
The Building Blocks of Data
Open interactive version (quiz + challenge)Real-world analogy
Variables are like labeled boxes — each box holds ONE type of thing. Some boxes are permanent (const), some can be swapped out (let). Arrays are like containers that hold MANY boxes of the same type in order!
What is it?
Variables store data. TypeScript has primitive types (string, number, boolean) and collection types (arrays, Maps, Sets). Arrays are the most common way to store multiple items. Each type is strictly checked — you can't put a string where a number is expected.
Real-world relevance
Almost every program uses arrays constantly: shopping lists, user searches, data from databases. Array methods like map, filter, and reduce are so important they appear in interviews!
Key points
- const vs let vs var — Use const by default — it can't be reassigned. Use let only when you NEED to change a variable. NEVER use var — it has weird bugs. Rule: const > let >> var (avoid var!)
- Primitive Types — string (text), number (any number: int, decimal, negative), boolean (true/false), null (empty on purpose), undefined (not set yet), void (function returns nothing), never (function never finishes).
- Type Inference — TypeScript guesses types for you! const name = 'John' → TS knows it's string. You only need to write types when it's NOT obvious.
- Arrays and Array Methods — Arrays hold multiple items: string[], number[]. Use .map() to transform, .filter() to select, .find() to search, .reduce() to combine, .some()/.every() to check conditions.
- Array Methods Deep Dive — push/pop (add/remove), length (count), includes (check if exists), indexOf (find position), forEach (loop), map (transform each), filter (keep matches), find (first match), some/every (any/all match), reduce (combine to one value).
- Map and Set Collections — Map is like a dictionary (key → value lookup). Set is like a bag of unique stickers (no duplicates). Use Map for dynamic keys, Set to remove duplicates.
- Object Utility Methods — Object.keys() gets all keys, Object.values() gets all values, Object.entries() gets key-value pairs. Loop with for...of or .forEach().
- Destructuring and Spread — Unpack arrays and objects into variables: const [a, b] = arr or const {name, age} = user. Spread operator (...) merges arrays/objects: [...arr1, ...arr2]
Code example
// Variables — choose const by default
const name = "John"; // cannot change
let age = 25; // can change if needed
age = 26; // OK!
// Basic types
const text: string = "hello";
const count: number = 42;
const active: boolean = true;
const nothing: null = null;
const notSet: undefined = undefined;
// Arrays
const fruits: string[] = ["apple", "banana"];
const numbers: number[] = [1, 2, 3];
// Array methods
fruits.push("cherry"); // ["apple", "banana", "cherry"]
fruits.pop(); // removes "cherry"
fruits.length; // 2
fruits.includes("apple"); // true
fruits.indexOf("banana"); // 1
// Transform with map
const upper = fruits.map(f => f.toUpperCase());
// ["APPLE", "BANANA"]
// Filter
const long = fruits.filter(f => f.length > 5);
// ["banana"]
// Find first match
const found = fruits.find(f => f.startsWith("a"));
// "apple"
// Check if ANY/ALL match
fruits.some(f => f === "apple"); // true (at least one)
fruits.every(f => f.length > 2); // true (all match)
// Reduce — combine into ONE value
const nums = [1, 2, 3, 4, 5];
const sum = nums.reduce((total, n) => total + n, 0);
// → 15
// Map — dictionary (key → value)
const scores = new Map<string, number>();
scores.set("math", 95);
scores.get("math"); // 95
scores.has("math"); // true
scores.size; // 1
// Set — unique values only!
const tags = new Set<string>();
tags.add("javascript");
tags.add("javascript"); // ignored (duplicate)
tags.size; // 1
// Spread — merge arrays
const a = [1, 2];
const b = [3, 4];
const merged = [...a, ...b]; // [1, 2, 3, 4]
// Destructuring
const [first, second] = fruits; // first="apple", second="banana"Line-by-line walkthrough
- 1. Comment: Use const by default for variables
- 2. Declaring a constant 'name' set to 'John' - cannot be reassigned
- 3. Declaring 'age' with let starting at 25 - CAN be changed
- 4. Reassigning age to 26 - allowed because we used let
- 5.
- 6. Comment: Basic TypeScript types
- 7. Explicitly typed string variable
- 8. Explicitly typed number variable
- 9. Explicitly typed boolean variable
- 10. Null type - intentionally empty
- 11. Undefined type - value not yet set
- 12.
- 13. Comment: Arrays hold multiple items of the same type
- 14. A string array with two fruit names
- 15. A number array with three numbers
- 16.
- 17. Comment: Array methods for manipulating arrays
- 18. push() adds 'cherry' to the end of the array
- 19. pop() removes and returns the last item
- 20. length tells how many items (2)
- 21. includes() checks if 'apple' is in the array (true)
- 22. indexOf() finds the position of 'banana' (index 1)
- 23.
- 24. Comment: Transform arrays with map
- 25. map() creates a new array by uppercasing each fruit
- 26. Comment: Result is ['APPLE', 'BANANA']
- 27.
- 28. Comment: Filter keeps only matching items
- 29. filter() keeps only fruits with more than 5 characters
- 30. Comment: Only 'banana' matches
- 31.
- 32. Comment: Find the first matching item
- 33. find() returns the first fruit starting with 'a'
- 34. Comment: Result is 'apple'
- 35.
- 36. Comment: Check if any or all items match
- 37. some() checks if at least one fruit equals 'apple' - true
- 38. every() checks if ALL fruits have more than 2 characters - true
- 39.
- 40. Comment: Reduce combines all items into one value
- 41. Creating a number array for reduce demo
- 42. reduce() adds all numbers starting from 0: result is 15
- 43. Comment: Final result is 15
- 44.
- 45. Comment: Map is a key-value dictionary
- 46. Creating a new Map with string keys and number values
- 47. Setting key 'math' to value 95
- 48. Getting value for key 'math' - returns 95
- 49. Checking if key 'math' exists - true
- 50. Getting the Map's size - 1 entry
- 51.
- 52. Comment: Set stores only unique values
- 53. Creating a new Set for strings
- 54. Adding 'javascript' to the set
- 55. Adding 'javascript' again - ignored because it's a duplicate!
- 56. Getting the set size - still 1
- 57.
- 58. Comment: Spread operator merges arrays
- 59. Array a with [1, 2]
- 60. Array b with [3, 4]
- 61. Spread both into a new merged array: [1, 2, 3, 4]
- 62.
- 63. Comment: Destructuring unpacks arrays into variables
- 64. Extracting first='apple' and second='banana' from the fruits array
Spot the bug
const age: string = 25;
const names: number[] = ["Alice", "Bob"];
console.log(age, names);Need a hint?
Look at the types assigned versus the actual values...
Show answer
Two type mismatches: 'age' is typed as string but assigned number 25, and 'names' is typed as number[] but contains strings. Fix: change to 'age: number = 25' and 'names: string[] = ["Alice", "Bob"]'.
Explain like I'm 5
Think of variables like labeled jars in your kitchen. One jar says 'cookies' and only holds cookies. Another says 'candies' and only holds candies. Arrays are like a cookie jar that holds MANY cookies in a row. You can count them, pick your favorite, or add more!
Fun fact
The .reduce() method is considered the most powerful array method. You can implement map, filter, and almost any other operation using reduce! Senior developers flex with it.
Hands-on challenge
Create an array of numbers [1-10]. Use array methods to: filter evens, map to double them, and reduce to sum. What's the result?
More resources
- TypeScript Handbook - Everyday Types (TypeScript Official)
- JavaScript Arrays Explained (Web Dev Simplified)
- MDN Array Reference (MDN Web Docs)