JavaScript basic interview question summary 01

Posted by soccerstar_23 on Sun, 06 Feb 2022 21:23:01 +0100

1. What are the basic types of JavaScript? What are the reference types? What is the difference between null and undefined?

Data type:

Basic data types: Number, String, Boolean, undefined, null

Reference data types: Function, Object, Array

difference:

undefined: indicates the value when the variable is declared but not initialized

Null: indicates that it is prepared to save the object, but the value of the object has not been actually saved. From a logical point of view, a null value represents a null object pointer

ECMA standard requires null and undefined equivalence judgment to return true

null == undefined // true

null === undefined // false

2. How to judge the data type of JavaScript?

typeof

typeof can be used to distinguish original data types other than null type. Functions of object type can be recognized from ordinary objects:

typeof undefined // "undefined" 
typeof null // "object" 
typeof 1 // "number" 
typeof "1" // "string" 
typeof Symbol() // "symbol" 
typeof function() {} // "function" 
typeof {} // "object"

// ES6 introduces a new primitive data type Symbol, which represents a unique value. The biggest usage is to define the unique attribute name of the object.

Question 1: typeof cannot recognize null. How to recognize null?

Answer: if you want to judge whether it is null, you can directly use the = = = congruence operator (or use the following Object.prototype.toString method)

let a = null 
a === null // true 

Question 2: will typeof report an error when it acts on an undefined variable?

Answer: no error will be reported and "undefined" will be returned.

typeof randomVariable // "undefined" 

Question 3: what is the return value of typeof Number(1)?

Answer: "Number". Note that when Number and String are called as ordinary functions, they convert the parameters to the corresponding original data types, which is similar to a forced type conversion operation, rather than being called as constructors by default. Note the difference between Array and Array, Array(...) Equivalent to new Array(...)

typeof Number(1) // "number" 
typeof String("1") // "string" 
Array(1, 2, 3) // Equivalent to new Array(1, 2, 3) 

Question 4: what is the return value of typeof new Number(1)?

Answer: "object".

typeof new Number(1) // "object" 
typeof new String(1) // "object"

instanceof

instanceof cannot be used to judge the data of the original data type

 3 instanceof Number // false 
'3' instanceof String // false 
true instanceof Boolean // false 

instanceof can be used to determine the type of object

var date = new Date() 
date instanceof Date // true 
var number = new Number() 
number instanceof Number // true 
var string = new String() 
string instanceof String // true 

It should be noted that the result of instanceof is not necessarily reliable, because in ECMAScript7 specification, you can customize symbol Hasinstance method to override the default behavior.

Object.prototype.toString 
Object.prototype.toString.call(3).slice(8, -1) // "Number" 
Object.prototype.toString.call(new Number(3)).slice(8, -1) // "Number" 
Object.prototype.toString.call('3').slice(8, -1) // "String" 
Object.prototype.toString.call(new String(3)).slice(8, -1) // "String" 
Object.prototype.toString.call(true).slice(8, -1) // "Boolean" 
Object.prototype.toString.call(new Boolean(true)).slice(8, -1) // "Boolean" 
Object.prototype.toString.call(undefined).slice(8, -1) // "Undefined" 
Object.prototype.toString.call(null).slice(8, -1) // "Null" 
Object.prototype.toString.call(Symbol()).slice(8, -1) // "Symbol" 

It can be seen from the above example that this method has no way to distinguish between digital type and digital object type. Similarly, there are string type and string object type, boolean type and Boolean object type

In addition, the ECMAScript7 specification defines the symbol symbol Tostringtag, you can customize the object through this symbol prototype. Behavior of toString method:

'use strict' 
var number = new Number(3) 
number[Symbol.toStringTag] = 'Custom' Object.prototype.toString.call(number).slice(8, -1) // "Custom" 
function a () {} 
a[Symbol.toStringTag] = 'Custom' 
Object.prototype.toString.call(a).slice(8, -1) // "Custom" 
var array = [] 
array[Symbol.toStringTag] = 'Custom' 
Object.prototype.toString.call(array).slice(8, -1) // "Custom" 

