Storing and Working with Data
Variables are containers for storing data values. JavaScript has three ways to declare variables: var, let, and const.
JavaScript is a dynamically typed language, meaning variables can hold any type of data.
Example
// Variables
let name = 'John'; // String
const age = 25; // Number
let isStudent = true; // Boolean
let hobbies = ['reading', 'coding']; // Array
let person = { name: 'John', age: 25 }; // Object
let nothing = null; // Null
let notDefined; // Undefined
// Variable Declaration
let x; // Declare
x = 10; // Assign
let y = 20; // Declare and assign
// Const (cannot be reassigned)
const PI = 3.14159;
// PI = 3.14; // Error!
// Let vs Var
let blockScoped = 'accessible in block';
var functionScoped = 'accessible in function'; - let - Block-scoped, can be reassigned
- const - Block-scoped, cannot be reassigned
- var - Function-scoped (old way, avoid)
- String - Text in quotes
- Number - Integers and decimals
- Boolean - true or false
- Array - List of values
- Object - Key-value pairs
- null - Intentionally empty
- undefined - Not yet defined
Try Variables
HTML
<div id="output"></div>
<button onclick="showVariables()">Show Variables</button> CSS
#output { padding: 20px; background: #f0f0f0; border-radius: 5px; margin: 10px 0; min-height: 100px; }
button { padding: 10px 20px; background: #d1039e; color: white; border: none; border-radius: 5px; cursor: pointer; } JavaScript
function showVariables() {
let name = 'Alice';
const age = 30;
let isStudent = false;
let hobbies = ['painting', 'gaming', 'cooking'];
let output = `
Name: ${name}<br>
Age: ${age}<br>
Is Student: ${isStudent}<br>
Hobbies: ${hobbies.join(', ')}<br>
Type of name: ${typeof name}<br>
Type of age: ${typeof age}
`;
document.getElementById('output').innerHTML = output;
} Notes
- Always use const by default. Use let only when you need to reassign. Avoid var.
