More Variable Stuff
This leniency isn’t infinite, so we should keep the following things in mind when naming our variables:
Variables can be as short as one character, or they can be as long as you want—think thousands and thousands of characters.
Variables can start with a letter, underscore, or the $ character. They can’t start with a number.
Outside of the first character, our variables can be made up of any combination of letters, underscores, numbers, and $ characters. We can also mix and match lowercase and uppercase to our heart’s content.
Spaces are not allowed.
Below are some examples of valid variable names:
let myText; let $; let r8; let _counter; let $field; let thisIsALongVariableName_butItCouldBeLonger; let __$abc; let OldSchoolNamingScheme;
Outside of valid names, there are other things to focus on as well, such as naming conventions and how many people commonly name variables and other things that you identify with a name. We will touch on these things in other chapters.
More on Declaring and Initializing Variables
Declaring a Variable Is Optional
For example, we don’t have to use the let keyword to declare a variable. We could just do something as follows:
myText = "hello, world!"; alert(myText);
Notice the myText variable is being used without formally being declared with the let keyword. While not recommended, this is completely fine. The end result is that we have a variable called myText. The only thing is that, by declaring a variable this way, we are declaring it globally. Don’t worry if the last sentence makes no sense. We’ll look at what globally means when talking about variable scope later.
Declaring and Initializing on Separate Lines is Cool
There is one more thing to call out, and that is this: The declaration and initialization of a variable does not have to be part of the same statement. We can break it up across multiple statements:
let myText; myText = "hello, world!"; alert(myText);
In practice, we will find ourselves breaking up our declaration and initialization of variables all the time.
Changing Variable Values and the const Keyword
Lastly, we can change the value of a variable declared via let to whatever we want whenever we want:
let myText; myText = "hello, world!"; myText = 99; myText = 4 * 10; myText = true; myText = undefined; alert(myText);
const siteURL = "https://www.google.com"; alert(siteURL);