W3docs

javascript · Javascript Basics

What is the purpose of the 'const' keyword in JavaScript?

Answers

  • To declare a variable that might change later
  • To declare a constant variable whose value cannot be changed
  • To create a new function
  • To define a conditional statement
  • To import a module
# Understanding the 'const' keyword in JavaScript The use of the 'const' keyword in JavaScript is to declare a constant variable whose value is not supposed to be changed once it is set. This is different from using 'var' and 'let' for declaring variables, which can have their values changed over time. If you try to reassign a new value to a 'const' variable, JavaScript will throw an error. ## Practical Example: Consider the following block of JavaScript code: ```javascript const PI = 3.14159; console.log(PI); // Outputs: 3.14159 ``` In this example, the constant `PI` is declared and assigned the value `3.14159`. Once this is done, trying to change the value of `PI` will result in an error. Trying to reassign the value like so: ```javascript PI = 3.14; // Outputs: Error! Uncaught TypeError: Assignment to constant variable. ``` As shown in the code above, JavaScript throws an error informing us that we're trying to assign a value to a constant variable, which is not allowed. ## Best Practices: The question then becomes, when to utilize 'const' versus other variable declaring keywords like 'let' and 'var'? The answer typically falls on the expected behavior of the variable. - If the variable is neither going to be used outside of its scope nor reassigned, then 'const' is the most appropriate choice. - If the variable may need to be reassigned, such as a counter or accumulator, then use 'let'. - While 'var' still functions as a variable declaring keyword, most developers prefer 'let' and 'const' due to their improvements in scoping. Using the appropriate keyword for declaring variables not only makes your code easier to understand but also helps prevent bugs and errors in your JavaScript projects.