★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★

What is a variable

Variable as the most common is also our first contact with js js knowledge, believes everyone not unfamiliar, variable exists in almost all languages, for the interpretation of the variable in baidu encyclopedia for “variable or variables, it is to point to have no fixed value, can change the number. Variables in a number of symbols to express, generally use the Latin alphabet.” In JavaScript, variables are loosely typed (weakly typed). The so-called loose type is that it can be used to hold any type of data, without specifying the type of the variable when declaring it. So, when we declare a variable, we can store any type of data.

How do I declare a variable

The variable name

To declare a variable in js, we usually declare a variable in js with a keyword and a variable name.

  • The variable name must start with a letter, underscore (_), or dollar sign ($), and can be followed by a letter, underscore, dollar sign, or number
  • The variable name cannot exceed 255 characters
  • Variable names must be case sensitive
  • The variable name must not contain Spaces, line breaks, or other punctuation marks
  • You cannot use a variable name that is reserved by the scripting language, such as true, false, function, etc. (see the JavaScript reserved Keywords tutorial for details).

In addition to these js plain-text variable naming conventions, we usually have industry-wide naming conventions for variable names to make the code more readable.

  • Try to use words that match the current semantics, such asage,time, avoid meaningless character combinations, such asaaa,bbb
  • As part of the framework may be used$As keywords, we should also try to avoid using them$As a variable name
  • If more than two words are named, try to use the hump method of naming, e.guserAge,myFirstName
  • Try to avoid using Chinese as variable names, although that will not cause errors

Declare a variable

Js variable declaration method for keyword plus a variable name, said the name of the variable, we will talk about the declaration of the variable keyword, js variable declaration keyword has the following three kinds

var

The keyword var is the first keyword we learn js and the most commonly used to declare variables. The use method is directly followed by the keyword var and the variable name, such as

var message = 'hello world'
console.log(message) // hello world
Copy the code

Var features of the keyword

  • Repeatable declaration, but it doesn’t help
  • The declared variable can be modified
var message = 'hello'
message = 'world'
console.log(message) // world
Copy the code
  • There are initial values, each of which usesvarAll declared variables start withundefined
var message
console.log(message) // undefined
Copy the code
  • Multiple variables can be declared at the same time
var message, test, handleName
console.log(message) // undefined
console.log(test) // undefined
console.log(handleName) // undefined
Copy the code
  • varKeywords can be omitted
message = 'hello'
console.log(message) // hello

