JS variables

·

2 min read

JS variables

Variables

Simply variables are like giving a name to a memory block that stores value and this value can be modified. When we need to access a particular value stored in memory we use to access it with the variable name. In Javascript variables can be created in different ways :

  • By using var keyword

  • By using let and const keyword

  • By using nothing

Declaration and defining variables through these keywords

Syntax :

var/let/const variable_name; // declaration
variable_name = 10; // assigning or defining value

Ex :

var value = 10;
let bool = "true";
const id = 101;
  • Always declare JavaScript variables with var, let, or const.

  • The var keyword is used in all old JavaScript code.

  • The let and const keywords were added to JavaScript in 2015.

  • If you want your code to run in older browsers, you must use var.

  • variables declared with const cannot be changed, If variables need to be changed in a later part of the code then use let/var. Mostly prefer let as it is having some advantages when compared to the var keyword and var is used in old code. There are differences between var and let that will be discussed in a later part.

we can also declare and define in this way also

let person = "John", empid = 200, price = 500;

let person = "john",
     empid = 200,
     price = 500;

let person = "john"
     , empid = 200
     , price = 500;

But not preferred to use it like the above for better readability.

Redeclaring of a variable is possible with var keyword but not with let and const

var person = "John";
var person; // The value John will not be changed even after redeclaring the person

let person = "John";
let person; // It will not work

variable name setting rules :

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter.
  • Names can also begin with $ and _
  • Names are case-sensitive (x and X are different variables).
  • Reserved words (like JS keywords) cannot be used as names.