JavaScript
Beginner
JavaScript Variables and Data Types
70 views
35 min read
Table of Contents
Understanding Variables and Data Types
Variables are containers that store data values. In JavaScript, you can create variables using var, let, or const.
Declaring Variables
// Modern way (recommended)
let userName = "John";
const age = 25;
// Older way (avoid in new code)
var city = "New York";
Variable Naming Rules
- Must start with a letter, underscore (_), or dollar sign ($)
- Can contain letters, numbers, underscores, and dollar signs
- Cannot use reserved keywords (like
let,function, etc.) - Case-sensitive (
myVarandmyvarare different)
JavaScript Data Types
1. Numbers
let integer = 42;
let decimal = 3.14;
let negative = -10;
2. Strings
let singleQuotes = 'Hello';
let doubleQuotes = "World";
let templateLiteral = `Hello, ${userName}!`;
3. Booleans
let isActive = true;
let isComplete = false;
4. Arrays
let fruits = ["apple", "banana", "orange"];
let numbers = [1, 2, 3, 4, 5];
5. Objects
let person = {
name: "Alice",
age: 30,
city: "Boston"
};
6. Undefined and Null
let undefinedVar; // undefined
let nullVar = null; // null
Checking Data Types
console.log(typeof 42); // "number"
console.log(typeof "Hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof [1,2,3]); // "object"
Practice Exercise
// Create variables for a student profile
let studentName = "Your Name";
let studentAge = 20;
let isEnrolled = true;
let subjects = ["Math", "Science", "English"];
let grades = {
math: 85,
science: 92,
english: 78
};
// Display the information
console.log("Student:", studentName);
console.log("Age:", studentAge);
console.log("Enrolled:", isEnrolled);
console.log("Subjects:", subjects);
console.log("Grades:", grades);