EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript const
Secondary Sidebar
TypeScript Tutorial
  • TypeScript Basic and Advanced
    • What is TypeScript?
    • Typescript Examples
    • TypeScript Versions
    • TypeScript Operators
    • JavaScript dump object
    • JavaScript get Method
    • Webpack ReactJS
    • Code Generator JavaScript
    • JavaScript Projects
    • Call Stack JavaScript
    • JavaScript Projects GitHub
    • JavaScript Filter Function
    • JavaScript nan
    • JavaScripttimestamp
    • TypeScript loop
    • CoffeeScript
    • TypeScript Webpack
    • setTimeout TypeScript
    • DHTMLX
    • CoffeeScript for loop
    • TypeScript number
    • JavaScript export module
    • TypeScript string contains
    • TypeScript Inheritance
    • TypeScript get
    • TypeScript undefined
    • TypeScript Global Variable
    • TypeScript Dictionary
    • TypeScript Generic
    • TypeScript Cast Object
    • TypeScript Optional Parameters
    • TypeScript? switch
    • TypeScript promise
    • TypeScript tuple
    • TypeScript Hashmap
    • TypeScript let
    • TypeScript Getter
    • TypeScript Pattern Matching
    • TypeScript number to string
    • TypeScript substring
    • TypeScript?lambda
    • TypeScript UUID
    • TypeScript JSDoc
    • TypeScript Decorators
    • Typescript for loop
    • TypeScript HTTP Request
    • TypeScript Abstract Class
    • TypeScript Question Mark
    • TypeScript Nullable
    • TypeScript reduce
    • TypeScript Mixins
    • TypeScript keyof
    • TypeScript string to number
    • TypeScript JSON parse
    • TypeScript const
    • TypeScript declare module
    • TypeScript String
    • TypeScript filter
    • TypeScript Multiple Constructors
    • TypeScript? Set
    • TypeScript string interpolation
    • TypeScript instanceof
    • TypeScript JSON
    • TypeScript Arrow Function
    • TypeScript generator
    • TypeScript namespace
    • TypeScript default parameter
    • TypeScript cast
    • TypeScript babel
    • Typescript Key-Value Pair
    • TypeScript if
    • TypeScript keyof Enum
    • TypeScript wait
    • TypeScript Optional Chaining
    • TypeScript JSX
    • TypeScript Version Check
    • TypeScript Unit Testing
    • TypeScript Handbook
    • TypeScript module
    • TypeScript Extend Interface
    • TypeScript npm
    • TypeScript pick
    • TypeScript Interface Default Value
    • JavaScript import module
    • Obfuscate Javascript
    • TypeScript basics
    • setInterval TypeScript
  • Type of Union
    • TypeScript Object Type
    • TypeScript type check
    • TypeScript promise type
    • TypeScript JSON type
    • TypeScript Union Types
    • TypeScript typeof
    • TypeScript Types
  • TypeScript Array
    • TypeScript Array of Objects
    • Methods TypeScript Array
    • TypeScript remove item from array
    • TypeScript add to array
    • TypeScript Array Contains
  • Function Of Array
    • TypeScript Function Interface
    • TypeScript Functions
    • TypeScript Export Function
    • TypeScript function return type

TypeScript const

TypeScript const

Introduction to TypeScript const

TypeScript const is one of the ways of declaring variables. The keyword ‘const’ makes the variable a constant, which means the variable’s value can not be changed. There are many other ways of declaring variables using ‘let’, ‘var’, etc. As ‘var’ allows to declare variables the same as JavaScript, it has the same scoping rules as that in JavaScript. While the ‘let’ keyword was introduced in ES6 along with the ‘const’ keyword, ‘let’ declares block-scoped local variables initializing to a value optionally. But in some cases, we do not want to block scope but also want immutable variables. Hence, with this limitation in the ‘let’ keyword, we are using the ‘const’ keyword for immutable variables.

Syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Given below is the syntax of TypeScript const:

const <constant_name> = <value>

It is a normal variable declaration but with the keyword ‘const.

Rules and Regulations for const Keyword

