JavaScript and TypeScript course Β· Module 1: JavaScript Basics
Basic Data Types (string, number, boolean, null, undefined)
In this lesson8
Just as in Jurassic Park we have different dinosaur species, each with unique characteristics and behaviors, in JavaScript we have different data types, each serving specific purposes. Understanding these types is crucial for effective programming - it's like knowing the differences between a Velociraptor and a Triceratops for a park employee.
Primitive Types
JavaScript has five main primitive types: string, number, boolean, null, and undefined. These are the fundamental "species" in our digital park.
1. String - Text
The string type represents text - a sequence of characters enclosed in single ('), double ("), or backtick (`) quotes. It's like information signs in Jurassic Park that convey important messages to visitors.
1// Different ways to declare strings
2const dinoName = "Tyrannosaurus Rex";
3const warningSign = 'Warning! Do not approach the fence!';
4const locationInfo = `You are in sector B4`;
5
6// Strings can contain special characters
7const multilineWarning = "Warning!\nDo not feed the dinosaurs!"; // \n means new line
8
9// String length (number of characters)
10const nameLength = dinoName.length; // 17
11
12// Joining strings (concatenation)
13const fullWarning = warningSign + " " + dinoName + " is dangerous!";
14
15// Template literals - only with backticks (``)
16const modernWarning = `${warningSign} ${dinoName} is dangerous!`;Strings are like the universal language of communication in the park - they serve to display information, send messages, and label resources.
String Methods
Strings in JavaScript have built-in methods that allow manipulation, similar to how park employees have tools for managing exhibits:
1const species = "Velociraptor";
2
3// Changing case
4const upperCase = species.toUpperCase(); // "VELOCIRAPTOR"
5const lowerCase = species.toLowerCase(); // "velociraptor"
6
7// Searching in a string
8const hasRaptor = species.includes("raptor"); // true
9const position = species.indexOf("raptor"); // 6 (indices start from 0)
10const startsWith = species.startsWith("Velo"); // true
11const endsWith = species.endsWith("tor"); // true
12
13// Extracting fragments
14const firstFour = species.substring(0, 4); // "Velo"
15const lastSix = species.slice(-6); // "raptor"
16
17// Replacing fragments
18const newSpecies = species.replace("Veloci", "Micro"); // "Microraptor"
19
20// Splitting a string into an array
21const announcement = "Attention! All guests please evacuate!";
22const words = announcement.split(" "); // ["Attention!", "All", "guests", ...]2. Number - Numbers
The number type represents both integers and floating-point numbers (decimals). Unlike many other programming languages, JavaScript doesn't distinguish between these two types - they are all simply number.
It's like the numerical system in the park used for everything - from counting dinosaurs to measuring their weight or height.
1// Integers
2const dinoCount = 37;
3const parkSectors = 12;
4
5// Floating-point numbers (decimals)
6const trexHeight = 5.6; // meters
7const raptorSpeed = 38.5; // km/h
8
9// Scientific notation
10const atomSize = 1.5e-10; // 0.00000000015
11const dinosaurCellCount = 3.2e12; // 3,200,000,000,000
12
13// Infinity and NaN (Not a Number)
14const infinity = Infinity; // Infinite value
15const negInfinity = -Infinity; // Negative infinite value
16const notANumber = NaN; // Result of an invalid mathematical operation, e.g., 0/0Number Operations
Numbers in JavaScript support all standard mathematical operations, similar to how scientists in the park perform various calculations:
1// Basic arithmetic operations
2const sum = 10 + 5; // 15 (addition)
3const diff = 10 - 5; // 5 (subtraction)
4const product = 10 * 5; // 50 (multiplication)
5const quotient = 10 / 5; // 2 (division)
6const remainder = 10 % 3; // 1 (modulo - remainder of division)
7const power = 10 ** 2; // 100 (exponentiation - 10 to the power of 2)
8
9// Math object for advanced operations
10const roundedHeight = Math.round(trexHeight); // 6 (rounding)
11const ceilingHeight = Math.ceil(trexHeight); // 6 (rounding up)
12const floorHeight = Math.floor(trexHeight); // 5 (rounding down)
13const randomNumber = Math.random(); // Random number between 0 and 1
14const maxSpeed = Math.max(42, 35, 38, 40); // 42 (highest value)
15const sqrtValue = Math.sqrt(25); // 5 (square root)Caution with Floating-Point Precision
In JavaScript (and many other languages), floating-point numbers can lead to unexpected results, similar to unpredictable dinosaur behaviors:
1const precisionIssue = 0.1 + 0.2; // We expect 0.3, but get 0.30000000000000004
2
3// Solution - use rounding or scaled constants:
4const fixedResult = Number((0.1 + 0.2).toFixed(1)); // 0.3
5const scaledResult = (0.1 * 10 + 0.2 * 10) / 10; // 0.33. Boolean - Logical Values
The boolean type has only two possible values: true or false. It's like an alarm system in the park that can be on or off.
1// Basic boolean values
2const fenceActive = true;
3const parkClosed = false;
4
5// Logical expressions return boolean
6const isTRexDangerous = true;
7const isParkOpen = !parkClosed; // true (negation)
8const isSafeToEnter = fenceActive && isParkOpen; // true (AND)
9const needsAttention = !fenceActive || parkClosed; // false (OR)Boolean values are crucial for decision-making in programs - similar to security systems in the park that decide whether to open a gate, trigger an alarm, or evacuate a sector.
1// Using boolean in conditional statements
2if (fenceActive) {
3 console.log("Enclosure secured");
4} else {
5 console.log("WARNING! Enclosure unsecured!");
6 activateEmergencyProtocol();
7}
8
9// Comparison operators return boolean
10const isDangerousSpecies = dinosaurType === "Velociraptor" || dinosaurType === "T-Rex";
11const isHerbivore = dinosaurDiet !== "carnivore";
12const isTooBig = dinosaurHeight > 3;
13const isInRange = visitorDistance >= 50;4. null - Intentional Absence of Value
The value null represents an intentional absence of value - it is an explicit indication that a variable contains no value. It's like an empty enclosure in the park, specially prepared, but currently without a dinosaur.
1// Variable with null value
2let selectedDinosaur = null; // Currently no dinosaur is selected
3
4// Null is often used as an initial value
5let scannedChip = null; // Before scanning, the chip contains no data
6
7// Checking if a value is null
8if (selectedDinosaur === null) {
9 console.log("No dinosaur has been selected");
10}
11
12// Null is a falsy value
13if (!selectedDinosaur) {
14 console.log("This will also display for null");
15}5. undefined - Undefined Value
The value undefined means that a variable has been declared but has not been assigned any value. It's like an undeveloped plot in the park - it exists, but its purpose has not been determined yet.
1// Declared but uninitialized variable
2let newDinosaur; // automatically has the value undefined
3
4// Function without explicit return returns undefined
5function checkEnclosure() {
6 // No return statement
7}
8const result = checkEnclosure(); // result has value undefined
9
10// Checking if a value is undefined
11if (newDinosaur === undefined) {
12 console.log("Dinosaur has not been specified yet");
13}
14
15// undefined is a falsy value
16if (!newDinosaur) {
17 console.log("This will also display for undefined");
18}Differences Between null and undefined
Although both types represent "lack of value," there are important differences between them:
nullis an intentional absence of value (like an empty enclosure)undefinedis an unintentional absence of value (like an unassigned spot)
1// typeof shows the difference
2typeof null; // "object" (this is a historical bug in JavaScript)
3typeof undefined; // "undefined"
4
5// In terms of equality
6null == undefined; // true (loose equality)
7null === undefined; // false (strict equality)Symbol and BigInt - Newer Primitive Types
Newer versions added two more primitive types: Symbol (ES2015) and BigInt (ES2020). Together with the five types above, JavaScript has seven primitive types.
Symbol - Unique Identifier
1// Creating unique identifiers
2const dinoId = Symbol('dino-id');
3const enclosureId = Symbol('enclosure-id');
4
5// Each Symbol is unique
6const id1 = Symbol('id');
7const id2 = Symbol('id');
8console.log(id1 === id2); // false, even though they have the same descriptionBigInt - Large Integers
1// Creating BigInt by adding 'n' at the end of a number or using the BigInt() function
2const dinoGenomeSize = 9007199254740991n;
3const sameBigInt = BigInt(9007199254740991);
4
5// BigInt can represent numbers larger than Number.MAX_SAFE_INTEGER
6console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991Type Checking
To identify the type of a given value (similar to identifying a dinosaur species), we can use the typeof operator:
1typeof "Triceratops"; // "string"
2typeof 42; // "number"
3typeof true; // "boolean"
4typeof null; // "object" (note: this is a historical bug in JavaScript)
5typeof undefined; // "undefined"
6typeof Symbol(); // "symbol"
7typeof 42n; // "bigint"
8
9// For functions and objects
10typeof function() {}; // "function"
11typeof {}; // "object"
12typeof []; // "object" (arrays are objects in JavaScript)Type Coercion
JavaScript automatically converts types during operations, which can sometimes lead to unexpected results - similar to the unexpected behavior of hybrid dinosaurs in the park.
1// Automatic conversion to string
2"Dinosaur " + 5; // "Dinosaur 5" (number 5 was converted to string)
3
4// Automatic conversion to number
5"5" - 2; // 3 (string "5" was converted to number)
6"5" * 2; // 10 (string "5" was converted to number)
7
8// Automatic conversion to boolean
9if ("Dinosaur") {
10 // This code will execute, because a non-empty string is treated as true
11}
12
13if (0) {
14 // This code will NOT execute, because 0 is treated as false
15}Falsy and Truthy Values
In JavaScript, every value can be converted to boolean. Values automatically converted to false are called "falsy," and those converted to true are called "truthy."
Falsy values:
false0""(empty string)nullundefinedNaN
All other values are truthy, including:
true- Any number other than 0 (including negative and fractions)
- Any non-empty string
- Any object, array, and function
1// Boolean conversion examples
2Boolean(0); // false
3Boolean(""); // false
4Boolean(null); // false
5Boolean(undefined);// false
6Boolean(NaN); // false
7
8Boolean(1); // true
9Boolean("text"); // true
10Boolean([]); // true (empty array is truthy)
11Boolean({}); // true (empty object is truthy)Explicit Type Conversion
To avoid unexpected results, it's recommended to explicitly convert types - similar to how in Jurassic Park it's always better to have full control over the dinosaurs:
1// Converting to string
2String(42); // "42"
3(42).toString(); // "42"
442 + ""; // "42" (uses implicit conversion)
5
6// Converting to number
7Number("42"); // 42
8parseInt("42", 10); // 42 (second number is the radix, e.g., 10 for decimal)
9parseFloat("42.5"); // 42.5
10+"42"; // 42 (uses implicit conversion)
11
12// Converting to boolean
13Boolean(1); // true
14Boolean(0); // false
15!!"value"; // true (double negation)Safe Type Checking
In real applications, just as in park safety protocols, it's worth applying rigorous type checking:
1// Checking if a variable is a string
2function isString(value) {
3 return typeof value === 'string' || value instanceof String;
4}
5
6// Checking if a variable is a number (with additional NaN check)
7function isNumber(value) {
8 return typeof value === 'number' && !isNaN(value);
9}
10
11// Checking if a variable is a boolean
12function isBoolean(value) {
13 return typeof value === 'boolean';
14}
15
16// Checking if a variable has a null value
17function isNull(value) {
18 return value === null;
19}
20
21// Checking if a variable has an undefined value
22function isUndefined(value) {
23 return typeof value === 'undefined';
24}Practical Example: Dinosaur Inventory System
The following example illustrates the use of different data types in a complex system:
1// Configuration constants
2const PARK_NAME = "Jurassic Park";
3const MAX_CAPACITY = 50;
4const SECURITY_LEVELS = {
5 LOW: 1,
6 MEDIUM: 2,
7 HIGH: 3,
8 CRITICAL: 4
9};
10
11// Dinosaur inventory system
12function processDinosaurData(dinoId, name, species, height, isDangerous) {
13 // Data type checking
14 if (typeof dinoId !== 'number' || !Number.isInteger(dinoId) || dinoId <= 0) {
15 return "Error: Invalid dinosaur ID";
16 }
17
18 if (typeof name !== 'string' || name.trim() === '') {
19 return "Error: Invalid dinosaur name";
20 }
21
22 if (typeof height !== 'number' || height <= 0) {
23 return "Error: Invalid dinosaur height";
24 }
25
26 if (typeof isDangerous !== 'boolean') {
27 return "Error: Danger parameter must be of type boolean";
28 }
29
30 // Data processing
31 let securityLevel = null;
32
33 if (isDangerous) {
34 securityLevel = height > 3 ? SECURITY_LEVELS.CRITICAL : SECURITY_LEVELS.HIGH;
35 } else {
36 securityLevel = height > 5 ? SECURITY_LEVELS.MEDIUM : SECURITY_LEVELS.LOW;
37 }
38
39 // Preparing dinosaur report
40 const dinoRecord = {
41 id: dinoId,
42 name: name,
43 species: species || "Unknown", // Protection against undefined
44 height: height,
45 dangerous: isDangerous,
46 securityLevel: securityLevel,
47 enclosureType: getEnclosureType(securityLevel),
48 lastUpdated: new Date().toISOString()
49 };
50
51 // Return the report
52 return dinoRecord;
53}
54
55// Helper function
56function getEnclosureType(securityLevel) {
57 switch(securityLevel) {
58 case SECURITY_LEVELS.LOW:
59 return "Open range";
60 case SECURITY_LEVELS.MEDIUM:
61 return "Standard fence";
62 case SECURITY_LEVELS.HIGH:
63 return "Reinforced fence with monitoring";
64 case SECURITY_LEVELS.CRITICAL:
65 return "Isolated high-security enclosure";
66 default:
67 return "Unspecified";
68 }
69}
70
71// Usage example
72const trexData = processDinosaurData(
73 1,
74 "Rexy",
75 "Tyrannosaurus Rex",
76 5.6,
77 true
78);
79
80console.log(trexData);Summary
String - represents text
- Like information signs in the park
- Enclosed in
',", or` - Has many built-in methods (e.g.,
toUpperCase(),indexOf())
Number - represents integers and floating-point numbers
- Like the numerical system in the park
- Supports all standard mathematical operations
- Be careful with floating-point precision
Boolean - logical values
trueorfalse- Like an alarm system (on/off)
- Foundation for decision-making (conditional statements)
- Also created as a result of comparison operations
null - intentional absence of value
- Like an empty, prepared enclosure
- Explicitly set by the programmer
- Represents "nothing" or "unknown"
undefined - undefined value
- Like a yet-unassigned spot in the park
- Appears automatically for uninitialized variables
- Also the default result of a function without
return
Understanding data types in JavaScript is the foundation of effective programming - just as knowing different dinosaur species is crucial for Jurassic Park employees. Each type has its applications, limitations, and behaviors that you need to know to avoid unexpected "incidents" in your code!
In the next lesson, we will discuss type conversion and operations on data types - like learning safe and effective work with different dinosaur species in the park.
Code for this lesson: index.js
1// Diagnostic System - Functions
2// Exercise: Creating and calling functions
3
4// Function declaration
5function checkDinosaur(name, health) {
6 console.log("Examining: " + name);
7 if (health > 80) {
8 return name + " - status: EXCELLENT";
9 } else if (health > 50) {
10 return name + " - status: GOOD";
11 } else {
12 return name + " - status: NEEDS CARE";
13 }
14}
15
16// Function call
17console.log(checkDinosaur("T-Rex", 95));
18console.log(checkDinosaur("Raptor", 72));
19console.log(checkDinosaur("Brachio", 45));
20
21// Function with default value
22function feedDinosaur(name, amount = 50) {
23 console.log(name + " fed: " + amount + " kg");
24}
25
26feedDinosaur("T-Rex", 200);
27feedDinosaur("Compy"); // will use default value 50
28
29// Your task:
30// 1. Create a function calculateAge(birthYear) that calculates age
31// 2. Create a function with a default parameter
32// 3. Call them with different arguments
33
34// Your code here:
35Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What values can the boolean type hold in JavaScript?
2. What will typeof 42 return in JavaScript?
Hands-on tasks in the game
- Code editor
Declare three variables describing a DNA sample: the species name (string), the weight in kilograms (number) and whether the dinosaur is a carnivore (boolean). Display each variable in the console together with its type, using typeof.