No announcement
 

Let & Const and Template Literals

Let & Const

The let and const keywords were introduced in ECMAScript 6 (ES6) to declare variables. let allows you to declare variables that can be reassigned, while const is used for variables whose values should not be changed after assignment.

Example:

let_const.html

<!DOCTYPE html>
<html>
<head>
  <title>Let & Const Example</title>
</head>
<body>

<h2>Let & Const:</h2>
<p id="output"></p>

<script>
// Using let
let num = 5;
num = 10; // Reassignment allowed

// Using const
const PI = 3.14159;
// PI = 3.14; // Error: Cannot reassign a constant

document.getElementById("output").textContent = 
  "num: " + num + "\nPI: " + PI;
</script>

</body>
</html>

Output
num: 10 PI: 3.14159

Explanation:

  • In the HTML code, we have an empty <p> element with the id "output".
  • In the JavaScript code, we demonstrate the use of let and const.
  • We declare a variable num using let and assign it a value of 5. We then reassign it to 10.
  • We declare a constant PI using const and assign it the value 3.14159. Attempting to reassign PI results in an error.

Template Literals

Template literals provide an elegant way to create strings by allowing you to embed variables and expressions directly within the string using ${} placeholders.

Example:

template_literal.html

<!DOCTYPE html>
<html>
<head>
  <title>Template Literals Example</title>
</head>
<body>

<h2>Template Literals:</h2>
<p id="output"></p>

<script>
let name = "Alice";
let age = 30;

let message = `Hello, my name is ${name} and I am ${age} years old.`;
document.getElementById("output").textContent = message;
</script>

</body>
</html>

Output
Hello, my name is Alice and I am 30 years old.

Explanation:

  • In the HTML code, we have an empty <p> element with the id "output".
  • In the JavaScript code, we declare two variables, name and age.
  • We create a message string using template literals (enclosed within backticks ``) and embed the name and age variables using ${} placeholders.
  • The resulting message is displayed in the <p> element with the id "output".