Home » JavaScript

const in JavaScript

JavaScript const: Here, we are going to learn about the const in JavaScript, how to create a constant in JavaScript?
Submitted by IncludeHelp, on February 01, 2019

const

Like other programming languages, JavaScript also provide the feature to create constants, we can make any identifier as constant by using the "const".

"const" is a keyword in JavaScript and it makes an identifier constant.

Syntax:

const identifier_name = value;

Points to remember:

  • While creating a constant, a value should be assigned.
  • A constant’s value cannot be changed.

Error

If we try to change the value of a constant following type error throws:

TypeError: Assignment to constant variable.

Example:

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
	<script>		
		const url = "www.example.com";
		const port_no = 25;
		
		//printing...
		document.write("url: " + url + "<br>");
		document.write("port_no: " + port_no + "<br>");
		
		//if you will try to change the value
		//it will not be changed
		try{
		port_no = 21;		
		}
		catch(err){
			document.write(err + "<br>");
		}
	</script>
</body>
</html>

Output

url: www.example.com
port_no: 25
TypeError: Assignment to constant variable.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.