JavaScript Variables
JavaScript Variables are containers for storing data values.
-
Create a JavaScript variable that can use the keyword let.
Example
let message = 'Hello World!'; console.log(message); // Hello World let myName = "Mike"; console.log(myName); // Mike message = myName; // Assign the value of myName to message console.log(message); // Mike
-
The "old" var
- In earlier scripts, you could find the keyword var instead of let.
- Both the keyword var and let can be used to define a variable.
-
var has no block level scope. var can run through if, for, or other code blocks, which is equivalent to being able to ignore them.
Example 1
// var if(true) { var appleColor = 'red'; } console.log(appleColor); // Return red. It can be seen that the variable survives if. // let if(true) { let appleColor = 'red'; } console.log(appleColor); // Error: appleColor is not defined. It can be seen that variables are destroyed after if.
Example 2
for(var i = 0; i < 10; i++) { var getNumber1 = i; let getNumber2 = i; } console.log(i); // 10 console.log(getNumber1); // 9 console.log(getNumber2); // Error: getNumber2 is not defined for(let j = 0; j < 10; j++) { // ... } console.log(j); // Error: j is not defined
-
When the function starts (or the global script starts), the var declaration is processed, that is, all the var will rise to the top of the function.
Example
console.log(phrase); // undefined, no error reported var phrase = "Hello"; // assignment console.log(phrase); // Hello // The upper code is equivalent to the lower code var phrase; console.log(phrase); // undefined, no error reported phrase = "Hello"; // assignment console.log(phrase); // Hello
let is now the main way to declare variables.
-
Variable naming
-
Variable names can only contain letters, numbers, or symbols $and '; the first character cannot be a number.
Example
let $ = 10; let _ = 19; console.log($ + _); // 29
-
Camel case is usually used when the name contains more than one word.
Example
let myName = "Mike"; let myBirthday = "11.01.1911";
Reserved words, such as let and return, cannot be used as variable names.
-
-
Constants
-
const is like let, but the value of the variable cannot be changed.
Example
const myBirthday = "11.01.1911"; myBirthday = "22.02.1922"; // Error: Assignment to constant variable.
-
Use constants named uppercase and underscore as aliases for hard to remember values
Example
// Color hexadecimal values are hard to remember, write, and read. Unlike age, they change every year. In this case, capital constants can be used. In the same way, capital constants can be used for birthday dates. const COLOR_RED = "#F00"; const COLOR_GREEN = "#0F0"; const COLOR_BLUE = "#00F"; const COLOR_ORANGE = "#FF7F00"; let appleColor = COLOR_RED; console.log(appleColor); // #F00
-