A variable is a named location in memory to store data. In TypeScript, an extension of Javascript, there are three different keywords to define variables: var
, let
, and const
.
var
var a = 11;
var
keyword is used to define a variable and has scope outside the block in which it is used. This is known as var scoping or function scoping.var
, we can access it anywhere in the program.var
can be redeclared many times, but this may lead to bugs.//var redeclaration examplefunction f(x:any) {//declaring first timevar x:any = 1;console.log(x);//redeclaring second timevar x:any = 2;console.log(x)if (true) {//redeclaring third timevar x:any = 3;console.log(x)}}//calling the functionf(0)
let
let a = 11;
let
keyword is used to define a variable whose scope is limited to the block it is defined in.Cannot find name x
because we define and declare x
in the if
block with the let
keyword, so we cannot access it from outside the if
block.function f(isLoggedIn: boolean) {//defining variable x with let keyword in if blockif (isLoggedIn) {let x = 10;}return x;}//calling the functionf(true)
x
outside of the if
block and inside the function with the let
keyword so it has function scope.function f(isLoggedIn: boolean) {//defining variable x with let keyword in function blocklet x;if (isLoggedIn) {x = 10;}return x;}//calling the functionconsole.log(f(true))
Unlike var
, variables that are declared with let
cannot be redeclared, as shown in the code below.
function f(){let x = 5;//redeclaring xlet x = 10;return x;}f()
const
const pi = 3.14
const
is a keyword that is used to declare variables where the value of the variable is restricted to change.const
is useful when you want to define some constant values and you don’t want other programmers to change that value in the rest of the program.const pi = 3.14;// changing const value throws errorpi = 1;
_
and $
.Below are the example code snippets for variable rules.
//variable can contain alphabets and digitsvar abc123 = "Example"console.log(abc123)
//variable names cannot start with a digit//It will throw errorvar 4abc = "Example";console.log(4abc);
//Allowed special character `_` and `$`.var a_b = "Example";console.log(a_b)