JavaScript basics finishing (continuously updated)

1. Chapter 1 What is JavaScript

1.1 JavaScript function and composition

JavaScript is a scripting language that runs on the client side. In the early days of browsers, to validate a form, a round-trip communication was required with the server. With the increasing popularity of the web, web pages became more and more complex, and the emergence of JavaScript solved this problem, but also has many functions and functions.

  • Web page special effects (listen to some behaviors of users and let the web page make corresponding feedback)
  • Form validation (judging the legitimacy of form data)
  • Data interaction (get the data in the background, render it to the front end)
  • Server-side programming (node.js)

The composition of JavaScript is as follows:

1.2 JavaScript and HTML

A JavaScript program cannot run on its own, it needs to be embedded in HTML before the browser can execute the JavaScript code. Introduce JavaScript code into HTML through script tags.

1.2.1 Outlining JavaScript


<script src="external js file path"></script>

1.2.2 Inline JavaScript

Just put the code block directly in the script tag

       function say(){

1.2.3 script attribute

  • defer attribute

    This attribute indicates that the execution of the script will not change the structure of the page, which means that the script will be delayed until the entire page is loaded before execution (immediate download, delayed execution)

  • async property

    The purpose of adding this attribute is to tell the browser that it does not have to wait until the script is downloaded and executed before loading the page, and it does not have to wait until the asynchronous script is downloaded and executed before downloading and executing another script.

2. Chapter 2 The Language Basics of JavaScript

2.1 Syntax

2.1.1 Case sensitivity

typeof cannot be used as a function name, but Typeof can.

2.1.2 Identifiers

Identifiers use camel case, and the first character must consist of a letter, underscore, symbol No open head , leftover Down That he Character symbol Can by Yes Character mother , number Character , Down Draw Wire , The beginning of the symbol, the remaining other characters can be letters, numbers, underscores, At the beginning of the symbol, the rest of the characters can be letters, numbers, underscores, symbols.

Note: keywords, reserved words, true,false,null cannot be used as an identifier

2.2 Keywords and reserved words

2.2.1 Keywords

Keywords: Refers to words that have been used by JS itself, and can no longer be used as variable names and method names.

Including: break, case, catch, continue, default, delete, do, else, finally, for, function, if, in, instanceof, new, return, switch, this, throw, try, typeof, var, void, while, with etc.

2.2.2 Reserved words

Reserved words: In fact, they are reserved "keywords", which means that although they are not keywords now, they may become keywords in the future, and they cannot be used as variable names or method names.

Including: boolean, byte, char, class, const, debugger, double, enum, export, extends, fimal, float, goto, implements, import, int, interface, long, native, package, private, protected, public, short, static, super, synchronized, throws, transient, volatile, etc.

2.3 Variables

2.3.1 var keyword

var declares function scope or global.

function func() {
    if (true) {
        var str = 'hello world';
func() //output hello world
console(str)  //error

The declaration of function scope means that variables declared after exiting the function will also be destroyed

function func() {
    if (true) {
        str = 'hello world';
func() //output hello world
console(str)  //output hello world

Omitting the var keyword can define a global variable, and variables inside the function can also be accessed outside the function, but this is not recommended.

function func() {
    if (true) {
        str = 'hello world';
func() //output undefine d

The output of undefine d instead of an error is because variables declared with the var keyword can be pulled to the top of the function scope. The above code is equivalent to:

function func() {
    if (true) {
        var str;
        str = 'hello world';
func() //output undefine d

2.3.2 let keyword

  • let is block scoped.
function func() {
    if (true) {
        var str
        str = 'hello world';
    console(str) //output 'hello world'
function func() {
    if (true) {
        let str
        str = 'hello world';
    console(str) //Error, str is not defined

The let declaration only works at the block level, and the same variable name cannot appear in the same code block. The biggest difference from var is that let will not be promoted, and a temporary dead zone will occur if it is used without a declaration.

function func() {
    if (true) {
        console.log(str);  //error, str is undefined
        str = 'hello world';
func() //error, str is undefined
  • global declaration of let

Unlike the var keyword, variables declared in the global scope using let do not become properties of the window object.

var name = 'matt'
console(  // 'matt'

let name = 'matt'
console(  // undefine

However, the let declaration still occurs in the global scope, and the corresponding variable will persist in the life cycle of the page. In order to avoid errors, it is necessary to ensure that the same variable is not repeatedly declared in the page.

  • let statement in a for loop

Before let appears, the iteration variable of the for loop will seep into the body of the loop

for(var i = 0; i<5; ++i){
//loop logic
console(i); //5

for(let i = 0; i<5; ++i){
//loop logic
console(i); //Error, i is not defined
var msg = ["This", "is", "a", "test"];
for (var i = 0; i < msg.length; i++) {
    setTimeout(function() {
        console.log("index:" + i + ",msg:" + msg[i]);
    }, 0);

  setTimeout is executed asynchronously
  JavaScript is single-threaded, encounters setTimeout Will open another thread later
  implement setTimeout When the code in the synchronous code for The loop has been executed
  At this time, the iteration variable holds the value that caused the loop to exit: 4, which is executed after setTimeout When code, all i are all the same variable (4).
var msg = ["This", "is", "a", "test"];
for (let i = 0; i < msg.length; i++) {
    setTimeout(function() {
        console.log("index:" + i + ",msg:" + msg[i]);
    }, 0);
use let When declaring the iteration variable, JavaScript Behind the scenes the engine declares a new iteration variable for each iteration loop. each setTimeout All references are to different variable instances.
let declared variables, only in let It is valid in the code block where the command is located, and there is a temporary dead zone constraint
 Temporary dead zone: as long as it exists in block-level scope let command, the variables it declares are "bound" ( binding)This area is no longer subject to external influences

2.3.3 const keyword

const is basically the same as let, the only important difference is that the variable must be initialized at the same time as it is used to declare the variable, and trying to modify the variable declared by const will cause a runtime error. Const also does not allow repeated declarations, and the scope is also a block-level scope, but const will not be used to declare iteration variables, such as for loops.

const age = 18;
age = 20;   // Report an error, assign a value to a constant

//But const declares an object, and it is allowed to modify the internal properties of the object
const person = {} = 'Matter'  // this is allowed

2.4 Data Types

In ES5, the basic data types we know are: number, string, boolean, undefine d, null, object

Later, ES6 introduced a new type Symbol. Objects of this type are never equal, that is, the same value is passed in when they are created, which can solve the problem of attribute name conflict as a marker.

There is also a bigInt in Google version 67. Refers to safe storage and manipulation of large integers. (But many people don't consider this as a type).

How many JS data types are there?

8 kind. Number,Boolean,String,Null,Undefind,Object,Symbol,bigint

JS data types: What types are included in Object?

  which contains Data,function,Array Wait. These three are commonly used.

JS data types: What are the basic types and reference types of JS?

Basic type (single type): except Object.  String,Number,boolean,null,undefined. 

Reference type: object. contained in function,Array,Date. 

2.4.1 typeof operator

The values ​​returned by typeof are:

  • "undefine d" is not defined
  • "boolean" boolean
  • "string" string
  • "number" means a number
  • "object" means the value is an object or null
  • "function" means the value is a function
  • "symbol" means the value is a symbol

2.4.2 undefine d type

There is only one value of undefined, which is undefined. When a variable is declared with var or let without initialization, the variable is assigned undefine d by default.

2.4.3 Null type

The null value represents a null object pointer, which is also to pass a null to typeof, which will return "object".

undefined is derived from null, and Null has only one value, which is null. object that does not exist. Undefined has only one value, which is undefined. Not initialized.

The simple understanding is: undefined is not defined, null is defined but empty.

2.4.4 Boolean type

The most used type has two literal values, true and false. true is not necessarily equal to 1, and false is not necessarily equal to 0. Literals of type boolean are case-sensitive. True and False are identifiers

2.4.5 Number Type

​ Numeric types, representing integers and floating-point numbers of data. Also called a "double value" in some languages.

​ var intNum = 55; decimal

​ var num = 012; octal

​ var octalNum = 0x23; hexadecimal

  • floating point number

To define a floating-point number, the value must contain a decimal point, a number after the decimal point, and a number before the decimal point, because the memory space used to store a floating-point number is twice as much as an integer, and there is no number after the decimal point or 0 after the decimal point It will be automatically converted to an integer. At the same time, for very large or very small values, scientific notation can be used.

let floatNum1 = 1.1;
let floatNum1 = 0.1;
let floatNum1 = .1; //Effective but not recommended

let floatNum1 = 1.
let floatNum1 = 1.0
//are treated as integers

let floatNumb1 = 3.125e7 //equal to 31250000
  • NaN

NaN means not a number, and is used to indicate that the operation to return a number failed, rather than throwing an error. For example, dividing 0 by any number usually causes an error in other languages, but not in JS.

NaN has several characteristics used as follows, the isNaN() function is used to determine whether the parameter is "not a value"

console.log(NaN == NaN)  //false
console.log(isNaN(NaN))  //true
console.log(isNaN(10))   //false
console.log(isNaN("10"))  //false, can be converted to the value 10
console.log(isNaN("bulsu"))  //true
console.log(isNaN(true))  //false can be converted to the value 1
  • Numeric conversion

There are three main functions for converting non-numeric values ​​to numeric values: Number(), parseInt(), and parseFloat().

The Number() function performs the conversion based on the following rules:

  • Boolean value, true is converted to 1, false is converted to 0
  • value, return directly
  • null, returns 0
  • undefined, returns NaN
  • Strings, numeric strings are converted to numeric values, empty strings are converted to 0, others return NaN
  • object, calling the valueof() function
let num1 = Number("Hellow world!")  //NaN
let num1 = Number("")  //0
let num1 = Number("0000111")  //111
let num1 = Number("true")  //1

The conversion rules of parseInt() and parseFloat() are similar, and they are converted from position 0.

let num = parseInt("1234blue")  //1234
let num = parseFloat("12.34blue")  //12.34
let num = parseInt("")   //NaN
let num = parseInt("0xA")  //10, interpreted as a hexadecimal number
let num = parseInt(12.5)  //12
let num = parseFloat(12.5)  //12.5
let num = parseInt("2")  //2

2.4.6 String type

​ Strings can be represented by single quotes, double quotes, and backticks. Strings are immutable, once created, the value cannot be changed To change the string held by a variable, first destroy the original string and then fill the variable with another contained string.

  • character conversion

1. **.toString()** method: Note that null and undefined cannot be converted, and the toString() method generally does not receive any parameters

//Convert to string --> toString method
var bool=true;
//Note that toString cannot be converted to null and undefined.

2. **String()** method: can be converted

console.log(String(null));  //null
console.log(String(undefined));  //undefined

2.4.7 Symbol type

Objects of type Symbol are never equal, even when created with the same value. Therefore, the problem of resolving attribute name conflicts (how many encodings are applicable) can be used as a marker.

2.4.8 Object type

An object in ECMAjavascript is actually a collection of data and functions. Objects can be created by executing the new operator followed by the name of the object type to be created. Create an instance of the object type and add properties (or) methods to it, you can customize the creation of objects.

Such as: var o = new Object( );

Each instance of object has the following properties and methods:

  • constructor: holds the function used to create the current object. (Constructor) constructor is object();
  • hasOwnProperty(propertyName): Used to check whether the given current property exists in the current object instance (rather than in the instance prototype). Among them, the property name (propertyName) as a parameter must be specified in the form of a literal string (for example: o.hasOwnProperty("name")).
  • isPrototypeOf(object): Used to check whether the incoming object is the incoming object prototype.
  • propertyIsEnumerable(propertyName): Used to check whether a given property can be used with a for-in statement. As with the hasOwnProperty() method, the property name as a parameter must be specified as a string.
  • toLocaleString( ): Returns a string representation of the object that corresponds to the locale of the execution environment.
  • toString( ): Returns the string representation of the object.
  • valueOf( ): Returns the string, numeric or boolean representation of the object. Usually the same as the return value of the toString( ) method.

object in ECMAJS is the basis of all objects, so all objects have these basic properties and methods.

Tags: Javascript Front-end programming language

Posted by ginginca on Sun, 10 Jul 2022 19:56:37 +0530