Variables and Data Types

Learn how to store information using variables and understand the different types of data JavaScript can work with.

What are Variables?

// Variables are containers for storing data
let message = "Hello JavaScript!";
const maxUsers = 100;
Variables store values:
message → "Hello JavaScript!"
maxUsers → 100

Declaration keywords:

  • let - For values that might change later
  • const - For values that won't change (constant)
  • var - Older method (avoid in modern JavaScript)

Basic Data Types

// String: Text values
let name = "Alex";

// Number: Numeric values
let age = 30;

// Boolean: True/False values
let isStudent = true;

// Undefined: Uninitialized variable
let unknownValue;

// Null: Intentional empty value
let emptyValue = null;
Data types:
name → String
age → Number
isStudent → Boolean
unknownValue → Undefined
emptyValue → Null

JavaScript has 7 fundamental data types. We'll cover Objects and Arrays next.

Complex Data Types

// Object: Collection of key-value pairs
let person = {
name: "Maria",
age: 28,
isEngineer: true
};

// Array: Ordered list of values
let colors = ["red", "green", "blue"];
Objects group related data
Arrays store ordered lists
Both can contain mixed data types

Important: Arrays are special types of objects with numeric keys.

Checking Types with typeof

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" (historical quirk)
console.log(typeof [1,2,3]); // "object"
console.log(typeof {name: "John"}); // "object"
string
number
boolean
undefined
object
object
object

Use typeof to check a variable's type. Note that arrays and null both return "object".

Variable Naming Rules

// Valid names
let userName;
let total_price;
let $element;
let _internalValue;

// Invalid names
let 1stPlace; // Cannot start with number
let full-name; // Hyphens not allowed
let let; // Reserved word
Rules:
- Start with letter, $ or _
- Can contain letters, numbers, $, _
- Case sensitive
- Cannot be reserved words

Convention: Use camelCase for variable names (e.g., userAge)

Common Mistakes with Variables

// 1. Missing declaration keyword
price = 9.99; // ❌ Creates global variable (avoid!)

// 2. Reassigning const variable
const pi = 3.14;
pi = 3.1416; // ❌ Error!

// 3. Redeclaring let variable
let count = 1;
let count = 2; // ❌ Error!

// 4. Using undefined variables
console.log(unknownVar); // ❌ ReferenceError

Always declare variables with let or const to avoid unexpected behavior.

Type Conversion

// String to Number
let str = "123";
let num = Number(str); // 123 (number)

// Number to String
let n = 456;
let s = String(n); // "456" (string)

// Boolean conversion
console.log(Boolean(1)); // true
console.log(Boolean(0)); // false
console.log(Boolean("hello")); // true
console.log(Boolean("")); // false
Explicit conversion:
Number() → Converts to number
String() → Converts to string
Boolean() → Converts to true/false

JavaScript automatically converts types in some contexts (implicit conversion), but explicit conversion is safer.

Making Buttons Work

// 1. Find the button element
const button = document.getElementById("showTypes");

// 2. Add click event listener
button.addEventListener("click", function() {
// 3. Code to run when clicked
console.log("Button clicked!");
document.getElementById("output").textContent = "Data shown!";
});
When button is clicked:
- Console shows "Button clicked!"
- Webpage updates with "Data shown!"

Event listeners: Make elements interactive by responding to user actions like clicks.

Practical Example: User Profile

// Store user information
const userName = "Sam";
let userAge = 32;
const isAdmin = true;
const hobbies = ["reading", "hiking", "coding"];

// Create user profile object
const userProfile = {
name: userName,
age: userAge,
adminStatus: isAdmin,
interests: hobbies
};

// Display information
console.log(userProfile);
document.getElementById("output").innerHTML = `
const name = "Sam";
const greeting = `Hello, ${name}!`; // "Hello, Sam!"
const age = 25;
const bio = `I am ${age} years old.`; // "I am 25 years old."`;
Console: Object with user data
Webpage:
Name: Sam
Age: 32
Admin: true
Hobbies: reading, hiking, coding

Your Task: Practice with Variables

Create JavaScript code that:

  1. Declare variables representing different data types:
    • A string with your name
    • A number with your age
    • A boolean indicating if you're a student
    • An array with at least 3 favorite foods
    • An object with book title and author
  2. Use typeof to check the type of each variable
  3. Display all variables and their types in the console
  4. Show the collected information in the webpage (id="output")
  5. Make the button display the information when clicked using addEventListener

Challenge: Try converting your age to a string and your student status to a number

Tip: Use JSON.stringify() for displaying objects in HTML

Section 1/10What are Variables?

What are Variables?

Declaration keywords:let - For values that might change laterconst - For values that won't change (constant)var - Older method (avoid in modern JavaScript)

Variables and Data Types

Learn how to store information using variables and understand the different types of data JavaScript can work with.

What are Variables?

// Variables are containers for storing data
let message = "Hello JavaScript!";
const maxUsers = 100;
Variables store values:
message → "Hello JavaScript!"
maxUsers → 100

Declaration keywords:

  • let - For values that might change later
  • const - For values that won't change (constant)
  • var - Older method (avoid in modern JavaScript)

Preview