JavaScript identifier

1. What is an identifier?

The name of a variable, function, attribute, or function argument.

2. Naming rules for identifiers:

(1) Consists of letters, digits, underscores (_), and dollar signs ($)

(2) Do not start with a number

(3) Can not use keywords, reserved words as identifiers

What is a variable?

ECMAScript variables are loosely typed

Loose type: Can be used to hold any type of data

In other words, each variable is just a placeholder to hold the value

Variable naming conventions

1. Only numbers, letters, underscores (_), and $are allowed (cannot start with a number).

2. Be case sensitive

3. Don’t duplicate definitions/declarations

4. Keywords/reserved words cannot be used as variable names

5. Semantic hump naming

6. Name is name

  1. Keyword => js words that have been given special functions
  2. Reserved words => JS reserved words that may be used in the future

Key words:

Break, else, new,var, case, finally, return, void, catch, for, switch, while, continue, function, this, with, default, if, throw, Delete, in, try, do, Instranceof, TypeofCopy the code

Reserved words:

Abstract, enum, int, short, Boolean, export, Interface, static, byte, extends, long, super, char, final, native , synchronized, class,float, Package, throws, const, goto, private, TRANSIENT, debugger, implements, protected, volatile, double, import And the publicCopy the code
// The following are all valid variable names

let a;
let A;
let b333;
let _abc;
let $;
let $o0_0o$;
let_____.let _;

// The following are invalid variable names
let 123a;
let 12_a;
let abc@163;
letABC RMB;let let;
let class;
Copy the code

Note:

Keywords, reserved words do not need to be able to remember, in the future learning process will be exposed to a large number of reserved keywords,

Define multiple ways to write a variable

Define a variable using the let keyword

The same variable cannot be defined more than once.

1. Assignment at definition (common)

The assignment operator variable is assigned with an equal sign. The equal sign is the assignment symbol. In JS, the equal sign has no other meaning.

let x = 10;  // A variable can be understood as a container used to store a value.
// Select * from a where a = 1; // Select * from a where a = 1
let y = 20; // JavaScript variable names are case sensitive, x and x are two different variables.


// = The Spaces on both sides are not necessary for aesthetics
Copy the code

2. Define and assign

let x;
let y;
x = 10;
y = 20;
Copy the code

3. Define multiple variables and separate them with commas (,)

let x,y;
x = 10;
y = 20;

/ / equivalent to the
let x = 10,
 	y = 20;
Copy the code

Pay attention to

This is also valid if you forget to write the let command when assigning a value to a variable.

let a = 1;

// Basically equivalent

a = 1;
It is not recommended to omit the let operator to define global variables. It is recommended to always declare variables using the let command
Copy the code

If you use a variable without declaring it, JavaScript will report an error telling you that the variable is undefined.

console.log(x);
// ReferenceError: x is not defined
Copy the code

4. Define constants

const x = 3.1315927;

// Const variables are called constants and are not allowed to be reassigned.

// Develop conventions for constant names in all uppercase
Copy the code

Note:

= The left-hand side is a variable and cannot be an expression

let a = 10;
let b = 5; 
let c;
a - c = b   // The left side of the assignment operator cannot be an expression
console.log(c);    
Copy the code

statements

JavaScript programs are executed in lines, one line at a time. Typically, a line is a statement.

A statement is an operation to accomplish a task.

let a = 1 + 3;
// this statement uses let to declare variable A and then assigns the result of 1 + 3 to variable A
//1 + 3 is called expression, which refers to an expression used to get a return value.
Copy the code

The difference between statements and expressions

Statements are used to perform an operation and generally do not return a value

The expression returns a value, and it must return a value. Expressions can be used wherever values are expected in the JavaScript language.

The same type of data (such as constants, variables, functions, etc.), with operation symbols according to certain rules connected, meaningful formula is called expression

For example, the right side of the equals sign of an assignment statement is expected to be a value, so various expressions can be placed.

More on that later

JavaScript is a dynamically typed language, that is, there is no limit to the type of a variable, and variables can change their type at any time.

