From Zero to AI

Lesson 1.2: Data Types

Duration: 45 minutes

Learning Objectives

By the end of this lesson, you will be able to:

  • Understand what data types are and why they matter
  • Work with strings (text data)
  • Work with numbers (integers and decimals)
  • Work with booleans (true/false values)
  • Check the type of any value
  • Convert between different data types

What are Data Types?

Data types describe what kind of value a variable holds. Just like in real life - a phone number is different from a name, and a price is different from a yes/no answer.

JavaScript has several primitive (basic) data types:

Type Description Examples
string Text data "Hello", 'World', `Hi`
number Numeric data 42, 3.14, -17
boolean True or false true, false
undefined No value assigned undefined
null Intentionally empty null

In this lesson, we focus on the three most common: strings, numbers, and booleans.


Strings: Working with Text

A string is any text wrapped in quotes. You can use single quotes, double quotes, or backticks.

const greeting = 'Hello, World!';
const name = 'Alice';
const message = `Welcome to the course`;

String Length

Find out how many characters are in a string:

const text = 'JavaScript';
console.log(text.length); // Output: 10

Combining Strings (Concatenation)

Join strings together using +:

const firstName = 'John';
const lastName = 'Doe';
const fullName = firstName + ' ' + lastName;
console.log(fullName); // Output: "John Doe"

Template Literals (Backticks)

The modern way to combine strings and variables:

const name = 'Alice';
const age = 25;

// Old way with +
const intro1 = 'My name is ' + name + ' and I am ' + age + ' years old.';

// Modern way with template literals
const intro2 = `My name is ${name} and I am ${age} years old.`;

console.log(intro2); // Output: "My name is Alice and I am 25 years old."

