Falytom logoFALYTOM
Games
ToolsUI ComponentsServicesProductsAbout
LoginSign Up
menu
  1. Home
  2. /Web Development
  3. /Javascript
  4. /Data Types
Your Progress0%
0 of 61 completed

JavaScript Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project

Data Types and Type Checking

Understanding the different kinds of values in JavaScript

Data types define what kind of value a variable holds. Is it text? A number? True or false? JavaScript has several built-in data types, and understanding them is crucial for writing effective code. Let's explore each type and learn how to work with them!

What Are Data Types?

A data type specifies what kind of value a variable contains. Different types of data behave differently and support different operations.

JAVASCRIPT
// Different data types
let name = "John";        // String (text)
let age = 25;             // Number
let isStudent = true;     // Boolean (true/false)
let score = null;         // Null (intentionally empty)
let address;              // Undefined (not assigned yet)

JavaScript is dynamically typed, meaning you don't need to declare what type a variable is—JavaScript figures it out automatically.

JAVASCRIPT
// The same variable can hold different types
let value = 42;           // Number
console.log(typeof value); // "number"

value = "Hello";          // Now it's a string
console.log(typeof value); // "string"

value = true;             // Now it's a boolean
console.log(typeof value); // "boolean"

Primitive vs Reference Types

JavaScript data types fall into two categories:

Primitive Types (7 types)

Simple, immutable values stored directly in the variable. When you copy them, you get a separate copy.

  • String
  • Number
  • Boolean
  • Null
  • Undefined
  • Symbol (ES6+)
  • BigInt (ES2020+)

Reference Types (Objects)

Complex values that can hold multiple values. When you copy them, you copy a reference, not the value itself.

  • Objects
  • Arrays
  • Functions

Key Difference: Primitive types are copied by value. Reference types are copied by reference. We'll explore this difference in detail later.

String Type

Strings represent text. You can create them with single quotes, double quotes, or backticks (template literals).

Creating Strings

JAVASCRIPT
// Three ways to create strings
let single = 'Hello';
let double = "Hello";
let template = `Hello`;

// All are equivalent
console.log(single);   // Hello
console.log(double);   // Hello
console.log(template); // Hello

String Characteristics

JAVASCRIPT
let message = "Hello, World!";

// Strings have a length property
console.log(message.length);  // 13

// You can access individual characters (zero-indexed)
console.log(message[0]);      // H
console.log(message[7]);      // W

// Strings are immutable (can't be changed)
message[0] = "h";             // This doesn't work
console.log(message);         // Still "Hello, World!"

// You must create a new string to "change" it
message = "hello, world!";    // This works (new string)
console.log(message);         // hello, world!

Special Characters

JAVASCRIPT
// Escape sequences
let newLine = "First line\nSecond line";
let tab = "Name\tAge";
let quote = "She said, \"Hello\"";
let backslash = "C:\\Users\\John";

console.log(newLine);
// First line
// Second line

console.log(tab);      // Name    Age
console.log(quote);    // She said, "Hello"
console.log(backslash); // C:UsersJohn

Template Literals (Backticks)

JAVASCRIPT
let name = "John";
let age = 25;

// Template literals allow embedded expressions
let greeting = `Hello, my name is ${name} and I'm ${age} years old.`;
console.log(greeting);

// Multi-line strings (no \n needed)
let multiLine = `
  This is line 1
  This is line 2
  This is line 3
`;
console.log(multiLine);

// Can include expressions
let price = 50;
let quantity = 3;
let total = `Total: $${price * quantity}`;
console.log(total);  // Total: $150

String Practice

Experiment with different string operations

Output:
Click "Run" to execute your code...
💡 Tip: Use console.log() to see your output in the console above.

Number Type

JavaScript has a single number type that represents both integers and floating-point numbers.

Number Basics

JAVASCRIPT
// Integers
let age = 25;
let score = 100;

// Floating-point numbers (decimals)
let price = 19.99;
let pi = 3.14159;

// Negative numbers
let temperature = -5;
let balance = -150.50;

// Scientific notation
let large = 1e6;      // 1,000,000
let small = 1e-6;     // 0.000001

