Variable declaration is the process of creating a new variable and specifying its name. JavaScript provides three ways to declare variables: using
the var
, let
, and const
keywords.
- The
var
keyword is used to declare function-scoped or global-scoped variables, i.e. they are accessible throughout the function or
the entire program, respectively.
- The
let
keyword is used to declare block-scoped variables, that is, variables accessible only within the nearest curly braces
block where it is defined.
- The
const
keyword is used to declare variables that are constant, meaning their values cannot be reassigned.
Explicitly declaring variables improves code readability and maintainability. It makes it clear to other developers that you are creating a new
variable and sets expectations about its scope. It also helps catch typos and avoid potential issues caused by accidentally reusing variable
names.
If you assign a value to a variable without declaring it with var
, let
, or const
, JavaScript treats it as an
implicit global variable. Implicit globals can lead to unintended consequences and make it difficult to track and manage variables. They can cause
naming conflicts, make code harder to understand, and introduce bugs that are hard to trace.
function f() {
i = 1; // Noncompliant: i is global
for (j = 0; j < array.length; j++) { // Noncompliant: j is global too
// ...
}
}
You should explicitly declare all the variables of your code. Use the const
keyword if the variable is only assigned once and the
let
keyword otherwise.
function f() {
const i = 1;
for (let j = 0; j < array.length; j++) {
// ...
}
}