// If the var keyword is omitted in js, the global variable is automatically created
function foo() {
 message = 'hello'  console.log(message) // hello } foo() console.log(message) // hello  // If used, the variable in the current scope is created function foo() {  var message = 'hello'  console.log(message) // hello } foo() console.log(message) // message is not defined Copy the code

* Note that keywords must not be omitted in strict mode, otherwise an error will be reported

let

The let keyword is an important JavaScript keyword added in ES2015(ES6) and used in the same way as var

let message = 'hello world'
console.log(message) // hello world
Copy the code

Where the let keyword differs from var

  • Non-repeatable declarations, already declared variables will be declared again (in the same scope) error
var message
let message // Identifier 'message' has already been declared

let test = 'test'
let test = 'hello' // Identifier 'test' has already been declared
Copy the code
  • letDeclared variables only inletValid in the code block in which the command resides
{
  let a = 10;
  var b = 1;
}

a // ReferenceError: a is not defined. b / / 1 Copy the code

Using this feature of let solves a classic problem

for (var index = 0; index < 6; index++) {
  setTimeout(function() {
    console.log(index)
  }, 100)
}
Copy the code

The result of this code is six 6’s. This is because the index is defined by var, and the index used in each loop is a global variable. So by the time the loop is executed 100 milliseconds later, the index is already 6. You can solve this problem very well

for (let index = 0; index < 6; index++) {
  setTimeout(function() {
    console.log(index)
  }, 100)
}
// 0 1 2 3 4 5 Copy the code

Since the let is only valid for the current block of code, each loop here defines a new index, so the last output is the value of the loop. You might ask, if the variable I is redeclared for each round of the cycle, how does it know the value of the last round to calculate the value of this round? This is because the JavaScript engine internally remembers the value of the last round of the loop, and when the variable I of the round is initialized, it is calculated on the basis of the last round of the loop.

const

The const keyword is an important JavaScript keyword added in ES2015(ES6). It is used in the same way as var, except that const generates one or more constants. In some cases, when we define a value that we do not want to be overwritten or modified, we can use const

const message = 'hello world'
console.log(message) // hello world
Copy the code

The difference between the const and var keywords

  • Non-repeatable declaration
  • Declaration must be initialized, otherwise an error will be reported
const a // Missing initializer in const declaration
const b = 'test' / / right
Copy the code
  • Declared constants cannot be modified by assignment
const a = 'hello'
a = 'world' // Uncaught TypeError: Assignment to constant variable.
Copy the code
Const is not a constant in the strict sense of the word, because when we use const to define a constant as a reference type (primitives and reference types are discussed below), we can change the value of the reference type, although we cannot reassign it.Copy the code
const a = {
    name: 'Ming'
}
a.name = 'small house'
console.log(a.name) / / small house
Copy the code

Value of variable: basic type and reference type

We know that values in JS can hold all data types, so what are the data types in JS? There are six types of data types in JavaScript, including five simple data types (also called basic data types) and one complex data type — Object (Object). Since this article is mainly about variable related knowledge, data types are not explained in depth, but the knowledge is roughly said.

Basic types of

There are five basic data types :Undefined, Null, Boolean, Number, and String. The five basic data types are accessed by value because you can manipulate the actual values stored in variables. Let’s just go straight to the line.

var a = 'Ming'
var b = a
a = 'small house'
console.log(b) // 'xiao Ming'
Copy the code

Reference types

Because the knowledge of the object is relatively large, there will be a special article to introduce and summarize the following.

If you know that primitive types store values, and object types store addresses (Pointers), then when we define the value of a variable as an object, because we’re actually storing the address of that object in memory, we’re just referring to that object here, So something unexpected happens when you copy assignments and changes to some variables, like the code below

var a = {
  name: 'Ming'
}
var b = a
b.name = 'small house'
console.log(a.name) / / small house Copy the code

In the example above, when we assign a to b, we are actually assigning to b the address of the object referenced by a. In this case, a and b are actually referring to the same object, so when we modify either of them, we are modifying the same object

When we use a const constant as an object, all we hold in that constant is the address of an object. No matter how much we modify the object, the address of a const constant remains the same. In the example above, changing an object that is const does not violate the rule that const variables cannot be modified. Only if we assign a new object (i.e., a new address) to the constant, will the rule trigger const constants that are not modifiable.

Variable scope

Scope, for our purposes here, we can simply think of scope as the place where variables can take effect and be accessed. In JavaScript, there are global scopes and local scopes. Variables in the global scope are accessible everywhere. Variables in the local scope are accessible only in the current scope.

In some programming languages like C, each pair of braces has its own scope, which is called block scope. In JavaScript, there is no block-level scope (pre-ES6). Instead, there is function scope, so we often refer to local scope as function scope.

var a = "hello" // Global scope
function foo() {
    // A is accessible in this scope
    console.log(a) // 'hello'
    var b = 'world'
} foo() console.log(a) // 'hello' // Since the variable b is defined in function foo, it cannot be accessed outside of function foo's scope console.log(b) // b is not defined Copy the code

In JS, when you use a variable, the JavaScript engine will first look for it in the current scope, and if it can’t find it, it will go to the next level of scope. If you go all the way to the top-level scope (that is, the global scope) and cannot find it, an error will be reported.

ES2015(ES6) has added the let keyword, which allows us to declare variables in block-level scope (braces).

Variable ascension

In JavaScript, function and variable declarations are promoted to the top of the current scope.

//var a <------------------
console.log(a) / / undefined write
var a   // ---------------->
Copy the code

In the example above, we print a without an error, even though the declaration comes after the print statement, because the variable declaration is at the top of the current scope, which we call variable promotion.

Var a = ‘test’; var a = ‘test’; var a = ‘test’

console.log(a) // undefined
var a = 'test'

// The execution steps of the above code can be understood by the following code

var a console.log(a) a = 'test'  Copy the code

Combining the above function scope, let’s look at the following example

var a = 'test'
function foo() {
  console.log(a)
  var a = 'hello'
}
foo() Copy the code

Guess what it prints out, yes, undefined, we defined the global variable a, we defined the local variable a, so when we execute foo(), we’re actually looking for the local variable a in foo(), The local variable a is promoted to the top of function foo() by variable, but the variable assignment is not promoted, so the final print is undefined. The above code can be interpreted as follows

var a = 'test'
function foo() {
  var a
  console.log(a)
  a = 'hello'
} foo() Copy the code

It is important to note that let and const do not have variable promotion. Using them before you define them will cause an error. Interestingly, there is a difference between let and const

console.log(test) // Cannot access 'test' before initialization
const test = 'hello'

console.log(message) // message is not defined
let message = 'hello'
 // If we write in the local scope, the error is the same function foo() {  console.log(message) // Cannot access 'message' before initialization  let message = 'world' } foo() Copy the code

Based is poorer, the author does is the purpose of writing more in order to improve their abilities, but summary writing down to avoid a repetitive and errors, if can help to others is very happy, of course, if you find any problem are welcome at any time, I also will continue to learn, constantly to modify a new article, hope everybody progresses together, come on

This article was typeset using MDNICE