console.log(large);   // 1000000
console.log(small);   // 0.000001

Special Number Values

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

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

// Checking for NaN
let result = "hello" * 2;
console.log(isNaN(result));   // true
console.log(isNaN(42));       // false

Number Methods

JAVASCRIPT
let num = 123.456;

// Convert to string
console.log(num.toString());        // "123.456"

// Fixed decimal places
console.log(num.toFixed(2));        // "123.46"
console.log(num.toFixed(0));        // "123"

// Parse numbers from strings
console.log(parseInt("123"));       // 123
console.log(parseInt("123.456"));   // 123 (truncates)
console.log(parseFloat("123.456")); // 123.456

// Number conversion
console.log(Number("123"));         // 123
console.log(Number("123.456"));     // 123.456
console.log(Number("hello"));       // NaN

Math Operations

JAVASCRIPT
// Basic arithmetic
console.log(10 + 5);   // 15 (addition)
console.log(10 - 5);   // 5  (subtraction)
console.log(10 * 5);   // 50 (multiplication)
console.log(10 / 5);   // 2  (division)
console.log(10 % 3);   // 1  (remainder/modulo)
console.log(2 ** 3);   // 8  (exponentiation)

// Order of operations (PEMDAS)
console.log(2 + 3 * 4);      // 14 (not 20)
console.log((2 + 3) * 4);    // 20 (parentheses first)

// Increment and decrement
let count = 5;
count++;            // Add 1
console.log(count); // 6
count--;            // Subtract 1
console.log(count); // 5

Floating-Point Precision: Computers can't always represent decimal numbers exactly. This can lead to small errors:

JAVASCRIPT
console.log(0.1 + 0.2);  // 0.30000000000000004 (not exactly 0.3!)

// For money calculations, work in cents
let price = 1050;  // $10.50 in cents
let total = price * 2;
console.log(total / 100);  // 21 (convert back to dollars)

Boolean Type

Booleans represent logical values: true or false. They're essential for making decisions in your code.

Boolean Basics

JAVASCRIPT
// Boolean values
let isLoggedIn = true;
let isAdmin = false;
let hasPermission = true;

console.log(isLoggedIn);     // true
console.log(typeof isLoggedIn); // "boolean"

// Booleans from comparisons
let age = 18;
let isAdult = age >= 18;
console.log(isAdult);        // true

let score = 75;
let passed = score >= 60;
console.log(passed);         // true

Boolean in Conditions

JAVASCRIPT
let isRaining = true;

if (isRaining) {
  console.log("Take an umbrella!");
} else {
  console.log("Enjoy the sunshine!");
}

// Negating with !
let isSunny = !isRaining;
console.log(isSunny);  // false

Truthy and Falsy Values

In JavaScript, values can be converted to boolean. Some values are "falsy" (become false), others are "truthy" (become true).

Falsy values (only 6):

  • false
  • 0 (zero)
  • "" (empty string)
  • null
  • undefined
  • NaN

Truthy values: Everything else!

  • All numbers except 0 (including negative numbers)
  • All strings except empty string (even "0" or "false")
  • All objects and arrays
  • The boolean true
JAVASCRIPT
// Falsy values
console.log(Boolean(false));      // false
console.log(Boolean(0));          // false
console.log(Boolean(""));         // false
console.log(Boolean(null));       // false
console.log(Boolean(undefined));  // false
console.log(Boolean(NaN));        // false

// Truthy values
console.log(Boolean(true));       // true
console.log(Boolean(1));          // true
console.log(Boolean(-1));         // true
console.log(Boolean("hello"));    // true
console.log(Boolean("0"));        // true (string, not number!)
console.log(Boolean([]));         // true
console.log(Boolean({}));         // true

Null and Undefined

These two types represent "no value," but they're used in different situations.

Undefined

undefined means a variable has been declared but not assigned a value. JavaScript sets this automatically.

JAVASCRIPT
// Variable declared but not assigned
let name;
console.log(name);           // undefined
console.log(typeof name);    // "undefined"

// Function with no return
function test() {
  // No return statement
}
console.log(test());         // undefined