Template literals use backticks () and ${...}` to insert variables.

Common String Methods

const text = 'Hello, World!';

// Convert to uppercase
console.log(text.toUpperCase()); // "HELLO, WORLD!"

// Convert to lowercase
console.log(text.toLowerCase()); // "hello, world!"

// Get a character at position (0-based index)
console.log(text[0]); // "H"
console.log(text[7]); // "W"

// Check if string includes another string
console.log(text.includes('World')); // true
console.log(text.includes('world')); // false (case-sensitive)

// Replace part of a string
console.log(text.replace('World', 'JavaScript')); // "Hello, JavaScript!"

// Remove whitespace from ends
const messy = '   Hello   ';
console.log(messy.trim()); // "Hello"

Numbers: Working with Numeric Data

Numbers in JavaScript include both integers and decimals (floating-point numbers).

const age = 25; // Integer
const price = 19.99; // Decimal
const temperature = -5; // Negative number
const million = 1_000_000; // Underscores for readability

Basic Math Operations

const a = 10;
const b = 3;

console.log(a + b); // Addition: 13
console.log(a - b); // Subtraction: 7
console.log(a * b); // Multiplication: 30
console.log(a / b); // Division: 3.333...
console.log(a % b); // Remainder (modulo): 1
console.log(a ** b); // Exponent (power): 1000

Shorthand Operations

let score = 10;

score = score + 5; // Long way
score += 5; // Short way (same result)

// All shorthand operators
score += 10; // score = score + 10
score -= 5; // score = score - 5
score *= 2; // score = score * 2
score /= 4; // score = score / 4

Increment and Decrement

let count = 0;

count++; // count = count + 1 (now 1)
count++; // count = count + 1 (now 2)
count--; // count = count - 1 (now 1)

The Math Object

JavaScript provides built-in math functions:

// Round to nearest integer
console.log(Math.round(4.7)); // 5
console.log(Math.round(4.4)); // 4

// Round up (ceiling)
console.log(Math.ceil(4.1)); // 5

// Round down (floor)
console.log(Math.floor(4.9)); // 4

// Get absolute value
console.log(Math.abs(-5)); // 5

// Find maximum and minimum
console.log(Math.max(1, 5, 3)); // 5
console.log(Math.min(1, 5, 3)); // 1

// Random number between 0 and 1
console.log(Math.random()); // e.g., 0.7234...

// Random integer between 1 and 10
const randomNum = Math.floor(Math.random() * 10) + 1;

Special Number Values

// Infinity
console.log(1 / 0); // Infinity
console.log(-1 / 0); // -Infinity

// NaN (Not a Number)
console.log('hello' * 2); // NaN
console.log(Math.sqrt(-1)); // NaN

// Check for NaN
console.log(isNaN('hello' * 2)); // true
console.log(isNaN(42)); // false

Booleans: True or False

Booleans represent yes/no, on/off, true/false values.

const isLoggedIn = true;
const hasPermission = false;
const isAdult = age >= 18;

Comparison Operators Return Booleans

console.log(5 > 3); // true
console.log(5 < 3); // false
console.log(5 >= 5); // true
console.log(5 <= 4); // false
console.log(5 === 5); // true (strict equality)
console.log(5 !== 3); // true (not equal)

Strict vs Loose Equality

Always use strict equality (=== and !==):

// Loose equality (==) - converts types, can be confusing
console.log(5 == '5'); // true (string converted to number)
console.log(0 == false); // true (false converted to 0)

// Strict equality (===) - no conversion, more predictable
console.log(5 === '5'); // false (different types)
console.log(0 === false); // false (different types)

Truthy and Falsy Values

Some values are treated as false in boolean context:

// Falsy values (treated as false)
console.log(Boolean(false)); // false
console.log(Boolean(0)); // false
console.log(Boolean('')); // false (empty string)
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(NaN)); // false

// Everything else is truthy
console.log(Boolean(true)); // true
console.log(Boolean(42)); // true
console.log(Boolean('hello')); // true
console.log(Boolean([])); // true (empty array)
console.log(Boolean({})); // true (empty object)

Checking Data Types

Use typeof to check what type a value is:

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 known JavaScript quirk)

Converting Between Types

To String

const num = 42;

// Method 1: String() function
const str1 = String(num); // "42"

// Method 2: toString() method
const str2 = num.toString(); // "42"

// Method 3: Concatenate with empty string
const str3 = num + ''; // "42"

To Number

const str = '42';

// Method 1: Number() function
const num1 = Number(str); // 42

// Method 2: parseInt() for integers
const num2 = parseInt('42px'); // 42 (stops at non-digit)

// Method 3: parseFloat() for decimals
const num3 = parseFloat('3.14'); // 3.14

// Method 4: Unary plus
const num4 = +'42'; // 42

To Boolean

const str = 'hello';
const empty = '';

const bool1 = Boolean(str); // true
const bool2 = Boolean(empty); // false

// Double negation shortcut
const bool3 = !!str; // true
const bool4 = !!empty; // false

Practical Examples

Example 1: User Greeting

const userName = 'Alice';
const visitCount = 5;
const isPremium = true;

const greeting = `Welcome back, ${userName}! 
This is visit #${visitCount}.
Premium member: ${isPremium}`;

console.log(greeting);

Example 2: Price Calculation

const price = 29.99;
const quantity = 3;
const discount = 0.1; // 10% discount

const subtotal = price * quantity;
const discountAmount = subtotal * discount;
const total = subtotal - discountAmount;

console.log(`Subtotal: $${subtotal.toFixed(2)}`);
console.log(`Discount: -$${discountAmount.toFixed(2)}`);
console.log(`Total: $${total.toFixed(2)}`);

Example 3: Form Validation

const email = 'user@example.com';
const password = 'secret123';

const isEmailValid = email.includes('@');
const isPasswordLong = password.length >= 8;
const canSubmit = isEmailValid && isPasswordLong;

console.log(`Email valid: ${isEmailValid}`); // true
console.log(`Password long enough: ${isPasswordLong}`); // true
console.log(`Can submit form: ${canSubmit}`); // true

Exercises

Exercise 1: String Manipulation

Create a variable with your full name. Then:

  • Print the length of your name
  • Print your name in uppercase
  • Print the first letter of your name
Solution
const fullName = 'John Smith';

console.log(fullName.length); // 10
console.log(fullName.toUpperCase()); // "JOHN SMITH"
console.log(fullName[0]); // "J"

Exercise 2: Temperature Converter

Convert a temperature from Celsius to Fahrenheit. Formula: F = (C * 9/5) + 32

const celsius = 25;
Solution
const celsius = 25;
const fahrenheit = (celsius * 9) / 5 + 32;
console.log(`${celsius}°C = ${fahrenheit}°F`); // "25°C = 77°F"

Exercise 3: Type Checking

Check and print the type of each value:

const values = ['Hello', 42, true, undefined, null];
Solution
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"

Key Takeaways

  1. Strings are text data - use template literals for combining with variables
  2. Numbers include integers and decimals - use Math for advanced operations
  3. Booleans are true/false - result from comparisons
  4. Use === for equality checks, not ==
  5. typeof tells you what type a value is
  6. Convert types when needed using String(), Number(), Boolean()

Resources

Resource Type Description
MDN: Data Types Documentation Complete data types reference
MDN: String Documentation String methods reference
JavaScript.info: Data Types Tutorial Detailed types tutorial

Next Lesson

Now that you understand data types, let's learn how to work with them using operators.

Continue to Lesson 1.3: Operators and Expressions