Because object prototype. ToString method can be through symbol Tostringtag property to override the default behavior, so using this method to determine the data type is not necessarily reliable

Array.isArray 
Array.isArray(value)Can be used to judge value Array or not: 
Array.isArray([]) // true 
Array.isArray({}) // false 
(function () {console.log(Array.isArray(arguments))}()) // false

3. How to create functions?

First (function declaration)

  function sum1(num1, num2) {
    return num1 + num2;
  }

Second (function expression)

  var sum2 = function (num1, num2) {
    return num1 + num2;
  }

The third (function object mode)

  var sum3 = new Function("num1", "num2", "return num1+num2")

4. How many ways can JavaScript create objects?

1. Simple object creation uses object literals {}

Create an object (the simplest, easy to understand, recommended)

  var Cat = {} // JSON 
  Cat.name = "kity" // Add attribute and assign value 
  Cat.age = 2
  Cat.sayHello = function () {
    alert("hello " + Cat.name + ",this year" + Cat["age"] + "Years old") // You can use "." You can also use HashMap to access properties 
  }
  Cat.sayHello() // Call the (method) function of the object

2. Use function to simulate class

2.1) create an object, which is equivalent to an instance of new class (parameterless constructor)

  function Person() {}
  var personOne = new Person() // Define a function. If there is a new keyword to "instantiate", the function can be regarded as a class 
  personOne.name = "dylan"
  personOne.hobby = "coding"
  personOne.work = function () {
    alert(personOne.name + " is coding now...")
  }
  personOne.work()

2.2) the parameterized constructor can be used for implementation, which is more convenient to define and more extensible (recommended)

  function Pet(name, age, hobby) {
    this.name = name // this scope: current object
    this.age = age
    this.hobby = hobby
    this.eat = function () {
      alert("My name is" + this.name + ",I like it" + this.hobby + ",It's also a foodie")
    }
  }
  var maidou = new Pet("McDull", 5, "sleep") // Instantiate / create objects
  maidou.eat() // Call eat method (function)

3. Create using factory mode (Object keyword)

  var wcDog = new Object()
  wcDog.name = "Wangcai"
  wcDog.age = 3
  wcDog.work = function () {
    alert("I am" + wcDog.name + ",Woof, woof......")
  }
  wcDog.work()

4. How to use prototype object prototype keyword

  function Dog() {
  }
  Dog.prototype.name = "Wangcai"
  Dog.prototype.eat = function () {
    alert(this.name + "It's a foodie")
  }
  var wangcai = new Dog()
  wangcai.eat()

5. Mixed mode (prototype and constructor)

  function Car(name, price) {
    this.name = name
    this.price = price
  }
  Car.prototype.sell = function () {
    alert("I am" + this.name + ",I sell it now" + this.price + "Ten thousand yuan")
  }
  var camry = new Car("Camry", 27)
  camry.sell()

6. Dynamic prototyping (can be regarded as a special case of mixed mode)

  function Car(name, price) {
    this.name = name
    this.price = price
    if (typeof Car.sell == "undefined") {
      Car.prototype.sell = function () {
        alert("I am" + this.name + ",I sell it now" + this.price + "Ten thousand yuan")
      }
      Car.sell = true
    }
  }
  var camry = new Car("Camry", 27)
  camry.sell()

The above are the most common ways to create objects in javascript

5. Please point out the difference between JavaScript host object and native object?

Native object

"Object provided by ECMAScript implementation independent of host environment"

Including: Object, Function, Array, String, Boolean, Number, Date, RegExp, Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError

Built in object

Developers don't have to instantiate the built-in object. It has been instantiated internally

It is also "independent of the host environment". ECMA-262 defines only two built-in objects, Global and Math

Host object

Both BOM and DOM objects are hosts. Because it presents different content for different "host" environments. In fact, to put it bluntly, the official undefined objects of ECMAScript belong to the host object, because most of the undefined objects are created by themselves through the ECMAScript program

Topics: Javascript Front-end Interview