// Non-existent object property
let person = { age: 25 };
console.log(person.name);    // undefined

Null

null is an intentional assignment meaning "no value" or "empty." You set this yourself.

JAVASCRIPT
// Intentionally setting to null
let result = null;
console.log(result);         // null
console.log(typeof result);  // "object" (this is a JavaScript bug!)

// Common use: reset a variable
let user = { name: "John" };
user = null;  // Clear the user

// Checking for null
if (result === null) {
  console.log("Result is null");
}

Null vs Undefined

JAVASCRIPT
// undefined: JavaScript says "I don't know what this is yet"
let notAssigned;
console.log(notAssigned);  // undefined

// null: You say "this is intentionally empty"
let intentionallyEmpty = null;
console.log(intentionallyEmpty);  // null

// Comparison
console.log(null == undefined);   // true (loose equality)
console.log(null === undefined);  // false (strict equality)

// Best practice: use null when you want to explicitly set "no value"
let selectedItem = null;  // No item selected yet

// Let JavaScript use undefined for uninitialized variables
let tempValue;  // Don't set to undefined manually

Rule of Thumb: Use null when you want to explicitly indicate "no value." Let JavaScript handle undefined for uninitialized variables.

The typeof Operator

The typeof operator tells you what type a value is. It returns a string describing the type.

Using typeof

JAVASCRIPT
// Checking types
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" (JavaScript bug!)
console.log(typeof {});             // "object"
console.log(typeof []);             // "object" (arrays are objects)
console.log(typeof function() {}); // "function"

Practical typeof Usage

JAVASCRIPT
function processValue(value) {
  if (typeof value === "string") {
    console.log("Processing string:", value.toUpperCase());
  } else if (typeof value === "number") {
    console.log("Processing number:", value * 2);
  } else if (typeof value === "boolean") {
    console.log("Processing boolean:", !value);
  } else {
    console.log("Unknown type:", typeof value);
  }
}

processValue("hello");  // Processing string: HELLO
processValue(42);       // Processing number: 84
processValue(true);     // Processing boolean: false

typeof Quirks

Be aware of these typeof quirks:

JAVASCRIPT
// null returns "object" (this is a bug)
console.log(typeof null);  // "object" (should be "null")

// Arrays return "object"
console.log(typeof [1, 2, 3]);  // "object"

// To check for array, use Array.isArray()
console.log(Array.isArray([1, 2, 3]));  // true
console.log(Array.isArray({}));         // false

// NaN is a number!
console.log(typeof NaN);  // "number"

Type Inspector

See the variables, their types, and values in real-time

Code:
let text = "Hello World";
let number = 42;
let decimal = 3.14;
let yes = true;
let no = false;
let nothing = null;
let notDefined;
let calculation = 10 * 5;

No variables detected. Declare some variables in the code above.

📘 Note: This inspector shows variables declared with let, const, or var keywords.

Objects and Arrays (Introduction)

Objects and arrays are reference types that can hold multiple values. We'll cover them in depth in later lessons, but here's a quick introduction.

Objects

Objects store collections of key-value pairs (properties).

JAVASCRIPT
// Creating an object
let person = {
  name: "John",
  age: 25,
  city: "New York"
};

console.log(person);
console.log(typeof person);  // "object"

// Accessing properties
console.log(person.name);    // "John"
console.log(person.age);     // 25

Arrays

Arrays store ordered lists of values.

JAVASCRIPT
// Creating an array
let colors = ["red", "green", "blue"];

console.log(colors);
console.log(typeof colors);        // "object"
console.log(Array.isArray(colors)); // true

// Accessing elements (zero-indexed)
console.log(colors[0]);  // "red"
console.log(colors[1]);  // "green"
console.log(colors[2]);  // "blue"

Comparing Data Types

JAVASCRIPT
// Strings
let str1 = "hello";
let str2 = "hello";
console.log(str1 === str2);  // true (same value)

// Numbers
let num1 = 42;
let num2 = 42;
console.log(num1 === num2);  // true (same value)

// Booleans
let bool1 = true;
let bool2 = true;
console.log(bool1 === bool2);  // true (same value)

