Welcome to the javascript learning course

Lets start today's topic - How many ways are there to declare variable in javascript.
  • var
  • let
  • const

Lets explore all ways:

Let's start with var. Declare a variable by this syntax

copy
var a
Assign a value to the varibale .

copy
var a = 1
Reassign a value to the variable .

copy
a = 3
Lets see what happens when we declare a variable and print it's value to console.

copy
var a
console.log(a)  // undefined
undefined is printed on console because we didn't assign any value to the variable 'var a'.
Let's see what happens when we assign a value to the variable.

copy
var a = 1
console.log(a)  // 1
a = 3
console.log(a)  // 3
We can see that 1 is printed and when we reassign the value 3 to a, 3 is printed.
var with same name can be redeclared again it will replace the previously defined value.

copy
var a
console.log(a)  // undefined
var a = 1;
console.log(a)  // 1
var a = 3;
console.log(a)  // 3

Next is let way to declare a variable.

copy
let b
console.log(b)  // undefined
When value is not assigned to let is print's undefined.

copy
let b = 1
console.log(b)  // 1
b = 4
console.log(b)  // 4
Value to b can be reassigned to let.
let with the same name cannot be redeclared again it throw's syntax error.

copy
let b
console.log(b)  // undefined
let b = 1
console.log(b)  // Uncaught SyntaxError: Identifier 'b'
               // has  already been declared

Let's see const in action.
When we declare variable as const we have to initialise it's value if not initialised it throws error.

copy
const c;
console.log(c)  // Uncaught SyntaxError: Missing
               //  initializer in const declaration
Can the const variable be redeclared as in it is in var.

copy
const c = 1;
console.log(c)  // 1
const c = 2;
console.log(c)  // Uncaught SyntaxError: Identifier 'c'
               //  has already been declared
const variable cannot be redeclared as in var
Now let's try to reinitialise const variable.

copy
const c = 1
console.log(c)  // 1
c = 2
console.log(c) // Uncaught TypeError: Assignment to
              //  constant variable.
const variable cannot be reinitialised.
That's all for today.