Table of Contents
- Table of Contents
- What is a variable?
- Declaring a variable
- Declaring multiple variables at once
- Changing the value
- Rules for declaring variables
What is a variable?
Declaring a variable
A variable can be declared, that is created , with the
let keyword followed by the name of
the variable, followed by an equal sign, follwed by the value, and that’s it:
let puppets = 99;
The above statement declares a variable named puppets and assigns it the number 99. That is not the only way to do it. You may first only declare the variable name. And then after that you may or may not assign a value to it. Like this:
let bugs; bugs = 98;
After a variable has been declared, it may be accessed if needed. Like you can alert the contens of a variable just by putting the name of the variable in between the brackets:
Declaring multiple variables at once
You can also declare an infinite number of variables with a single let keyword. Let’s have a look at this example:
let ants = 97, peacocks = 96, sparrows = 95, butterflies = 94;
While you can do this and get away with this so easily, yet may not grow up to adore this as much as you are doing now sitting there reading this. For the sake of readability, always consider declaring variables line by line.
let ants = 93; let peacocks = 92; let sparrows = 91; let butterfiles = 90;
Although, I got those numbers wrong, you may now have an appreciation for the readability this multi-line variant brings. Embrace it. Move on.
Weird ways you can declare variables include doing these:
let ants = 89, peacocks = 88, sparrows = 87, butterflies = 86; let what = 85 , does = 84 , it = 83 , even = 82 , mean = 81;
Changing the value
You may change the value of a variable any time you like:
let bottles = 80; bottles = 70; // value changed alert(bottles); // outputs 70
Rules for declaring variables
Variable names must contain only letters, digits, underscores (_), and/or dollar signs ($).
butterflyis different from
Butterfly. So, variable names are case sensitive.
Variable names cannot start with a digit. So
5fortuneis an illegal name.
You cannot use reserved keywords as variable names. These inlcude words used by the language as syntax like:
You can also declare objects which cannot change value. These are called constants. They are declared
const paintings = 79;
Once the above statement is executed, the following statement would result in an error:
paintings = 78;