// Different types
console.log(5 === "5");      // false (different types)
console.log(5 == "5");       // true (loose equality converts types)

// Always use === (strict equality)
console.log(0 === false);    // false
console.log(0 == false);     // true (loose equality)
console.log("" === false);   // false
console.log("" == false);    // true (loose equality)

Best Practice: Always use === (strict equality) instead of == (loose equality). Strict equality doesn't convert types, making your code more predictable.

Practical Examples

Example 1: User Registration

JAVASCRIPT
// User data with different types
let userName = "john_doe";              // string
let email = "john@example.com";         // string
let age = 25;                           // number
let isVerified = false;                 // boolean
let profilePicture = null;              // null (no picture yet)
let lastLogin;                          // undefined (never logged in)

console.log("Username:", userName, typeof userName);
console.log("Email:", email, typeof email);
console.log("Age:", age, typeof age);
console.log("Verified:", isVerified, typeof isVerified);
console.log("Profile pic:", profilePicture, typeof profilePicture);
console.log("Last login:", lastLogin, typeof lastLogin);

Example 2: Shopping Cart

JAVASCRIPT
// Shopping cart with various types
let productName = "Laptop";             // string
let productPrice = 999.99;              // number
let quantity = 2;                       // number
let inStock = true;                     // boolean
let discount = null;                    // null (no discount)
let shippingAddress;                    // undefined (not provided)

// Calculate total
let subtotal = productPrice * quantity;
let hasDiscount = discount !== null;

console.log(`Product: ${productName}`);
console.log(`Price: $${productPrice}`);
console.log(`Quantity: ${quantity}`);
console.log(`Subtotal: $${subtotal}`);
console.log(`In stock: ${inStock}`);
console.log(`Has discount: ${hasDiscount}`);

Student Profile Example

See different data types in action

Output:
Click "Run" to execute your code...
💡 Tip: Use console.log() to see your output in the console above.

Key Takeaways

  • JavaScript has 7 primitive types: string, number, boolean, null, undefined, symbol, bigint
  • Reference types include objects, arrays, and functions
  • Strings represent text and can be created with quotes or backticks
  • Numbers include both integers and decimals (floats)
  • Booleans are either true or false
  • null is intentionally empty, undefined means not yet assigned
  • Use typeof to check a value's type
  • typeof null returns "object" (this is a JavaScript quirk)
  • Always use === for comparisons (strict equality)
  • Falsy values: false, 0, "", null, undefined, NaN
  • Everything else is truthy

What's Next?

You now understand the fundamental data types in JavaScript and how to check what type a value is. This knowledge is crucial—every variable you create will be one of these types!

In the next lesson, we'll learn about Comments and Code Organization—how to document your code effectively and keep it clean and readable as your programs grow more complex.

💪 Practice Challenge:

Before moving on, try this:

  1. Create variables of each primitive type (string, number, boolean, null, undefined)
  2. Use typeof to check each variable's type
  3. Create an object with at least 5 properties of different types
  4. Experiment with truthy and falsy values using Boolean()
  5. Practice converting between types (string to number, number to string)

Test Your Understanding

Question 1 / 4

What data type is the value 42?

let age = 42;
Score: 0 / 0

Understanding JavaScript data types! 📊

Previous
Variables (var, let, const)
Next
Comments and Code Organization

Master JavaScript Fundamentals

Join 2,000+ developers learning JavaScript from the ground up. New lessons every week - FREE forever.

You might also like

UI Components

Ready-made components for your projects

Developer Tools

Boost productivity with handy generators

HTML Game

Learn HTML concepts through interactive gameplay

Join Our Web Development Training Program

Master frontend & backend development with hands-on projects.

JavaScript Tutorials

0 of 61 completed

Your Progress0%

Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project
Falytom logoFALYTOM

Learn technologies like HTML, CSS, JavaScript, React, NodeJS and more through interactive games, tutorials, components and free tools. Transform your businesses with AI chatbots, SEO-optimized websites, and professional development services.

© 2025 Tomilola Group
  • Facebook logo
  • Twitter logo
  • Instagram logo
  • LinkedIn logo
  • GitHub logo
  • YouTube logo