(Turn) JavaScript study notes: variables

There are variables in many languages, and that's the basics. There are variables in JavaScript too, and I've been learning about that recently. Today, let's summarize some basic knowledge about variables in JavaScript.

Variable Naming Rules Variables can be used to name values

​​in JavaScript. The names of variables are called identifiers and need to follow certain rules.

A variable name in JavaScript (also known as an identifier) ​​has certain rules for naming:

it must start with a letter, underscore (_) or dollar sign ($), and subsequent characters can contain numbers (0-9 ), such as num, _name, $doc, etc.;
variable names are case-sensitive, and uppercase letters can be uppercase (A~Z) and lowercase (a~z);
declaration methods

There are three declaration methods in JavaScript:

var: declare variables , optionally initialized to a value. Details
let: Declare a block-scope local variable, optionally initialized to a value. Details
const: Declare a read-only named constant. Details
Declare variables

There are three common ways to declare variables. Direct assignment using the keyword

var Using the keyword let Using the keyword var Using the keyword var declares a variable and can initialize the variable at the same time. For example: var i; var num; var a, b; var name ='bingdian';










var i = 0, j = 1 , k=6;
Variables declared using the var keyword can be divided into global variables and local variables according to the scope of the variable. And global variables and local variables is a headache concept, especially for a beginner, it is even more confusing. We will discuss and learn about this concept later.

Also variables declared with the var keyword are permanent, and deleting them with the delete operator will throw an error:

var a = 1;
b = 2;

delete this.a; // throws in strict mode TypeError, otherwise the execution fails without any prompt.
delete this.b;

console.log(a, b); // Throws ReferenceError.
// The 'b' property has been removed.
Direct assignment

In the code, you can assign a declaration name directly, such as:

x = 42;
This creates a global variable and causes a strict warning when JavaScript is compiled. Declaring a variable this way is strongly discouraged in code.

Using the keyword let The

keyword let is a new command in ES6 to declare a local variable of a block-level scope, and to initialize the variable at the same time. Its usage is similar to var, except that variables declared by let are only valid within code blocks:

{
    let a = 10;
    var b = 10;
    console.log(a); // 10
}

console.log(a); // Uncaught ReferenceError: a is not defined
console.log(b); // 10
The above code is in the code block, using let and var to declare two variables respectively. These two variables are then called within the code block, and the returned values ​​are both correct values. But when these two variables are called outside the code block, the variable declared by let reports the error message Uncaught ReferenceError: a is not defined, while the variable declared using var returns the correct value of 10. This also proves again that the variable declared by let is only valid in the code block in which it is located.

let vs var

In short, let's scope is block, and var's scope is function (either global or local):

var a = 5;
var b = 10;
if (a !== undefined) {
    let a = 10; // the field is inside the if block
    var b = 5; // the field is inside the function
    console.log(a); // 10
    console.log(b); // 5
}
console.log(a) ; // 5
console.log(b); // 5
One more thing about var is that you can declare the same variable repeatedly, while let doesn't allow you to declare a variable repeatedly in the same scope. Such as:

function func1(){
  let a = 'w3cplus';
  var a = 'blog';
  console.log(a);
}
func1();
// repl: Duplicate declaration "a"

function func2(){
  var a = "w3cplus";
  var a = "blog";
  console.log (a);
}
func2(); //
The variable declared by blog uses the var keyword, the variable can be promoted, and the let key does not have variable promotion. Look at two pieces of code:

console.log(foo); // ReferenceError
let foo = 2;
while using var will not report an error

console.log(foo); // undefined
var foo = 2;
When using var to declare a variable, All var statements in a function should be placed as close to the top of the function as possible.

Constants

As mentioned earlier, there are three declaration methods in JavaScript, among which the const keyword is used to create a read-only constant. The naming convention for constant identifiers is the same as for variables.

The value of a constant declared with const cannot be changed as long as it is declared.

const PI = 3.1415;
PI // 3.1415

PI = 3;
// TypeError: "PI" is read-only
The above code indicates that changing the value of the constant will result in an error.

Variables declared by const cannot be changed as long as they are declared, so they must be initialized immediately and cannot be left to assign values ​​later, otherwise an error will be reported.

const foo;
// SyntaxError: missing = in const declaration
const and let scope are the same, only valid in the block scope where the declaration is located.

if (true) {
  const MAX = 5;
}

MAX // Uncaught ReferenceError: MAX is not defined
The constant declared by the const command is also not promoted, and there is also a temporary dead zone, which can only be used after the declared position.

if (true) {
  console.log(MAX); // ReferenceError
  const MAX = 5;
}
The above code is called before the constant MAX is declared, and the result is an error.

The constant declared by const is also not repeatable declaration like let.

var message = "Hello!";
let age = 25;

// Both lines below will report an error
const message = "Goodbye!";
const age = 30;
A constant cannot have the same name as another variable or function in its scope.

The following example demonstrates the properties of constants. Check out this example in your browser's console:

// Note: Constants can be declared in uppercase and lowercase, but will usually be in all uppercase English.

// define constant MY_FAV and assign 7
const MY_FAV = 7;

// in Firefox and Chrome this will fail without error (in Safari this assignment will succeed)
MY_FAV = 20;

// output 7
console.log("my favorite number is: " + MY_FAV);

// Attempt to redeclare an error
const MY_FAV = 20;

// MY_FAV is reserved for the above constant, this operation will fail
var MY_FAV = 20;

// MY_FAV is still 7
console.log("my favorite number is " + MY_FAV);

// here is a syntax error
const A = 1; A = 2;

// constant requires an initial value
const FOO; // SyntaxError: missing = in const declaration

// constant can be defined as object
const MY_OBJECT = {"key": "value"};

// Rewriting the object will fail as above
MY_OBJECT = {"OTHER_KEY": "value"};

// Object properties are not protected, the following statement will successfully execute
MY_OBJECT.key = "otherValue"
; Values ​​A variable declared

with var or let without an initial value will be set to undefined. So we can judge whether a variable has an initial value by this method:

var a;
if (a === undefined) {
    ...
} else {
    ...
}
undefined values ​​will be treated as boolean type environments make false. For example, the following code will run the function myFunction because the elements in the array myArray are not assigned values:

var myArray = new Array();
if (!myArray[0]) myFunction();
the value of undefined in the context of a numeric type is converted to NaN:

var a;
a + 2; // NaN
When you evaluate an empty variable, the null value null is treated as 0 in numeric context, and as false in boolean context. For example:

var n = null;
console.log(n * 32); //
truth for 0 variables

Many people may have noticed that in Javascript, a variable and a property of an object have many similarities. In fact, there is no essential difference between them. In Javascript, any variable is a property of a specific object.

Global variables are properties of the global object. Before the Javascript interpreter starts running and the Javascript code is not executed, a global object will be created, and then the Javascript interpreter will define some properties for it. These properties are the built-in variables and methods that we can use directly in the Javascript code. . After that, whenever we define a global variable, we actually define a property on the global object.

In the client-side Javascript, this global variable is the Window object, which has an attribute window that points to itself, which is our commonly used global variable.

For the local variables of the function, when the function starts to execute, a corresponding calling object will be created, and the local variables of the function are stored as its properties. This prevents local variables from overriding global variables.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327104962&siteId=291194637
Recommended