Using Variables in JavaScript

Using Variables in JavaScript

Instructor-svgAl-Mamun Sarkar
Mar 29 , 2021

Variables in JavaScript are being used to store different types of data. In JavaScript, we can declare variables using the var or let keyword. 

Assign a value to a variable using var:

var a = 50;
var b = 60;
var c = a + b;
var name = "John Doe";

Declare first and Assign later:

var email;

email = "test@example.com"

Multiple Variable in one line:

var name = "John Doe", roll = 12, gpa = 5.00;

 

Use variable using Let:

let site = "hello@artofcse.com";
let p = 33;
let q = 55;
let z =  p + q

 

let and var both are being used to create variable but has difference on the scope. 

{
  var name = 'Mamun Sarkar';
}
console.log(name); // This will work

This will work but if we use let then it will not work.

 

{
  let name = 'Mamun Sarkar';
}
console.log(name); // This will show error

This will not work.

 

var val = 100;
{
    var val = 20;
}
console.log(val); // Value will be 20

The value of val variable is 20.

 

var val = 100;
{
    let val = 20;
}
console.log(val); // Value is 100

The value of val variable is 100.

 

We can declare a variable with the same name multiple times using var but let doesn't allow it.

var varName = "Something";
var varName = "Another thing.";

This code will work and the value of varName is Another thing.

 

let varName = "Something";
let varName = "Another thing.";

This will not work. it will show an error. 

  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram