JavaScript Variables
JS Variables
JVariables are containers for storing data values. In JavaScript, variables are used to store data that can be manipulated and referenced throughout a program.
There are three ways to declare variables in JavaScript:
var
- old, less preferredlet
- modern and preferred for variables that can changeconst
- modern and preferred for variables that shouldn't change
Rules for variables are:
- Names must start with a letter, an underscore (_), or a dollar sign ($)
myVar
,_myVar
,$myVar
- After the first character, you can use letters, digits, underscores, or dollar signs
myVar1
,_var2
,$var_3
- JavaScript variable names are case-sensitive --
myVar
andmyvar
are different variables because of case sensitivity - Reserved keywords cannot be used as variable names:
These are reserved for JavaScript syntax -
let
,const
,var
,if
,else
,while
,class
,return
, etc. - Variables should be meaningful
- It's a best practice to use descriptive names like:
userName
,totalAmount
,myName
,userAddress
var (global/function Scope)
var is function-scoped, meaning it is visible throughout the function or globally if declared outside a function. var can also be re-declared and updated within the same scope.
let (Block Scope)
let is block-scoped, meaning it is confined to the block in which it's declared (within ). This makes let safer than var since it prevents accidental overwriting.
const (Constant Values)
Once a value is assigned to a const variable, it cannot be reassigned or updated. However, if the const is an object or array, its contents can still be modified.