We shall look into some of the rules for declaring variables using the const keyword.

  • Const variables make a variable constant and cannot be changed.
  • Before declaring a const variable, users should make sure that the variable would not be reset.
  • An immutable variable is an approach that gives fewer bugs.
  • Const keyword declares block-scoped variables with any constant value.
  • Const has the same scoping rules that of the ‘let’ keyword.
  • If the user knows before hand that the variable declaring will not be reassigned, then it would be better to declare using const keyword instead of let and var keyword.
  • Const declaration provides a read-only reference to the value, which does not mean the value the const keyword is holding is immutable but can not be reassigned.
  • Const keyword can not be accessed before initialization which results in Reference Error.
  • Const can not be redeclared, which throws an Uncaught Syntax Error.

Sample declaration of const variables:

const sample_emp = "Karthik";

Examples of TypeScript const

Given below are the examples of TypeScript const:

Example #1

TypeScript const declaration.

Code:

const sample_emp="Karthik";
console.log('here is the employee name', sample_emp);

Output:

TypeScript const 1

So here, we are only declaring a const variable and initializing it to a string value.

Now, we will see various errors with these const declarations.

Example #2

TypeScript const, the const variable cannot be reassigned.

Code:

const Employee = {
empName: "Karthik",
empID: 10,
empLob: "RCL"
};
Employee = {
empName: "Daniel",
empID: 11,
empLob: "INS"
};
Employee.empName = "Saideep";
console.log('Employee Name: ', Employee.empName)
Employee.empID = 14;
console.log('Employee ID: ', Employee.empID)
Employee.empLob = "IVS";
console.log('Employee Lob: ', Employee.empLob)

Output:

There will be no output as this code will give an Error as ‘Cannot assign to ‘Employee’ as it is a constant.’

TypeScript const 2

Example #3

TypeScript const must be initialized.

Code:

const EmpName;
const EmpId = 45;
EmpId = 89;

Output:

There will be no particular output as the above code will throw an Error as ‘const declarations must be initialized’. & ‘Variable EmpId has implicitly ‘any’ type’. Also, we are reassigning EmpId to another value, so that too will throw us an error.

must be initialized

Example #4

TypeScript const being a block-scoped variable.

Code:

const stuName = "Ravi Kumar";
if (true) {
const stuName = "Ravi Kiran";
console.log('Student Name: ', stuName);
}

Output:

block scoped variable

The same const variable we are declaring and initializing with a new value, this does not give us any error as it is taken as a new variable and is only limited to the if block.

Example #5

TypeScript const for Deep immutability.

Code:

const student = { stuName: "Jaanu", stuId: 567, stuCtgry: "RCL" };
student.stuName = "Jahnavi"
student.stuId = 345
student.stuCtgry = "INS"
console.log('Student Name', student.stuName);
console.log('Student ID', student.stuId);
console.log('Student Category', student.stuCtgry);

Output:

TypeScript const 5

So here we see that student const has object literals, and we are reassigning the object literals and not the const value. Hence const keyword supports sub-properties of objects to be mutated.

Example #6

TypeScript const Read-only reference to a value.

Code:

const student = { stuid:101, stuname:"Tushar"}
student = {stuid:102, stuname:"Ramkiran"}
console.log('here are the student details', student.stuid, student.stuname);

Output:

Here we will not get an output as the above code gives us an Error ‘Cannot assign to ‘student’ because it is a constant.’

TypeScript const 6

The const here creates a Read-Only Reference to the value. The user can not change the reference as it is immutable. But user can change the value of the properties the const holds. The user can not assign a new object but can change the properties of the object.

Example #7

TypeScript const ‘Accessing before a declaration’.

Code:

console.log(Fruits);
const Fruits  = { fruitName1: "Orange", fruitName2: "Apple", fruitName3: "Grapes" };
console.log('Fruits', Fruits);

Output:

There will be no output as the above code will give an error as ‘Variable ‘Fruits’ is used before assigning’ & ‘Block Scoped variable ‘Fruits’ used before its declaration’.

‘Accessing before declaration’

We are trying to access the const before initialization which results in Reference Error.

Conclusion

With this, we shall conclude our topic ‘TypeScript const’. We have seen what is TypeScript const and how is it used. Looked into its syntax declaration and initialization with few examples. Most of the Errors we face with this small keyword ‘const’ are also shown. Most of the developers recommend using const to declare variables. Const is mostly for block-scoped variables and immutable variables. We have also listed out few rules for TypeScript const on the declaration, its usage and its limitations. Only references are immutable for const objects.

Recommended Articles

We hope that this EDUCBA information on “TypeScript const” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. TypeScript typeof
  2. TypeScript Optional Parameters
  3. TypeScript Dictionary
  4. TypeScript Operators
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more