What are variables in TypeScript?
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;
- The
varkeyword 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. - Once we define
var, we can access it anywhere in the program. varcan 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;
- The
letkeyword is used to define a variable whose scope is limited to the block it is defined in. - If you run the code snippet below, you will get the error
Cannot find name xbecause we define and declarexin theifblock with theletkeyword, so we cannot access it from outside theifblock.
function f(isLoggedIn: boolean) {//defining variable x with let keyword in if blockif (isLoggedIn) {let x = 10;}return x;}//calling the functionf(true)
- To resolve the error in the code above, we need to define the variable
xoutside of theifblock and inside the function with theletkeyword so it has function scope. - Check the code snippet below for the modified code.
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
constis a keyword that is used to declare variables where the value of the variable is restricted to change.constis 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;
Rules
- Variable names can contain alphabets and digits.
- Variable names cannot start with a digit.
- Allowed special characters are
_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)