D Dev Notebook

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 preferred
  • let - modern and preferred for variables that can change
  • const - modern and preferred for variables that shouldn't change

Rules for variables are:

  1. Names must start with a letter, an underscore (_), or a dollar sign ($) myVar, _myVar, $myVar
  2. After the first character, you can use letters, digits, underscores, or dollar signs myVar1, _var2, $var_3
  3. JavaScript variable names are case-sensitive -- myVar and myvar are different variables because of case sensitivity
  4. Reserved keywords cannot be used as variable names: These are reserved for JavaScript syntax - let, const, var, if, else, while, class, return, etc.
  5. Variables should be meaningful
  6. It's a best practice to use descriptive names like: userName, totalAmount, myName, userAddress

var (global/function Scope)

var myName = ’Digital Vision’; 
console.log(myName ); 

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 myLocation = ’Jaipur’; 
console.log(myLocation) 

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)

const myContact = 8100003010; 
console.log(myContact ); 

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.

On this page