preface

To do a good job, he must sharpen his tools.

Hello everyone, I am dragon ha ha. A Java, JavaScript amphibian. In this article, the first in a series of FuckingJavaScript articles, we’ll review data types.

JavaScript is a hybrid of weakly typed or dynamic language, functional programming and object-oriented programming. The developer does not have to declare the type of the variable in advance. The type will be determined automatically during the execution of the program. The same variable can hold different types of data.

var foo = 42;    // foo is a Number now
foo = "bar"; // foo is a String now
foo = true;  // foo is a Boolean now
Copy the code

The data type

The latest ECMAScript standard defines nine data types, including primitive and complex data types.

Primitive data type

  • String
  • Boolean
  • Number
  • Undefined
  • Symbol
  • Bigint

String

A string type used to represent text data. JavaScript strings are immutable. This means that once a string is created, it cannot be modified. However, new strings can be created based on operations on the original string.

  • String interceptionString.substr()
  • String splicingString.concat()

Boolean

Boolean with only two values, true and false, used to represent logical truth and falsehood.

Number

MAX_VALUE and MIN_VALUE, which are automatically converted to special values Infinity and NaN(non-numeric, not-a-number).

Undefined

There is only one value undefined. In JavaScript, a variable that has not been assigned a value will have the default value undefined.

Symbol

The symbol type is a new primitive data type defined in ES6. The symbol type is unique and cannot be modified. It cannot be enumerated.

  • As aObjecttheThe key attributesThe same attribute is guaranteed to never appear, preventing attribute contamination
  • simulationclassthePrivate property, control variable read and write
const garen = Symbol(a);// Galen tag
const jarvanIV = Symbol(a);// Mark of Gavin IV
// The demasic class
class demacia {
  constructor(){
    this[garen] = 'Garen';
    this[jarvanIV] = 'JarvanIV';
  }
  getGaren(){
    return this[garen];
  }
  setGaren(value){
    this[garen] = value;
  }
  getJarvanIV(){
    return this[jarvanIV];
  }
  setJarvanIV(value){
    this[jarvanIV] = value; }}Copy the code

Bigint

BigInt can safely store and manipulate large integers, even exceeding the safe integer limit for numbers.

Complex data types

  • Null
  • Object
  • Function

Null

The Null type has only one value, Null, and typeof Null is object.

Object

Almost all Object types that can be created using the new Keyword are Object types, such as new Array(), new Date(), new Map(), new Set(), new WeekMap(), new WeekSet(), and so on.

Function

Function is a special Obejct, the prototype Object of Function and prototype __proto__ points to Object.

Array

Array types. The methods commonly used to represent arrays of list data can be summarized into three categories

  • Changes the value of the object that calls them,pop,push,reverse,spliceEtc.
  • It doesn’t change the value of the object that called them, it just returns a new array,concat.slice.joinEtc.
  • Do not perform any operations on the original array during the traversal, otherwise the result of the traversal may be affected.foEach.entries.every.some.filter.findEtc.

The specific use of different methods is not explained here.

MDN Array Array

Date

Date type, based on Unix Time, the number of milliseconds since January 1, 1970 (UTC).

Set, WeakSet, Map, WeakMap

  • Map: key-value pairs and the ability to remember the original insertion order of the keys. Any value can be a key or a value
  • WeakMap: The key must be an object, and the value can be arbitrary and not enumerable. The object to which the key name points is a weak reference and not counted in the garbage collection mechanism
  • Set: A collection of arbitrary values whose elements you can iterate over in the order in which they are inserted. Elements in a Set occur only once, that is, the elements in a Set are unique.
  • WeakSet: A collection of object values, which are not enumerable. Objects are weak references and are not included in the garbage collection mechanism

Storage of different data types

The JavaScript stack is slightly different from Java

  • Stack: Local variables of primitive type, references to objects
  • Heap: Global variables of primitive types, variables in closure scenarios, object type data

Explanation: The variable B of the original type of the closure function shown in the figure below still exists in the [[Scopes]] object

var a = 1;
var f1 = function() {
  var b = 2;
  return function(){ console.log(b) }
}
console.dir(f1())
Copy the code

Type judgment

typeof

Detects the type of a variable

typeof '1' // string

typeof 1 // number

typeof 1n // bigint

typeof false // boolean

typeof undefined // undefined

typeof null // object

typeof [] // object

typeof new Date(a)// object

typeof function(){} // function

typeof Date // function

typeof Array // function
Copy the code

The value of typeof NULL is Object

It’s a historical Bug, brought up in the womb

In JavacSript, the first three bits of a binary are all zeros, so the first three bits of a binary are all zeros, so the first three bits of a binary are all zeros. XXX === null is recommended. For complex data, the type of the function is function and the type of the object is object

instanceof

Returns true/false to determine the object type by checking whether the constructor’s prototype appears on the prototype chain of the instance object.

How do I implement Instanceof manually

Instanceof can correctly determine the type of an object by determining whether the corresponding type can be found in the prototype chain of the object.

function instanceof(left, right) {
  / / prototype
  let proto = left.__proto__;
  // Find the corresponding prototype object layer by layer
  while(proto) {
    if (proto === right.prototype) {
      return true;
    }
    proto = proto.__proto__
  }
  return false;
}
Copy the code

Object.prototype.toString

Personally, recommend the judgment of the type of method is the Object. The prototype. ToString, can complete the judgment of the types of data, need to match the call or use the apply

Object.prototype.toString.call('1') // [object String]

Object.prototype.toString.call(1) // [object Number]

Object.prototype.toString.call(1n) // [object BigInt]

Object.prototype.toString.call(false) // [object Boolean]

Object.prototype.toString.call(undefined) // [object Undefined]

Object.prototype.toString.call(null) // [object Null]

Object.prototype.toString.call({}) // [object Object]

Object.prototype.toString.call([]) // [object Array]

Object.prototype.toString.call(new Date()) // [object Date]
Copy the code

The type in the return value [object {type}] is the type of the variable

Type conversion

  • Casts.
  • Implicit conversion

Casts.

Type conversion via String(), Number(), Boolean(), etc

Implicit conversion

In type conversions, the way the compiler automatically converts, usually through an operator

  • Arithmetic operator+.-.*.present.%Etc.
  • = =.! =
  • Conditions of operationif( ).else if( )Etc.

Arithmetic operator

  • string+Numbers, numbers are converted to strings
  • digital-String, string is converted to a number. ifStrings are not pure numbersWill be converted toNaN. Same thing with strings and numbers. Strings – Strings are also converted to numbers first
  • +.*.present.%.>.<-The same is true for conversion of

= =,! =

Automatic type conversion first, then comparison

  • When a string is compared with a number, the string is converted to a number and then compared
  • Strings and bulby are converted to numbers and then compared
  • When a number is compared to a Boolean, the Boolean is converted to a number and then compared

Conditions of operation

Convert conditional data or expressions to Boolean

Conversion example

Turn Number

  • trueTo 1,false0
  • nullIs zero,undefinedNaN.symbolAn error
  • String looks at the content, if it is a number or a base value, normal, otherwiseNaN
Number(true) / / 1
Number(false) / / 0
Number(null) / / 0
Number(undefined) // NaN
Number(Symbol('1')) // Uncaught TypeError: Cannot convert a Symbol value to a number at Number
Number('1')  / / 1
Number('1a') // NaN
parseInt('1') / / 1
parseInt('1.23 abc') / / 1
parseFloat('1.1') / / 1.2
parseFloat('1.1 abc') / / 1.1
+'1'  / / 1
Copy the code

Turn the String

String(1) / / '1'
1.toString() / / '1'
1.234.toFixed('2') / / '1.23'
Copy the code

Turns a Boolean

  • undefined,null,false,0,0,NaN,An empty stringtofalse
  • All other values are convertedtrue
Boolean(undefined) // false
Boolean(null) // false
Boolean(0) // false
Boolean(' ') // false
Boolean('0') // true
Boolean(NaN) // false
Boolean({ a: null }) // `true`
Copy the code

Equality judgment

  • Non-strict equality comparison (= =)
  • Strict equality comparison (= = =)
  • The Object is (args1 args2)

The difference between

  • = =After the type conversion is performed, the values are compared
  • = = =Do the same comparison without casting (always return false if the type is different)
  • Object.is= = =Similar treatment, but yeahNaN,0,0For special treatment,The Object is (NaN NaN)The results fortrue.Object.is(0. -0)The results forfalse

The resources

  • JavaScript data types and data structures
  • 【MDN】JavaScript equality judgment

The last

Three people, there must be my teacher yan nuggets, code more than mutual learning, common progress

If there are any errors in this article, please correct them in the comments section. If this article has helped you, feel free to like, comment and follow.

series

  • [Magic JavaScript] Data types, do you really master them?
  • [Magic JavaScript] Prototype programming, do you really understand?
  • [Magic JavaScript] function programming, you really skilled?
  • [Magic JavaScript] Asynchronous programming, have you really learned?
  • [Magic JavaScript] Event loop, do you really understand?
  • [Magic JavaScript] Garbage collection, are you really clear?