Table of Contents
What are variables?
A variable is a named storage for data. Each variable must have a unique name which is called identifier. Variables can be hard-coded to hold predefined values or dynamically generated.
You can easily declare a variable using the let keyword followed by the name of the variable
let email; email = "[email protected]";
You have the option to declare a variable and assign a value later or do both at once
let email = "[email protected]"; let loggedIn = false;
You can easily change the value of a variable by easily assigning a new one
let testVariable = "hello"; testVariable = "world";
let testVariable = "hello"; testVariable = 10; testVariable = false;
Javscript variable names can only contain letters, numbers or the symbols $ and _
However, the first character cant be a number and you cant use reserved keywords (such as let or return) for variable names.
//valid variable names let test1; let variable_name; let user_1; //invalid varaible names let 1test; let varaible-test; let return;
If the value of your variable is constant and won’t be re-assigned you can use const instead of let.
const welcomeMessage = "hello world";
These are useful to create a distinction between constant and changeable variables
const email = "[email protected]"; let isLoggedIn = true;
It has also become common practice to use constant aliases for known values that are used throughout a site or application. These are written with uppercase letter and underscores.
const PRIMARY_BRAND_COLOR = "#1c3aa4"; const CONTACT_EMAIL = "c[email protected]"; const COMPANY_REG_NUMBER = "0123456789";
What about var?
You can still declare variables using var, however the practice is now considered outdated.
//old standard var message = "hello world"; //new standard let message = "hello world";
variable declared with var aren’t scoped and have various other flaws, so unless you need to support a really old browser its best to use let and const variables.
- Use let to declare variables with changeable values
- Use const to declare constant, non changeable values
- Follow the naming rules and name your variables well
- Use uppercase constants for hard-coded global constant values
- Don’t use var to declare variables unless you require legacy browser support