Over its lifetime JavaScript has increased the ways that variables can be declared. I am going to take a brief look at the various methods I have come across so far that can be used.
var test
The var keyword declares a variable (in this case called test) which can later have its value changed/altered. In this example I have declared an empty variable, but I could have added a string, boolean or numerical value e.g. var test = “this string is now in test”;
Declaring a variable this way allows for its value to be changed inside loops or functions, which can lead to the variable value being changed by mistake, especially if the same variable name is used more than once. For example:
var test = “this string is now in test”;
Would set test and then:
var test = “and now a different string”;
Would remove the first string and change it.
Also:
var test = “this string is now in test”;
Would set test and then:
test = “and now a different string”;
Would remove the first string and change it.
let test
The let keyword declares a variable (again, called test), however unlike var the let keyword does not let a variable name be declared more than once. So:
let test = “this string is now in test”;
Sets the test variable and:
let test = “and now a different string”;
Would fail, leaving test to contain “this string is now in test”. However:
let test = “this string is now in test”;
test = “and now a different string”;
Would allow for the variable value to be set to “and now a different string”.
const TEST
The const keyword declares a variable (called TEST), however unlike the previous method it makes the variable read only. Due to this the variable value should be set whilst defining the variable. For example:
const TEST = “this string is now in test”;
Would set the variable and its value and as it is read only it cannot be changed. Normally JavaScript variables are written in camel case, but const variables names are regularly written in capital case (uppercase) letters.