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 datalet message = "Hello JavaScript!";const maxUsers = 100;
Variables store values:
message → "Hello JavaScript!"
maxUsers → 100Declaration keywords:
let- For values that might change laterconst- For values that won't change (constant)var- Older method (avoid in modern JavaScript)
Basic Data Types
// String: Text valueslet name = "Alex";// Number: Numeric valueslet age = 30;// Boolean: True/False valueslet isStudent = true;// Undefined: Uninitialized variablelet unknownValue;// Null: Intentional empty valuelet emptyValue = null;
Data types:
name → String
age → Number
isStudent → Boolean
unknownValue → Undefined
emptyValue → NullJavaScript has 7 fundamental data types. We'll cover Objects and Arrays next.
Complex Data Types
// Object: Collection of key-value pairslet person = {name: "Maria",age: 28,isEngineer: true};// Array: Ordered list of valueslet colors = ["red", "green", "blue"];
Objects group related data
Arrays store ordered lists
Both can contain mixed data typesImportant: 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
objectUse typeof to check a variable's type. Note that arrays and null both return "object".
Variable Naming Rules
// Valid nameslet userName;let total_price;let $element;let _internalValue;// Invalid nameslet 1stPlace; // Cannot start with numberlet full-name; // Hyphens not allowedlet let; // Reserved word
Rules:
- Start with letter, $ or _
- Can contain letters, numbers, $, _
- Case sensitive
- Cannot be reserved wordsConvention: Use camelCase for variable names (e.g., userAge)
Common Mistakes with Variables
// 1. Missing declaration keywordprice = 9.99; // ❌ Creates global variable (avoid!)// 2. Reassigning const variableconst pi = 3.14;pi = 3.1416; // ❌ Error!// 3. Redeclaring let variablelet count = 1;let count = 2; // ❌ Error!// 4. Using undefined variablesconsole.log(unknownVar); // ❌ ReferenceError
Always declare variables with let or const to avoid unexpected behavior.
Type Conversion
// String to Numberlet str = "123";let num = Number(str); // 123 (number)// Number to Stringlet n = 456;let s = String(n); // "456" (string)// Boolean conversionconsole.log(Boolean(1)); // trueconsole.log(Boolean(0)); // falseconsole.log(Boolean("hello")); // trueconsole.log(Boolean("")); // false
Explicit conversion:
Number() → Converts to number
String() → Converts to string
Boolean() → Converts to true/falseJavaScript automatically converts types in some contexts (implicit conversion), but explicit conversion is safer.
Making Buttons Work
// 1. Find the button elementconst button = document.getElementById("showTypes");// 2. Add click event listenerbutton.addEventListener("click", function() {// 3. Code to run when clickedconsole.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 informationconst userName = "Sam";let userAge = 32;const isAdmin = true;const hobbies = ["reading", "hiking", "coding"];// Create user profile objectconst userProfile = {name: userName,age: userAge,adminStatus: isAdmin,interests: hobbies};// Display informationconsole.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, codingYour Task: Practice with Variables
Create JavaScript code that:
- 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
- Use
typeofto check the type of each variable - Display all variables and their types in the console
- Show the collected information in the webpage (id="output")
- 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
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 datalet message = "Hello JavaScript!";const maxUsers = 100;
Variables store values:
message → "Hello JavaScript!"
maxUsers → 100Declaration keywords:
let- For values that might change laterconst- For values that won't change (constant)var- Older method (avoid in modern JavaScript)
Basic Data Types
// String: Text valueslet name = "Alex";// Number: Numeric valueslet age = 30;// Boolean: True/False valueslet isStudent = true;// Undefined: Uninitialized variablelet unknownValue;// Null: Intentional empty valuelet emptyValue = null;
Data types:
name → String
age → Number
isStudent → Boolean
unknownValue → Undefined
emptyValue → NullJavaScript has 7 fundamental data types. We'll cover Objects and Arrays next.
Complex Data Types
// Object: Collection of key-value pairslet person = {name: "Maria",age: 28,isEngineer: true};// Array: Ordered list of valueslet colors = ["red", "green", "blue"];
Objects group related data
Arrays store ordered lists
Both can contain mixed data typesImportant: 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
objectUse typeof to check a variable's type. Note that arrays and null both return "object".
Variable Naming Rules
// Valid nameslet userName;let total_price;let $element;let _internalValue;// Invalid nameslet 1stPlace; // Cannot start with numberlet full-name; // Hyphens not allowedlet let; // Reserved word
Rules:
- Start with letter, $ or _
- Can contain letters, numbers, $, _
- Case sensitive
- Cannot be reserved wordsConvention: Use camelCase for variable names (e.g., userAge)
Common Mistakes with Variables
// 1. Missing declaration keywordprice = 9.99; // ❌ Creates global variable (avoid!)// 2. Reassigning const variableconst pi = 3.14;pi = 3.1416; // ❌ Error!// 3. Redeclaring let variablelet count = 1;let count = 2; // ❌ Error!// 4. Using undefined variablesconsole.log(unknownVar); // ❌ ReferenceError
Always declare variables with let or const to avoid unexpected behavior.
Type Conversion
// String to Numberlet str = "123";let num = Number(str); // 123 (number)// Number to Stringlet n = 456;let s = String(n); // "456" (string)// Boolean conversionconsole.log(Boolean(1)); // trueconsole.log(Boolean(0)); // falseconsole.log(Boolean("hello")); // trueconsole.log(Boolean("")); // false
Explicit conversion:
Number() → Converts to number
String() → Converts to string
Boolean() → Converts to true/falseJavaScript automatically converts types in some contexts (implicit conversion), but explicit conversion is safer.
Making Buttons Work
// 1. Find the button elementconst button = document.getElementById("showTypes");// 2. Add click event listenerbutton.addEventListener("click", function() {// 3. Code to run when clickedconsole.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 informationconst userName = "Sam";let userAge = 32;const isAdmin = true;const hobbies = ["reading", "hiking", "coding"];// Create user profile objectconst userProfile = {name: userName,age: userAge,adminStatus: isAdmin,interests: hobbies};// Display informationconsole.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, codingYour Task: Practice with Variables
Create JavaScript code that:
- 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
- Use
typeofto check the type of each variable - Display all variables and their types in the console
- Show the collected information in the webpage (id="output")
- 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