Hey guys in this post, we will discuss Javascript variables with Examples
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.
Declaring variables
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;
Changing value
You can easily change the value of a variable by easily assigning a new one
let testVariable = "hello";
testVariable = "world";
Javascript is dynamically types do you can even assign a value of a different type (although that is not advised)
let testVariable = "hello";
testVariable = 10;
testVariable = false;
Naming rules
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;
Constants
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;
Uppercase constants
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";
There is technically no difference between them as for as javascript is concerned, it is just a style choice to differentiate them.
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.
Summary
- 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