W3docs

es6 · ES6 Basics

ES6 introduces a special "const" declaration. Do you know what it does?

const PI = 3.14; 
console.log(PI) //Prints 3.14

Answers

  • It is exactly the same as let.
  • It is used to define math-related variables.
  • Const turns variables into constants, and they can't be changed.
# Understanding the "const" Declaration in ES6 The introduction of ES6 (ECMAScript 2015) brought compelling new features to JavaScript, among which is the "const" declaration. Despite the common misconception, `const` is not exactly similar to `let` and neither is it specifically used for math-related variables. The correct understanding of `const` according to the quiz question above is that it is used to declare variables that are to remain constant throughout the program. In other words, once a variable is defined with `const`, you can't change its value. ## The Role of "const" The `const` declaration creates a read-only reference to a value. This does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance: ```javascript const PI = 3.14; console.log(PI) //Prints 3.14 PI = 99; //TypeError: Assignment to constant variable. ``` In the example above, the variable `PI` has been declared as a constant and it’s assigned the value 3.14. When you try to reassign a new value to `PI`, JavaScript throws a TypeError notifying you of an assignment to a constant variable. This is because `const` creates an immutable variable binding. ## Practical Applications Using `const` makes your JavaScript code more predictable, thus reducing chances of bugs and making it easier to read and understand. It's particularly useful when you have a reference that you don’t want to change by accident like a configuration object or a function that’s supposed to stay the same. ## Best Practices While using `const`, bear in mind that only the assignment is immutable, not the value. So if you assign an object or an array to a `const` variable, the contents can still be modified: ```javascript const obj = {a: 1}; obj.a = 2; // This will work. obj.a is now 2 console.log(obj); // {a: 2} const arr = [1, 2, 3]; arr.push(4); // This will work. arr is now [1,2,3,4] console.log(arr); // [1, 2, 3, 4] ``` In JavaScript, `const` doesn't mean constant state, but constant reference. This is a common area of confusion, and an important concept to understand. Remember, `const` isn't a magic bullet to make everything unchangeable. It merely prevents re-assignment of a variable identifier. In the course of writing JavaScript code, ensure to use `const` whenever you have identifiers that shouldn’t be reassigned. This would make your code more robust and less prone to bugs.