beginner

JavaScript Data Types

Explore JavaScript primitive types: strings, numbers, booleans, and more.

JavaScript is a dynamically typed language with several built-in data types. Understanding these types is essential for writing effective code and avoiding common bugs. From strings and numbers to the special values null and undefined, each type has unique behaviors and use cases. This exercise explores the fundamental data types you'll work with every day.

📚 Concepts & Theory

Primitive Data Types:

String - Text data:

let greeting = "Hello, World!";
let name = 'Alice';
let template = Hello, !; // Template literal

Number - Integers and decimals:

let age = 25;
let price = 19.99;
let negative = -10;
let infinity = Infinity;
let notANumber = NaN;

Boolean - True or false:

let isActive = true;
let isComplete = false;

Undefined - Variable declared but not assigned:

let x;
console.log(x); // undefined

Null - Intentional absence of value:

let user = null; // Explicitly "no value"

Checking Types:

typeof "hello"    // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (quirk!)

🎯 Your Challenge

Create variables for each data type: a string `productName` with "Laptop", a number `price` with 999.99, a boolean `inStock` with true, and a variable `discount` that is null.

📝 Starter Code

JavaScript
// String
let productName = 

// Number
let price = 

// Boolean
let inStock = 

// Null
let discount = 
  • Strings need quotes, numbers don't
  • Booleans are true or false (lowercase)
  • null means "intentionally empty"
  • undefined means "not yet assigned"

Solution

JavaScript
let productName = "Laptop";

let price = 999.99;

let inStock = true;

let discount = null;

Explanation

We create a string using quotes, a number without quotes (including decimals), a boolean with the literal true, and null to represent an intentional absence of a value for discount. Each variable uses let because values might change later.

⚠️ Common Mistakes to Avoid

  • Putting numbers in quotes (makes them strings)
  • Confusing null and undefined
  • Using NULL or True (wrong case)
  • Forgetting that typeof null returns object

❓ Frequently Asked Questions

undefined means a variable has been declared but not assigned a value. null is an intentional assignment that represents no value. Use null when you want to explicitly indicate emptiness.
This is a known bug in JavaScript that has existed since the beginning. It was never fixed because it would break existing code.

🔗 Related Concepts