Variables in JavaScript
Learn how to store and manage data using variables.
What are Variables?
Variables are containers for storing data values. In JavaScript, you can declare variables using three keywords: var, let, and const.
Modern JavaScript: Use
let and const instead of var. They provide better scoping and help prevent bugs.
Declaring Variables
Using let
Use let when you need to reassign a variable later.
Try it yourself
Output
Using const
Use const for values that should never be reassigned.
Try it yourself
Output
Using var (Legacy)
var is the old way to declare variables. It has function scope instead of block scope, which can lead to unexpected behavior.
JavaScript
var oldStyle = "I'm function-scoped";
// Avoid using var in modern JavaScript
Data Types
JavaScript has several data types:
Explore data types
Output
Variable Naming Rules
- Names can contain letters, digits, underscores, and dollar signs
- Names must begin with a letter, underscore (_), or dollar sign ($)
- Names are case-sensitive (
myVarandmyvarare different) - Reserved words (like
let,const,function) cannot be used as names
JavaScript
// Good variable names
let userName = "John";
let user_age = 25;
let $price = 9.99;
let _private = "hidden";
// Use camelCase for multi-word names
let firstName = "Jane";
let totalItemCount = 42;
Challenge: Create Your Variables
Create variables to store your name, age, and a boolean indicating if you like JavaScript. Then log them to the console.
Your solution
Output