let a = 100;
a = "Cloud Mu Mu";
// The variable a is first assigned to a value and then reassigned to a string
// The second assignment does not need to use var because variable A already exists
Copy the code

Distinguish between variables and immediate quantities

Do not enclose quotation marks around variables. If the variable is quoted, it becomes a direct value of the string.

let a = 200;
console.log("a");     //a

let a = "Hello, everybody.";
console.log(a);	/ / hello, everyone

// The quotation mark is the delimiter of "string", so the "a" in the double quotation mark has lost the meaning of the variable and is a string "a".
Copy the code

The data type

In a language, there are all kinds of values.

All kinds of data are used to solve the needs of different application scenarios.

Basic types:

The number of numerical

String string

Boolean Boolean value

Undefined undefined

Null null pointer

Complex data types:

object

ES6 new

The only value symbol

Bigint big integer

String

Basic introduction

A string is a sequence of zero or more characters, that is, a string.

String is a technical term, which is basically what we say.

Strings can be wrapped in double quotation marks (” “) or single quotation marks (” “) or template strings (” “),

There is no difference in appearance, can be used at will

 let b = "YunMu"; / / double quotation marks
 let bb = 'Xue Baochai'; / / single quotation marks
 let bbb = 'Lin Daiyu'; // Template string
Copy the code

If a number is enclosed in quotes, it’s a string.

console.log("666");
Copy the code

It is an error not to use quotation marks

// This is an error:
console.log(Yunmushuai B);Copy the code

Note that the quotation marks must be the same, mixing errors

