Web Analytics

JavaScript Variables

Beginner ~10 min read

What are Variables?

Variables are containers for storing data values. Think of them as labeled boxes where you can store information and retrieve it later.

HTML
CSS
JS

Three Ways to Declare Variables

JavaScript has three keywords for declaring variables: var, let, and const.

let (Recommended)

Modern way to declare variables that can be reassigned

let score = 0;
score = 10; // ✅ Can reassign

const (Recommended)

For values that won't be reassigned (constants)

const PI = 3.14159;
// PI = 3; // ❌ Error! Cannot reassign

var (Old Way)

Legacy way, avoid in modern code

var oldStyle = 'avoid this';
// Has weird scoping issues

let vs const - When to Use Each?

HTML
CSS
JS
Best Practice: Use const by default. Only use let when you know the value will change. Avoid var.

Variable Naming Rules

✅ Valid Names

let userName = 'Alice';
let user_age = 25;
let $price = 99.99;
let _private = 'secret';
let camelCaseStyle = 'recommended';

❌ Invalid Names

let 123name = 'error';  // Can't start with number
let user-name = 'error'; // No hyphens
let let = 'error';       // Can't use keywords
let my name = 'error';   // No spaces

Variable Scope

Scope determines where variables can be accessed in your code.

HTML
CSS
JS

Reassigning Variables

HTML
CSS
JS

Summary

  • Variables store data values
  • Use const by default for values that won't change
  • Use let for values that will be reassigned
  • Avoid var in modern JavaScript
  • Variable names must start with a letter, $, or _
  • Use camelCase for variable names
  • let and const have block scope

Quick Quiz

Which keyword should you use for a value that won't be reassigned?

A
var
B
let
C
const
D
variable