Variables in JavaScript

DevJunctionPoint
0

 

What are variables?

  • variables act as containers that can store the data.

JavaScript Variable Naming Rules

  • Variable names are case-sensitive "a" and "A" is different in JavaScript.
  • Only letter, digits, underscore( _ ), and $ dollar sign is allowed.
  • Only letter, underscore( _ ), or $ should be 1st character.
  • Reserved Keywords cannot be used as variable names.

//valid
let a = 'hello';
let _a = 'hello';
let $a = 'hello';

  • variable cannot start with a digit.

//invalid
Let 1a = 'hello'; // this gives an error

  • variable names are case-sensitive which means "y" and "Y" both are different.

let y = "hi";
let Y = 5;

console.log(y); // hi
console.log(Y); // 5

  • we cannot use reserved keywords as variable names in JavaScript.

//invalid
let new = 5; // Error! new is a keyword.

  • variable name should not contain space and special characters except underscore and dollar sign.

Types of variables:

1. let
2. var
3. const

1. let
  • let variable cannot be re-declared but value can be updated. 
  • it is used to declare a block-scoped variable.
  • let keyword was introduced in ES6 in 2015 and its alternative to var keyword.
  • the value of a let variable can be changed.
syntax:


let x = 5;
x = 10;
console.log(x); // 10


2. var
  • var is used in older versions of JavaScript.
  • Var can be re-declared and can be updated. 
  • Var is a global scope variable.
  • Using the var keyword we cannot declare the two same variables’ names.
Example:


var name =js
var name =learn”  invalid

var age = 25;
var age = 20;
var age = 80;
console.log(age) // 80


3. const
  • const value cannot be re-declared or updated once it is declared. 
  • variable using const must be initialized during the declaration.
  • The const keyword was also introduced in ES6 and const variable are block scoped.


const x = 5;
x = 10;  // Error! constant cannot be changed.
console.log(x)


Difference between let, var, const.

Let

Var

Const

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

The var keyword was used in all JavaScript code from 1995 to 2015.

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

Variables defined with let cannot be Redeclared

Example:

let x = "JS";

let x = 0;

Variables defined with var can be Redeclared

Example:

let x = "JS";

let x = 0;

Variables defined with const cannot be Redeclared

Example:

const x = "JS";

const x = 0;

Variables defined with let have Block Scope

Variables defined with var have global Scope

Variables defined with const have Block Scope

Tags

Post a Comment

0Comments

Do leave your comments

Post a Comment (0)

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Ok, Go it!
To Top