In this tutorial we’re going to learn how to use Const and let function in JavaScript. JavaScript let
is used to declare variables. The variables declared using let
are block-scoped. This means they are only accessible within a particular block. For example,
Let keyword
<script type="text/javascript">
let name = 'Amit';
{
let name = 'Kumar';
console.log(name);
}
console.log(name);
</script>
Output :-
Const example:-
We use the const keyword in JavaScript to declare variables whose value can be initialized only at the time of declaration. It is similar functionality of declaring variables as the other keywords provided in JavaScript i.e. var and let.
Example:-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<div id="result"></div>
<script type="text/javascript">
const NUM = 10;
var text = "";
for (let NUM = 0; NUM < 10; NUM++) {
text += NUM + ",";
}
text += "<br>"
try {
NUM = 20;
} catch (err) {
text += err.message;
}
document.getElementById("result").innerHTML = text;
</script>
</body>
</html>
Output:-
[…] How to use Let and Const in JavaScript ? […]