console.log('xi xi ");Copy the code

normal

There can be different kinds of quotes inside quotes, such as single quotes inside double quotes:

// Double quotation marks use single quotation marks
console.log("You smile like a flower.");
// Use double quotation marks
console.log("You smile like a flower.");
Copy the code

If you want to use double quotation marks inside double quotation marks or single quotation marks inside single quotation marks

let b1 = "Cloud" "Pasture";
// Use \ to escape meaningful symbols into meaningless characters
Copy the code

Can make no sense literallynConvert to a meaningful line break

// Escape characters
alert("How can you \n \n be \n so cute?");
Copy the code

boolean

Boolean (logic) can have only two values: true or false.

let c = true; // true
let c = false //false
        
        
let d = 20 > 30;
console.log(d);//false
Copy the code

If JavaScript expects a location to be a Boolean, existing values at that location are automatically converted to Booleans.

Except the following six values are convertedfalse, all other values are treated astrue.

undefined
null
false
0
NaN
""or' 'or` `(Empty string)Copy the code
console.log(Boolean("0"));//true
console.log(Boolean(""));//true An empty string with Spaces is also true
console.log(Boolean("false"));//true
console.log(Boolean("null"));//true
console.log(Boolean(2 - 2));//false
Copy the code

Booleans are often used to control program flow

if (' ') {
  console.log('true');
}
// If is expected to be a Boolean value. JavaScript automatically converts an empty string to a Boolean value false
// Causes the program to not enter the code block, so there is no output.
Copy the code

Number

let a = 10;

let aa = 10 + 20;	// The expression is assigned to the aa variable
Copy the code
The integer

In JavaScript, integer literals of numbers can have three bases:

Base 10: Ordinary numbers are decimal

Base 8: If the literal number starting with 0, 0o, or 0o is octal, octal contains only the digits 0 to 7

Hexadecimal: If the number begins with 0x, 0x the literal value is hexadecimal. Hexadecimal integers can contain (0-9) and the letters A-f or a-f

binary

Binary values start with 0b, 0b

console.log(0b10) / / 2
console.log(0b1111) / / 15
Copy the code
octal
// Start with 0, is octal; It is displayed in decimal notation
console.log(017);  //15 //7 times 8 to the zero plus 1 times 8 to the first
console.log(0o17);   / / 15
console.log(0O17);   / / 15

console.log(044); //4 times 8 to the zero plus 4 times 8 to the first
console.log(010);    / / 8
console.log(0o36);  / / 30
console.log(0O36);  / / 30
Copy the code

Pay attention to

Octal can only contain numbers from 0 to 7. If this number is not valid, JS will automatically assume that you entered the wrong number and display it in decimal:

console.log(080);  / / 80
// Start with 0, which should be octal, but the following number is wrong, so it should be decimal
Copy the code

However, if the number starting with 0O or 0O is written incorrectly, the console will report an error!

// If the number is 0o, the following number is wrong, sorry, do not convert to 10, console error!
console.log(0o88);    / / an error
console.log(0O88);    / / an error

//// Console error syntax error
//Uncaught SyntaxError: Invalid or unexpected token
Copy the code
hexadecimal
// Hexadecimal:
console.log(0xff);    //255 f equals 15
console.log(0x2b);    / / 43
Copy the code

The console reports an error if it is followed by an incorrect notation

console.log(0x2g);
// The console reported a syntax error
//Uncaught SyntaxError: Invalid or unexpected token
Copy the code
Floating point Numbers

Inside JavaScript, all numbers are stored as 64-bit floating point numbers

A decimal or exponential.

In the computer world, decimals are called “floating point numbers”

Exponents are: you can use e to express the number of powers multiplied by 10

console.log(3.1415);
console.log(35.);  // 0.35 If the number of digits is 0, it can be omitted


console.log(5e5); / / 500000
console.log(5.2 e5);  / / 520000
console.log(1e-4);     / / 0.0001
Copy the code

Note:

Only decimal has decimal literals; octal and hexadecimal have no decimal literals. So there’s no base for decimals

Because floating point numbers are not exact values, comparisons and operations involving decimals need to be done with extreme care

console.log(0.1+0.2);
/ / 0.30000000000000004

console.log( (0.3-0.2) = = = (0.2-0.1));
// false
Copy the code
Infinity

Infinity means “Infinity” and is used to represent two scenarios

One is that a positive number is too large, or a negative number is too small to represent

The other way is if you divide by 0, you get Infinity.

/ / the scene
 console.log(Math.pow(2.1024)); // 2 to the 1024
// Infinity  
// The result of the expression is too large or too small to represent, so return Infinity


2 / / scene
 console.log(1/0);   // Infinity
// Instead of 0 divided by 0, Infinity is returned.
Copy the code

InfinityThere are pluses and minuses,InfinityFor positive infinity,-InfinityMinus infinity

console.log(Infinity= = = -Infinity); // false
console.log(1  / 0 );    // Infinity
console.log(-1  / 0 ); // -Infinity
console.log(-1  / -0 ); // Infinity
Copy the code

Because JavaScript does not report errors on positive overflow, negative underflow, and division by zero, pure math has little chance of throwing an error.

InfinityGreater than any value (exceptNaN),-InfinityLess than all values (exceptNaN).

console.log(Infinity > 88888);  // true
console.log(-Infinity < 88888); //true

//Infinity vs. NaN always returns false.
Copy the code
NaN

NaN is a special JavaScript value called not a number, meaning “not a number.”

This occurs when parsing a string to a number fails.

NaN is not equal to any value, including itself.

console.log(1 - 'the cloud ranch DSB'); // NaN

//0 divided by 0 also gives NaN.
console.log(0/0);// NaN
// Note that NaN is not a separate data type, but a special value whose data type is still Number
Copy the code
isFinite()

The isFinite method returns a Boolean value indicating whether a value is a normal value.

Return false if number is a NaN (non-number), or a number with positive or negative infinity.

console.log(isFinite(Infinity)); // false
console.log(isFinite(-Infinity)); // false
console.log(isFinite(NaN)); // false
console.log(isFinite(undefined)); // false


// All values except Infinity, -infinity, NaN, and undefined return false

//isFinite returns true for all other values.
console.log(isFinite(null)); // true
console.log(isFinite(Awesome!)); // true
Copy the code

Undefined

Undefined means the value is undefined

Undefined occurs when:

(1) If a variable is declared but not assigned, it is undefined.

I’m not going to talk about the next three

(2) When the function is called, the argument that should be provided is not provided, which is equal to undefined.

(3) The object has no assigned attribute. The value of this attribute is undefined.

(4) If the function does not return a value, undefined is returned by default.

let a;/ / undefined
        
console.log(address);// indicates that the variable is not assigned a value
let address = undefined; // Rarely used

// Define variables ahead of time, do not know the data type, assign values later.
Copy the code

Null

Null means empty, and unlike undefined,

Null indicates an empty object pointer, undefined

 let f = null;
 // Define a variable ahead of time to point to an empty memory address, knowing that the variable will store object data.

// When we need object destruction, array destruction, or delete event listeners, we usually set them to NULL.
box.onclick = null;
Copy the code

If a variable that needs to hold an object does not actually hold an object, it should explicitly hold a null value. This not only demonstrates the convention of null as a pointer to an empty object, but also helps to further distinguish null from undefined

Description:

Undefined is derived from null, so undefined == null returns true

Object Indicates the data type of an Object

Objects are the most complex data types and can be divided into three subtypes.

  • Object in a narrow sense
  • Array
  • Functions

Array an Array

An array is a set of values arranged in order. Each value position is numbered (starting at 0), and the entire array is represented by square brackets.

// Array is used to store a set of data, which is itself a complex type, containing any other type of data

let a = [ "Lin Daiyu" ,"YunMu" , "Xue Baochai" , 200 ,true]

console.log(a);
Copy the code

The values

console.log( "Subscript 1 data :" , a[1]);console.log("Length of array",  a.length );// Take the length of the array
Copy the code

To assign a value

a[0] = 100;// Reassign an item

console.log(a);
Copy the code

What if I put an extra comma in the middle and nothing in the middle

let b = [ "Lin Daiyu" , "YunMu"."Xue Baochai" , 200 ,true]

console.log( b );

console.log("Length of array", b.length );

console.log( "Subscript 2 data :" , b[2]);
// The array placeholder is empty, which is the data type of undefined
Copy the code

In addition to assigning at definition time, arrays can also be defined before they are assigned.

let arr = [];

arr[0] = 'a';
arr[1] = 'b';
arr[2] = 'c';
Copy the code
Nested values of an array

If the elements of an array are still arrays, you have a multidimensional array

	// Array --> array inside a nested array
        let a = [ 
            "Lin Daiyu"."YunMu"."Xue Baochai".200.true[Hulk."Iron Man"."Superman",]];console.log(a[5] [2]);/ / superman
Copy the code

Object data (narrow sense)

Core concepts of Js

Object is a set of key-value pairs, is a kind of unordered composite data set

  // Object --> A description of a thing

let lindaiyu = {
    name : "Lin Daiyu Xiaobiji".// Attribute name (key name): attribute value (key value)
    sex : "Female".age : 16 ,				
    weight : "50kg".height : "150cm".marry : false
};

console.log(lindaiyu);

 All attribute names of the /* object are strings, quoted or unquoted, unless they do not comply with the rules for identifiers, such as the first character being a number containing a space or the operator */

// Attribute values can be of any data type

// Each property name is called a property. If the value of a property name is a function, the property is called a method

// Attributes are separated by commas, and the last attribute can be added or not

// Attribute names cannot be the same attribute values can be the same

Copy the code

Object value

// The value is not obtained by serial number subscript
console.log(lindaiyu.name);
console.log(lindaiyu.age);


console.log(lindaiyu.a);// Return undefined when an object does not exist
Copy the code

Object to modify

lindaiyu.marry = true
console.log(lindaiyu.marry);
Copy the code

Add new properties

lindaiyu.hobby = "Dui people";
console.log(lindaiyu);
Attributes can be created and added dynamically without having to be specified at object declaration time
Copy the code

Object to delete

delete lindaiyu.age
console.log(lindaiyu);

// = Assignment cannot delete object attributes
lindaiyu.height = undefined;
lindaiyu.height = null;
console.log(lindaiyu);
Copy the code

Simple exercise

 let lindaiyu = {
            name : "Lin Daiyu Xiaobiji".sex : "Female".age : 16 ,
            weight : "50kg".height : "150cm".marry : false.husband : {
                name : "YunMu".age : 18.hobby : ["Sing" , "Reading" , "Flute"]}};console.log(lindaiyu.husband.hobby[2]);/ / flute
Copy the code

Built-in object, node object

Built-in objects (objects that JS defines for you in advance)

Node object (by the element to fetch)

console.log(window); // The built-in window object is read-only and mostly readable and writable
console.log(document);
console.log()
Copy the code

The function object

A function is a block of code that can be called again and again

Encapsulate a bunch of code and don’t execute it right away.

function fn() {
    console.log("Big");
    console.log("Home");
    console.log("Good");
}

// one of the ways to call a function (active call)
fn();
Copy the code

The typeof operator

Detects the data type of a variable or data

The number type

// The variables defined below are of type number
var a = 200;       
var b = -123;
var c = 123.456;
var d = .5e4;
var e = 0xf0;
var f = 016;
var g = Infinity;       
var h = NaN;

console.log(typeof a);
console.log(typeof b);
console.log(typeof c);
console.log(typeof d);
console.log(typeof e);      
console.log(typeof f);
console.log(typeof g);
console.log(typeof h);
Copy the code

All numbers in JS are of type number

Number stuff, all numbers (positive and negative, integer, size, base, etc.),Infinity, NaN, not subdivided into integers, int, float, all that crap.

String String type

var str1 = "Hello?";
var str2 = "250";   
var str3 = "";      // An empty string, also a string
console.log(typeof str1);
console.log(typeof str2);
console.log(typeof str3);
Copy the code

Boolean type

Boolean type (Boolean type). Boolean types have only two values true,false, that is, true or false

var bool = true;  
console.log(bool );
console.log(typeof bool);  // boolean

// Note: true, false are not quoted, so they are not strings
Copy the code

Undefined type

Let only one variable, no initial value, its default value is undefined;

Undefined is its own, and its type and value are undefined. There is only one value page of this type.

var un;   // I just defined it, no initial value is assigned, so it is undefined and the type is undefined
console.log(un);
console.log(typeof un);   // undefined
Copy the code
console.log(typeof null);// object
console.log(typeof []);// object
console.log(typeof {});// object
console.log(typeof window);// object A built-in object
Copy the code

Special:

Null When typeof detection is used, the data type is Object

Historical reasons. The first version of the JavaScript language in 1995,

Only five data types (object, integer, floating point, string, and Boolean) were designed, and NULL was not considered, just as a special value of Object.

Later, null became a separate data type, and for compatibility with previous code, typeof NULL returned object could not be changed.

 console.log(typeof null);// Object but null
// It is recommended to define an unknown object as null first
Copy the code
console.log(typeof function a(){}) // function
// function makes a better distinction between ordinary objects and function objects
Copy the code

Assignment and value

The assignment

let a = 10; // assign --> 10 to variable A
console.log(a);
Copy the code

The values

let b = a * 10;// Take the value of variable A and multiply it by 10 and assign it to variable b
console.log(b);
Copy the code

Values and assignments of array and object data

  • An array of
let arr = [10 , 20];
console.log(arr[0]); / / value
arr[0] = 100 / / assignment
console.log(arr);


let a = 10;
let b = a * 10;
let arr1 = [a , b]; // The value should be stored as data, but it is a variable, and the corresponding data should be found
console.log(arr1); 

/ /
let arr2 = ["a" , "b"]; // A and B are string data stored directly.
console.log(arr2);
Copy the code

If YOU write a directly into the array, but a is not defined

let arr = [a];
console.log(arr);
< span style = "max-width: 100%; clear: both; min-height: 1em; Undefined is a data type, not an error
Copy the code
  • object
let obj = {x : 66 , y : 99};
console.log(obj.x);/ / value

obj.x = 200;// reassign
console.log(obj);
Copy the code

In addition to the. Operation, an object can also be evaluated by []

Pay attention to

If square brackets are used, the attribute name must be enclosed in quotes, otherwise it will be treated as a variable

console.log(obj["x"]);
console.log(obj.x);

// If used. Operator x is a string
// x is the variable if the square bracket operator is used without quotes
Copy the code

Usage scenarios

Square brackets can replace the dot operator, but if you want to access nonconforming attribute names such as example values, you must use []

console["log"] ("If clouds were a letter in the sky");
Copy the code