Learn about the JavaScript const keyword, block scope, and constant objects.
Understand how to declare and use constants, the scope of variables, and modifying properties.
Enhance your JavaScript knowledge with practical examples.
In JavaScript, the const keyword is used to declare a constant variable.
A constant is a variable that cannot be reassigned once it has been assigned a value.
It provides a way to define variables that should not be changed throughout the program execution.
JavaScript code:
<script> // Here we decleare intialize a const :x and assign vaule =16 const x=16; // output the value of this const by alert() method. alert("The value of const variable of x ="+x); </script>
<!DOCTYPE html> <html> <head> <title>decleare variable by const keyword</title> </head> <body> <script> const x=16; alert("The value of const variable of x ="+x); </script> </body> </html>
Here’s an example of using const in a complete HTML code:
<!DOCTYPE html> <html> <head> <title>JavaScript Const Example</title> </head> <body> <h1>JavaScript Const Example</h1> <script> // Declare a constant variable const PI = 3.14159; // Try to reassign the constant variable // This will result in an error // PI = 3.14; // Access and use the constant variable console.log("The value of PI is: " + PI); // You can also declare multiple constant variables in one statement const firstName = "Gogo", lastName = "Rabei", age = 15; console.log("Name: " + firstName + " " + lastName); console.log("Age: " + age); </script> </body> </html>
Explanation:
1-In this example, we declare a constant variable PI with the value of 3.14159. 2-We then try to reassign the PI variable, which will throw an error since it is a constant and cannot be changed.
3-We also declare multiple constant variables firstName, lastName, and age in a single statement using commas.
4-These variables are assigned string and number values respectively.
5-The console.log () function is used to display the values of the constant variables in the browser’s console.
6-You can open the browser’s developer tools to view the console output.
7-When you run this HTML code in a browser, you should see the constant values printed in console.log (), and if you try to reassign the PI variable, it will generate an error.
The const keyword in JavaScript is used when you want to declare a variable that should not be reassigned after its initial assignment.
It is suitable for situations where you have a value that remains constant throughout the execution of your code.
Here’s a complete HTML code example that demonstrates when to use const:
<!DOCTYPE html> <html> <head> <title>JavaScript Const - When to Use</title> </head> <body> <h1>JavaScript Const - When to Use</h1> <script> // Declare constant variables for mathematical operations const PI = 3.14159; const GRAVITY = 9.8; // Declare constant variables for configuration values const API_KEY = "your-api-key"; const MAX_RESULTS = 10; // Use constant variables in calculations const radius = 5; const area = PI * radius * radius; // Use constant variables in conditional statements if (area > 50) { console.log("Area is greater than 50"); } else { console.log("Area is not greater than 50"); } // Use constant variables in function parameters function greet(name) { console.log("Hello, " + name + "! Welcome to our website."); } greet("John"); // Use constant variables in object properties const person = { name: "Jane", age: 30, country: "USA" }; console.log(person.name + " is from " + person.country); </script> </body> </html>
Explanation:
1-In this example, we demonstrate various scenarios where const can be used:
2-We declare constant variables PI and GRAVITY for mathematical operations.
3-These values are not expected to change during the execution of the code.
4-We declare constant variables API_KEY and MAX_RESULTS for configuration values.
5-These values are typically set once and remain constant throughout the application.
6-We use the constant variables in calculations, such as calculating the area of a circle using the radius and PI constant.
7-We use the constant variables in conditional statements to make decisions based on their values.
8-We use the constant variable name as a function parameter in the greet() function.
9-We use the constant variables in object properties to define the properties of a person object.
When you run this code in a browser and open the browser’s console, you will see the output of the console.log statements, which demonstrate the usage of const in various scenarios.
Here are some properties of const variables:
Here’s a complete HTML code example that demonstrates the property of const variables where they must be initialized at the time of declaration:
<!DOCTYPE html> <html> <head> <title>JavaScript Const - Must be Initialized</title> </head> <body> <h1>JavaScript Const - Must be Initialized</h1> <script> // Declare a const variable without initializing it const age; // This will result in a SyntaxError console.log(age); </script> </body> </html>
Explanation:
1-In this example, we attempt to declare a const variable named age without initializing it.
2-However, this will result in a SyntaxError because const variables must be assigned an initial value at the time of declaration.
3-If you run this code in a browser and open the browser’s console, you will see an error message indicating that there is a missing initializer in the declaration of the const variable.
Another example:
A const variable must be assigned an initial value at the time of declaration. Unlike let, you cannot declare a const variable without initializing it.
JavaScript code:
<script> Const pi=22/7; Alert(pi); </script>
Here’s an example of using const variables in a complete HTML code:
<!DOCTYPE html> <html> <head> <title>JavaScript Const Example</title> </head> <body> <h1>JavaScript Const Example</h1> <script> // Declare and initialize a constant variable const PI = 3.14159; // Try to reassign the constant variable // This will result in an error // PI = 3.14; // Block scope example if (true) { const message = "Hello!"; console.log(message); // Output: Hello! } // console.log(message); // ReferenceError: message is not defined // Must be initialized // const age; // SyntaxError: Missing initializer in const declaration // Objects and arrays as const variables const person = { name: "Gogo", age: 25 }; person.name = "Omar"; // Modifying properties of a const object is allowed // person = {}; // Attempting to reassign the const object will result in an error const numbers = [1, 2, 3]; numbers.push(4); // Modifying elements of a const array is allowed // numbers = []; // Attempting to reassign the const array will result in an error console.log("The value of PI is: " + PI); console.log("Modified person object: ", person); console.log("Modified numbers array: ", numbers); </script> </body> </html>
Explanation:
1-In this example, we declare a const variable PI with the value of 3.14159.
2-We then try to reassign the PI variable, which will throw an error since it is a constant and cannot be changed.
3-We also demonstrate the block scope behavior of const variables. Inside the if block, we define a const variable message and print its value, which works fine.
4-However, if we try to access message outside the block, it will result in a ReferenceError since message is not defined in that scope.
5-We show that const variables must be initialized at the time of declaration. Attempting to declare a const variable without an initial value will result in a SyntaxError.
6-Furthermore, we demonstrate that while the value of a const object or array cannot be reassigned, you can still modify the properties or elements within them.
7-In the example, we modify the name property of the person object and push an element to the numbers array, which is allowed.
However, trying to reassign the entire object or array will generate an error.
The output of the modified object and array is printed in the page using document.write().
Once a const variable is assigned a value, its value cannot be changed or reassigned.
Attempting to reassign a const variable will result in an error.
Here’s a complete HTML code example that demonstrates the property of const variables where their values cannot be reassigned:
<!DOCTYPE html> <html> <head> <title>JavaScript Const - Value Cannot be Reassigned</title> </head> <body> <h1>JavaScript Const - Value Cannot be Reassigned</h1> <script> // Declare and initialize a constant variable const message = "Hello, World!"; // Try to reassign the constant variable message = "Goodbye!"; // This will result in an error console.log(message); </script> </body> </html>
Explanation:
1-In this example, we declare a const variable named message and assign it the value of “Hello, World!”.
2-However, when we attempt to reassign the message variable to “Goodbye!”, it will throw an error because const variables cannot be reassigned.
3-If you run this code in a browser and open the browser’s console, you will see an error message stating that you cannot assign a new value to a const variable.
Here’s a complete HTML code example that demonstrates the block scope and const usage in JavaScript:
<!DOCTYPE html> <html> <head> <title>JavaScript Const - Block Scope</title> </head> <body> <h1>JavaScript Const - Block Scope</h1> <script> // Global scope const name = "Gogo"; let age = 25; console.log("Global scope: " + name + ", " + age); if (true) { // Block scope const name = "Omar"; let age = 30; console.log("Block scope: " + name + ", " + age); } console.log("Global scope again: " + name + ", " + age); </script> </body> </html>
1-In this example, we demonstrate the block scope behavior of const and let variables in JavaScript:
2-We declare a const variable named name and a let variable named age in the global scope.
3-We print the values of these variables in the global scope using console.log.
4-Inside the if statement block, we declare a new const variable named name and a new let variable named age.
5-These variables have the same names as the variables in the global scope, but they are separate and have block scope.
6-We print the values of these variables inside the block using console.log.
7-After the block, we print the values of the global variables again using console.log. Here, you can observe that the block-scoped variables do not affect the values of the global variables.
8-When you run this code in a browser and open the browser’s console, you will see the output of the console.log statements, which demonstrate the block scope behavior of const and let variables.
Here’s a complete HTML code example that demonstrates the block-scoping behavior of const variables:
<!DOCTYPE html> <html> <head> <title>JavaScript Const - Block-Scoped</title> </head> <body> <h1>JavaScript Const - Block-Scoped</h1> <script> // Global scope const message = "Hello, World!"; console.log("Global scope: " + message); if (true) { // Block scope const message = "Hello, Block!"; console.log("Block scope: " + message); } console.log("Global scope again: " + message); </script> </body> </html>
Explanation:
1-In this example, we declare a const variable named message in the global scope and assign it the value of “Hello, World!”.
2-We then print the value of the message variable in the global scope.
3-Inside the if statement block, we declare another const variable named message with the value of “Hello, Block!”.
4-We also print the value of the message variable within the block.
5-After that, we print the value of the message variable again in the global scope.
6-As you can see, the const variable declared inside the block has its own block scope and does not affect the value of the const variable in the global scope.
When you run this code in a browser and open the browser’s console, you will see the following output:
Global scope: Hello, World!
Block scope: Hello, Block!
Global scope again: Hello, World!
This demonstrates that the const variables are block-scoped, meaning they are only accessible within the block of code where they are defined.
The const variable inside the if block does not affect the const variable in the global scope.
Here’s a complete HTML code example that demonstrates the usage of constant objects and arrays in JavaScript:
<!DOCTYPE html> <html> <head> <title>JavaScript Const - Constant Objects and Arrays</title> </head> <body> <h1>JavaScript Const - Constant Objects and Arrays</h1> <script> // Constant object const person = { name: "John", age: 25, city: "New York" }; // Modifying properties of a constant object person.name = "Jane"; person.age = 30; console.log(person); // Constant array const numbers = [1, 2, 3, 4, 5]; // Modifying elements of a constant array numbers.push(6); numbers[0] = 0; console.log(numbers); </script> </body> </html>
Explanation:
1- In this example, we declare a constant object named person with properties for name, age, and city.
2-We then proceed to modify the properties of the constant object by assigning new values to person.name and person.age.
3-Despite being declared as constant, we can still modify the individual properties of the object.
4-Next, we declare a constant array named numbers with elements 1, 2, 3, 4, and 5.
5-We proceed to modify the array by adding a new element using push() and changing the value of the first element using indexing.
6-Similarly, despite being declared as a constant, we can modify the elements of the array.
7-When you run this code in a browser and open the browser’s console, you will see the output of the console.log statements, which display the modified constant object and array.
8-This demonstrates that while the value of a constant object or array cannot be reassigned, you can still modify its properties or elements.
Here’s a complete HTML code example that demonstrates the usage of constant objects in JavaScript:
<!DOCTYPE html> <html> <head> <title>JavaScript Const - Constant Objects</title> </head> <body> <h1>JavaScript Const - Constant Objects</h1> <script> // Constant object const person = { name: "Gogo", age: 15, city: "Cairo" }; console.log(person); // Modifying properties of a constant object person.name = "Omar"; person.age = 17; console.log(person); // Trying to reassign the constant object person = {}; // This will result in an error console.log(person); </script> </body> </html>
1-In this example, we declare a constant object named person with properties for name, age, and city.
2-We then proceed to print the initial state of the person object using console.log.
3-Next, we modify the properties of the constant object by assigning new values to person.name and person.age.
4-Despite being declared as constant, we can still modify the individual properties of the object.
5-However, when we attempt to reassign the entire person object using person = {}, it will result in an error. Reassigning a constant object is not allowed.
6-When you run this code in a browser and open the browser’s console, you will see the output of the console.log statements, which display the initial and modified states of the constant object.
7-Additionally, an error message will be shown in the console when trying to reassign the constant object.
Here’s a complete HTML code example that demonstrates an application of the concepts covered in this lesson:
<!DOCTYPE html> <html> <head> <title>JavaScript Application: Shopping Cart</title> </head> <body> <h1>JavaScript Application: Shopping Cart</h1> <script> // Declare constant variables for product details const productName = "iPhone 12"; const productPrice = 999.99; const currency = "USD"; // Declare variable for quantity let quantity = 3; // Calculate total price const totalPrice = productPrice * quantity; // Display product information and total price console.log("Product: " + productName); console.log("Price: " + productPrice + " " + currency); console.log("Quantity: " + quantity); console.log("Total Price: " + totalPrice + " " + currency); </script> </body> </html>
Explanation:
1-In this example, we create a simple shopping cart application using JavaScript. Here’s how it works:
2-We declare constant variables productName, productPrice, and currency to store the details of the product being added to the cart.
3-In this case, we’re using an iPhone 12 with a price of $999.99 in USD.
4-We declare a variable quantity and set it to 3 to represent the quantity of the product added to the cart.
5-We calculate the total price by multiplying the productPrice by the quantity and store it in the constant variable totalPrice.
6-We display the product information and the total price using console.log. This will show the product name, price, quantity, and total price in the browser’s console.
7-When you run this code in a browser and open the browser’s console, you will see the output of the console.log statements, which represent the product details and the calculated total price in the shopping cart.
Try to modify the variables and their values to simulate different scenarios in your shopping cart application.
Here’s a multi-choice quiz about the concepts covered in this lesson:
<!DOCTYPE html> <html> <head> <title>JavaScript Application: Shopping Cart</title> </head> <body> <h1>JavaScript Application: Shopping Cart</h1> <script> // Multi-choice quiz about JavaScript const, block scope, and constant objects // Array to store the quiz questions and choices const quiz = [ { question: "1. What does the 'const' keyword do in JavaScript?", choices: [ "a. Declares a variable that can be reassigned", "b. Declares a constant variable that cannot be reassigned", "c. Declares a variable with block scope", "d. Declares a variable that must be initialized" ], answer: "b" }, { question: "2. Which of the following describes the block scope behavior of 'const' and 'let' variables?", choices: [ "a. They are hoisted to the top of their scope", "b. They can be accessed outside the block where they are defined", "c. They are only accessible within the block where they are defined", "d. They have global scope" ], answer: "c" }, { question: "3. What happens when you try to reassign a value to a 'const' variable?", choices: [ "a. It will be updated with the new value", "b. It will throw an error", "c. It will create a new variable with the new value", "d. It will silently fail without any effect" ], answer: "b" }, { question: "4. Can you modify the properties of a constant object in JavaScript?", choices: [ "a. Yes, you can modify the properties of a constant object", "b. No, constant objects cannot be modified", "c. Only certain properties can be modified", "d. It depends on the JavaScript version" ], answer: "a" }, { question: "5. What is the purpose of using 'const' variables?", choices: [ "a. To declare variables with block scope", "b. To declare variables that must be initialized", "c. To declare constant variables that cannot be reassigned", "d. To declare variables that can be modified" ], answer: "c" } ]; // Function to run the quiz function runQuiz() { let score = 0; // Iterate over each question in the quiz for (let i = 0; i < quiz.length; i++) { const question = quiz[i].question; const choices = quiz[i].choices; const answer = quiz[i].answer; console.log(question); // Display the choices for each question for (let j = 0; j < choices.length; j++) { console.log(choices[j]); } // Prompt the for their answer const Answer = prompt("Enter your answer (a, b, c, or d):"); // Check if the 's answer is correct if (Answer.toLowerCase() === answer) { console.log("Correct!"); score++; } else { console.log("Incorrect!"); } } // Display the final score console.log("Quiz completed. Your score: " + score + " out of " + quiz.length); } // Run the quiz runQuiz(); </script> </body> </html>
Explanation:
1-In this quiz, we have an array quiz that contains multiple objects.
2-Each object represents a question and its corresponding choices, as well as the correct answer.
3-The runQuiz() function iterates over each question, displays the question and choices, prompts the for their answer, and checks if the ‘s answer is correct.
4-The final score is displayed at the end of the quiz.
5-To run this quiz, you can copy and paste the code into a JavaScript environment such as a browser’s developer console or a Node.js environment. Follow the prompts to answer each question by entering the corresponding choice (a, b, c, or d). The quiz will then evaluate your answers and display your final score.
رابط الدرس باللغة العربية من هنا
Here are some references you can use to learn more about the concepts covered in this lesson: