I am small and live in Wuhan, do two years of new media, ready to use 6 months time to switch to the front end of the industry.

Lesson Objective for today

Yesterday, based on some page search, I learned the grammar and variables of ES basic concepts in chapter 3 of JavaScirpt Advanced Programming (3rd edition). Today, I mainly learn the basic data types of ES basic concepts in chapter 3 based on search. It is also a day for learning, come on, small and !!!!

The original plan was to use one article for the release, but the release kept prompting Request Entity Too Large, so it was released in two articles ~~~

The summary of today’s learning is in the first article, and the summary is in the second ~~~~


Today’s Lesson summary

A data type is defined in a data structure as a set of values and a set of operations defined on that set of values. Variables are places where values are stored. They have names and data types. The data type of a variable determines how the bits representing these values are stored in the computer’s memory. When declaring a variable, you can also specify its data type. All variables have data types to determine what kind of data can be stored.

The latest ECMAScript standard defines eight data types

  • Seven basic data types:
    • Undefined, like null, is a special keyword. Undefined denotes an undefined attribute of a variable.
    • Null, a special keyword that indicates a null value. JavaScript is case sensitive, sonullNull,NULLOr variants that are completely different.
    • Boolean, which has two values:truefalse.
    • A Number, an integer or a floating point Number, such as:42or3.14159.
    • Integers of arbitrary precision (BigInt) can safely store and manipulate large integers, even exceeding the safe integer limit for numbers.
    • A String is a sequence of characters representing a text value, such as “Howdy”.
    • Represents (Symbol) (a new type added in ECMAScript 6). An instance is a unique and immutable data type.
  • And objects.

Although these data types are relatively few, they allow you to develop useful functionality in your programs. Objects and functions are the other two basic elements of the language. You can think of an object as a named container for values, and then a function as a step your program can perform.


undefined

what

When a declared variable is not initialized, the default value of the variable is undefined, that is, the data type and content of the value are undefined.

function test(t) {
  if (t === undefined) {
     return 'Undefined value! ';
  }
  return t;
}

let x;

console.log(typeof x);
console.log(test(x));
Copy the code

Undefined is also an attribute of _ global object _. That is, it is a variable in the global scope. The most initial value undefined is primitive data types (undefined) (https://developer.mozilla.org/zh-CN/docs/Glossary/undefined).


attribute

Since the ECMAscript5 standard, undefined is a non-writable property which cannot be configured and works without a different browser. Even if it isn’t, avoid rewriting it

undefinedAttributes of attributes:
writable false
enumerable false
configurable false

example

Strictly equal and undefined








var x;
if (x === undefined) {
// Execute these statements
} else {
// These statements will not be executed
}
Copy the code

Note: we must use the strict equality operator (===) instead of the standard equality operator (==), because x == undefined checks if x is null, but strict equality does not.

Null is not the same as undefined. Move to the comparison operator to see details.


Typeof operator and undefined

Alternatively, you can use Typeof

var x;
if(typeof x === 'undefined') {
    // Execute these statements
}
Copy the code

Typeof is used because it does not throw an error if a variable is not declared.

If (typeof y === 'undefined') {// There is no error, Console. log("y is "+ typeof y) // y is undefined} if(y === undefined) {// ReferenceError: y is not defined }Copy the code

However, from a technical point of view such use should be avoided. JavaScript is a statically scoped language, so whether a variable is declared can be determined by seeing if it is declared in a closed context. The only exception is the global scope, but the global scope is bound to the global object, so checking whether a variable exists in the global context can be done by checking whether the property exists on the global object (for example, using the in operator).

if ('x' in window) {
  // only x is defined globally
}
Copy the code

The Void operator and undefined

The void operator is a third alternative.

var x;
if(x === void 0) {
    // Execute these statements
}
// do not declare y
if(y === void 0) {
    // Throws a RenferenceError (compared to 'typeof')
}
Copy the code

tip

However, a value of undefined is not the same as an undefined value, and the Typeof operator prints undefined for both undefined and undeclared variable data types.

    var oTemp;
    console.log(typeof oTemp);  / / output is undefined
    console.log(typeof oTemp2);  / / output is undefined
Copy the code





Notice that forUndeclared variablesUse in addition totypeofOther operators cause an error because the other operators can only be useddeclaredOn the variable of.

For example, the following code raises an error:

    var oTemp;
    console.log(oTemp2 == undefined);
Copy the code






A function returns a value when it does not explicitly return a valueundefined, as follows:

    function testFunc() {}
    console.log(testFunc() == undefined);  / / output "true"
Copy the code



Null

what

The value null indicates that the value of the object is not set. It is one of the basic JavaScript types and is known as falsy in Boolean operations. It has only one dedicated value, NULL, which is its literal. The value null is a literal, unlike undefined, which is not an attribute of a global object. Null is a missing identifier indicating that the variable does not point to any object.

It might be easier to think of NULL as an object that has not yet been created. In APIS, NULL is often used where the return type should be an object, but there is no associated value.

function getVowels(str) {
  const m = str.match(/[aeiou]/gi);
  if (m === null) {
    return 0;
  }
  return m.length;
}

console.log(getVowels('sky'));
// expected output: 0

Copy the code







example

You can also empty a variable by setting its value to NULL.

    var temp ="";
    console.log(typeof temp);//string
    temp=null;
    console.log(typeof temp);//object
Copy the code

tip

The value undefined is actually derived from the value null, so ECMAScript defines them to be equal as long as type-conversion matches are performed.

    console.log(null= =undefined);  / / output "true"
Copy the code

Although the two values are equal in this case, they have different meanings ~~~~~

  • undefinedIs the value assigned to a variable when it is declared but not initialized
  • nullIs used to representDoes not yet existObject, which was briefly introduced when we discussed typeof operators.








typeof null        // "object" (for some old reason instead of 'null')
typeof undefined   // "undefined"
null= = =undefined // false
null= =undefined // true
null= = =null // true
null= =null // true
!null //true
isNaN(1 + null) // false
isNaN(1 + undefined) // true
Copy the code

If a function or method returns an object, then null is usually returned if the object cannot be found.

    console.log(typeof null)// "object"
    console.log(typeof {})// "object"
Copy the code









Boolean

what

Boolean types are one of the most commonly used types in ECMAScript. It has two values true and false (that is, two Boolean literals). Even if false does not equal 0,0 can be converted to false if necessary, so it is safe to use both in Boolean statements.

    var temp = true;
    console.log(typeof temp);//boolean
    temp = !0;
    console.log(typeof temp)//boolean
    console.log(temp)//true
Copy the code

attribute


Boolean.prototypeAttributes of attributes:
writable false
enumerable false
configurable false

grammar

Boolean literals

Any Number entered directly (rather than accessed from another variable) is treated as a literal of type Number. For example, the following code declares a variable that holds integer values defined by the literal 86:

    var temp = 86;
    console.log(typeof temp);//number
    console.log(temp);/ / 86
Copy the code

The Boolean object

  • Syntax for creating Boolean objects
new Boolean([value])
Copy the code
  • parameter

Optional, used to initialize the value of a Boolean object.

  • The return value

If the first argument is not a Boolean, it is converted to a Boolean. If this parameter is omitted, or its value is 0, -0, NULL, false, NaN, undefined, or an empty string (“”), the generated Boolean object has the value false. If the argument passed is a DOM object document.all, a Boolean object with a value of false is also generated. Any other value, including a string with the value “false” and any object, creates a Boolean object with the value true. Be careful not to confuse the Boolean values true and false in primitive types with Boolean objects with values true and false.

  • Boolean Object properties
attribute describe
constructor Returns the function that created the instance prototype. The default isBooleanFunction.
length lengthProperty with a value of 1.

example

Create a Boolean object with a value of false


var bNoParam = new Boolean(a);var bZero = new Boolean(0);
var bNull = new Boolean(null);
var bEmptyString = new Boolean(' ');
var bfalse = new Boolean(false);
Copy the code

Create a Boolean object with a value of true


var btrue = new Boolean(true);
var btrueString = new Boolean('true');
var bfalseString = new Boolean('false');
var bSuLin = new Boolean('Su Lin');
var bArrayProto = new Boolean([]);
var bObjProto = new Boolean({});
Copy the code

tip

Any object that is not undefined and null, including Boolean objects with a value of false, is treated as true when used directly in conditional statements.

For example, the condition in the following if statement is true:

var x = new Boolean(false);
if (x) {
  // The code here will be executed} Boolean values of primitive types are not affected by this rule. For example:ifStatement condition false:var x = false;
if (x) {
  // The code here will not execute
}
Copy the code

Instead of converting a non-boolean to a Boolean by creating a Boolean object, use Boolean as a conversion function, or use double non-(!!). Operator:

var x = Boolean(expression);     / / recommend
varx = !! (expression);/ / recommend
var x = new Boolean(expression); / / not so good
Copy the code

For any object, even a Boolean object with a value of false, when passed to a Boolean function, the generated Boolean object will have a value of true.

var myFalse = new Boolean(false);   // false
var g = new Boolean(myFalse);       // true
var myString = new String("Hello");
var s = new Boolean(myString);      // true
Copy the code

Finally, do not use Boolean objects where you should use booleans of primitive types.


Number

what

JavaScript’s Number object is an encapsulated object that lets you manipulate numeric values. The Number object is created by the Number() constructor. JavaScript’s Number type is a double precision IEEE 754 64-bit floating-point type. But it can represent both 32-bit integers and 64-bit floating-point numbers.

Recently out stage3BigInt arbitrary precision numeric type, has entered stagE3 specification.


attribute


Number.prototypeAttributes of attributes:
writable false
enumerable false
configurable false

grammar

Numeric literal

Any Number entered directly (rather than accessed from another variable) is treated as a literal of type Number. For example, the following code declares a variable that holds integer values defined by the literal 86:

    var temp = 86;
    console.log(typeof temp);//number
    console.log(temp);/ / 86
Copy the code

Octal and hexadecimal numbers

Integers can also be represented as octal (base 8) or hexadecimal (base 16) literals. Although all integers can be expressed as octal or hexadecimal literals, all mathematical operations return decimal results. Octal literals must start with 0 and can be followed by any octal digit (0-7), as shown in the following code:

    var temp = 070;
    console.log(typeof temp);//number
    console.log(temp);// Print out 56 in decimal
Copy the code

To create A hexadecimal literal, the first digit must be 0, followed by the letter X (case insensitive), and then any hexadecimal digit (0 to 9 and A to F). These letters can be uppercase or lowercase. Such as:

    var temp = 0x1f;
    console.log(temp);// Print out 31 in decimal
    temp = 0xAB;
    console.log(temp);// Print out 171 in decimal
Copy the code

Floating point Numbers

To define a floating point value, you must include the decimal point and one digit after the decimal point (for example, use 1.0 instead of 1). This is referred to as a floating-point number dimension. Such as:

    var temp = 5.0;
    console.log(temp);// Display the integer 5
    temp = 5.5;
    console.log(temp);// Displays the floating point 5.5
    temp = 5.5+"";
    console.log(typeof temp);//string
Copy the code

The interesting thing about floating-point literals is that they are actually stored as strings before being evaluated.

Scientific enumeration

Floating-point numbers can be expressed in scientific notation for very large or very small numbers, where a number can be expressed as a number (including decimal numbers) plus e (or E), followed by a multiple of 10. For minimal-value floating points, you can either cut the specified number to the number by toFixed(number), or round a number to the nearest integer using the math.round () method, but for positive integers, Use toPrecision(Number) to truncate the entire number to the specified number length.

    var temp = 5.618 e7;
    console.log(temp);
    // Display the integer 56180000 5.618 x 10^7
    temp = 8e-17;
    console.log(temp);//8e-17

    temp = 0.000000000000000000000000000001245893576484897879;
    console.log(temp);/ / 1.2458935764848978 e-30
    // Please note that only 16 decimal places are displayed after the decimal point
    console.log(temp.toFixed(2));/ / 0.00
    console.log(temp.toPrecision(2));/ / 1.2 e-30
    console.log(Math.round(temp));/ / 0

    temp = 124589357648489787900000000000000000000000000000;
    console.log(temp);/ / 1.245893576484898 e+47
    // Please note that only 15 decimal places are displayed after the decimal point
    console.log(temp.toFixed(2));/ / 1.245893576484898 e+47
    console.log(temp.toPrecision(2));/ / 1.2 e+47
    console.log(Math.round(temp));/ / 1.245893576484898 e+47
Copy the code

ECMAScript converts floating point numbers with six or more leading zeros into scientific notation by default. Floating point values can also be stored in 64-bit form based on the IEEE 754 standard, which means that a decimal value can have up to 17 decimal bits. Values after 17 bits will be trimmed, resulting in a small mathematical error.

IEEE 754 Standard is the Standard number [1] of the IEEE Standard for Floating-point Arithmetic, which is equivalent to the international Standard ISO/IEC/IEEE 60559. The standard is issued by the Microprocessor Standards Committee (MSC) of the IEEE computer Society.

The standard defines formats for representing floating-point numbers (including negative zero-0 and denormal number), special values (Inf and NaN), and "floating-point operators" for these numbers. It also specifies four numerical modification rules and five exceptions (including when exceptions occur and how exceptions are handled). The full name of the standard is IEEE Binary Floating point Arithmetic Standard (ANSI/IEEE Std 754-1985), also known as IEC 60559:1989. Binary floating-point arithmetic for microprocessor systems (originally numbered IEC 559:1989).

Later, there was the IEEE 854-1987 standard for "floating-point numbers independent of cardinality", which specified cardinality 2 and 10. Now the latest standard is "IEEE 854-2008 standard".

Copy the code

The IEEE 754 standard specifies the exchange, arithmetic format, and methods of self-stating floating-point numbers in binary and decimal systems in computer programming environments.


The special Number value

Several special values are also defined as type Number. The first two are number. MAX_VALUE and number.min_value, which define the outer bounds of the set of Number values. All ECMAScript numbers must be between these two values. However, the resulting numerical result may not fall between these two values. When the Number generated by the calculation is greater than number.max_value, it is given the value number.positive_infinity, meaning that there are no more numeric values. Similarly, calculations that generate a value less than number.min_value will also be given the value number.negative_infinity, which means no more numeric values. If the calculation returns an infinite value, the resulting result cannot be used in other calculations. In fact, there is a special value for Infinity, which is (as you guessed) Infinity. POSITIVE_INFINITY is Infinity. The value of number. NEGATIVE_INFINITY is -infinity. Since infinitely large numbers can be positive or negative, there is one way to determine whether a number is finite (rather than testing each infinite number individually). The isFinite() method can be called on any number to ensure that it is not infinite. For numbers, you can call number.isINTEGER () to verify that the data is an integer.

var temp = Number.POSITIVE_INFINITY;
console.log(isFinite(temp));//false
var temp = 5;
console.log(isFinite(temp));//true
console.log(Number.isInteger("0.55"))//false
Copy the code

The last special value is NaN, which means Not a Number. NaN is a strange special value. In general, this happens when a conversion to a type (String, Boolean, and so on) fails. For example, converting the word blue to a numeric value will fail because there is no numeric equivalent. NaN, like infinity, cannot be used in arithmetic calculations. Another peculiar thing about NaN is that it is not equal to itself.

    var temp =  NaN;
    console.log(NaN == temp);  / / output is "false"
    // For this reason, NaN values themselves are not recommended. The isNaN() function will do fairly well
    temp =  NaN;
    console.log(isNaN(temp));  / / output "true"
    temp =  Awesome!;
    console.log(isNaN(temp));  / / output is "false"
Copy the code



Number object

new Number(value); 
var a = new Number('123'); // a === 123 is false
var b = Number('123'); // b === 123 is true
a instanceof Number; // is true
b instanceof Number; // is false
Copy the code

The Number object is a wrapper object for the original value.

  • Syntax for creating a Number object:
var temp=new Number("a");
console.log(temp);
/* Number {[[PrimitiveValue]]: NaN} __proto__:Number constructor:ƒ Number() toFixed:ƒ toFixed( ƒ toLocaleString() toPrecision() toString:ƒ toString() valueOf:ƒ valueOf() __proto__:Object [[PrimitiveValue]]:0 [[PrimitiveValue]]:NaN */
var tmp=Number("b");
console.log(tmp);//NaN
tmp=Number("");
console.log(tmp);/ / 0
Copy the code
  • parameter

The value argument is the value of the Number object to be created or converted to a Number.

  • The return value

When Number() is used as a constructor with the operator new, it returns a newly created Number object. If you call Number() as a function without the new operator, it converts its argument to a raw value and returns that value (or NaN if the conversion fails).

  • Number object properties
attribute describe
constructor Returns the constructor that created the instance object. The default isNumberObject.
prototype Additional attributes allowed on the Number object.
EPSILON The minimum interval between two representable numbers.
MAX_SAFE_INTEGER The largest safe integer in JavaScript (2-1).
MAX_VALUE The largest positive number that can be represented. The smallest negative number is zero-MAX_VALUE.
MIN_SAFE_INTEGER The smallest safe integer in JavaScript (1) - (2 -).
MIN_VALUE The smallest positive number that can be represented is the closest positive number to 0 (it doesn’t actually become 0). The largest negative number is zero-MIN_VALUE.
NaN Special “non-numeric” values.
NEGATIVE_INFINITY A special negative infinity value that is returned when overflow occurs.
POSITIVE_INFINITY Special positive infinity value that is returned when overflow occurs.
  • Number object method
methods describe
isNaN() Determine if the value passed is a NaN.
isFinite() Determines the type of value passed and whether it is itself a finite number.
isInteger() Make sure the value type passed is “number” and is an integer.
isSafeInteger() Determines whether the value passed is a safe integer (-1) (2 - 至 Between 2-1).
parseFloat() And global objectsparseFloat()The same.
parseInt() And global objectsparseInt()The same.
toString Converts a number to a string, using the specified cardinality.
toLocaleString Converts numbers to strings, using native number format order.
toFixed Converts a number to a string with the specified number of digits behind the decimal point.
toExponential Converts the value of an object to an exponential notation.
toPrecision Formats a number to the specified length.
valueOf Returns the base numeric value of a Number object.

example

Assign a value to a Number variable using the Number object

The following example uses the attributes of the Number object to assign values to several numeric variables:

var biggestNum = Number.MAX_VALUE;
var smallestNum = Number.MIN_VALUE;
var infiniteNum = Number.POSITIVE_INFINITY;
var negInfiniteNum = Number.NEGATIVE_INFINITY;
var notANum = Number.NaN;
Copy the code

The range of integer types

The range of integers that JavaScript can accurately represent is between -2^53 and 2^53 (excluding the two endpoints), beyond which the integer cannot be accurately represented. (See ECMAScript Standard, Chapter 6.1.6 The Number Type for details):

var biggestInt = Number.MAX_SAFE_INTEGER; 
/ / 9007199254740991
var smallestInt = Number.MIN_SAFE_INTEGER; 
/ / - 9007199254740991
Copy the code

When parsing serialized JSON, integer values outside this range can be corrupted if the JSON parser casts them to type Number. Using strings instead at work is a possible solution.


Convert a Date object using Number

The following example uses Number as a function to convert a Date object to a numeric value

var d = new Date("December 17, 1995 03:24:00");
console.log(Number(d));
Copy the code

This will output “819199440000”.


Converts a numeric string to a number


Number('123')     / / 123
Number('12.3')    / / 12.3
Number('12.00')   / / 12
Number('123e-1')  / / 12.3
Number(' ')        / / 0
Number(null)      / / 0
Number('0x11')    / / 17
Number('0b11')    / / 3
Number('0o11')    / / 9
Number('foo')     // NaN
Number('100a')    // NaN
Number('-Infinity') //-Infinity
Copy the code








This article is formatted using MDNICE