Web front-end training and JavaScript related knowledge

Sajjad Hussain
Sep 16 · 5 min read
Image for post
Image for post

Good programmers web front-end training shares JavaScript-related knowledge. Today I will share with you JavaScript-related knowledge. Let’s take a look at the friends who are working on the web front-end. I hope it can be helpful to everyone.

Basic types and reference types in JS

JavaScript variables contain two types of values: basic type values ​​and reference type values. The manifestation in memory is: the former are some simple data segments stored in the stack, and the latter are stored in the heap memory. An object.

Basic type value

The basic data types in JavaScript are String, Number, Undefined, Null, Boolean, and in ES6, a new basic data type Symbol is defined, so there are 6 types in total.

The basic type is accessed by value. After copying the value of the basic type from one variable to another, the values ​​of these two variables are completely independent. Even if one variable changes, it will not affect the second variable.

let str1 =’Hello’;

let str2 = str1;

str2 =’hello word’console.log(str2);//’hello word’

console.log(str1); //’Hello’

Reference type value

A reference type value is an instance of a reference type, which is an object stored in the heap memory. A reference type is a data structure. The most commonly used types are Object, Array, and Function, in addition to Date, RegExp, Error, etc.Two new data structures, Set and Map, are provided in ES6.

How to copy reference types in JS

The differentiation of basic types and reference type assignments, for example In the following code, only the name attribute in obj1 is modified, but the name attribute in ob1 and obj2 is changed at the same time.

let obj1 = {‘name’:’JOHN’};

let obj2 = obj1; obj2.name =’JOHN’;

console.log(obj1); // {‘name’:’H=JOHN’}

console.log(obj2); // {‘name’:’JOHN’}

When a variable copies a reference type value, it will copy the value of the variable to the new variable the same as the value of the basic type. The difference is that for the value of the variable, it is a pointer to the object stored in the heap memory.

Because, in JS, the object in the heap memory cannot be accessed directly, it is necessary to access the address of the object in the heap memory, and then obtain the value of the object according to this address.

Shallow copy

In JS, if the attribute is a basic type, the value of the basic type is copied; if the attribute is a reference type, the copy is the memory address; so if one object changes this address, it will affect the other object.

The following is the shallow copy method provided by JavaScript:

Object.assign

The method of copying objects in ES6, the first parameter accepted is the target of the copy, and the remaining parameters are the source object of the copy

Syntax: Object.assign(target, …sources)

let p = {‘name’:’hello word’,};

let copyP = {};

Object.assign(copyP, p);

console.log(copyP);console.log(p);

Object.assign is a shallow copy, it just creates a new object in the root property (the first level of the object), but if the value of the property is an object, it will only copy the same memory address.

Spread operator

Use the spread operator to clone or copy attributes when constructing literal objects. The syntax is as follows:

let cloneObj = {…obj };

let obj = {‘name’:’Monday’,’college’: [‘Tuesday’,’Wednesday’,’Thursday’]}let obj2 = {…obj};

obj.name=’No rest’;//{‘name’:’No rest’,’college’: [‘Tuesday’,’Wednesday’,’Thursday’]}console.log(obj);//{‘ name’:’Monday’,’college’: [‘Tuesday’,’Wednesday’,’Thursday’]}

console.log(obj2);

obj.college.push(‘Go’);//{‘name’:’No rest’,’college’: [‘Tuesday’,’Wednesday’,’Thursday’]}

console.log(obj); //{‘name’:’No rest’,’college’: [‘Tuesday’,’Wednesday’,’Thursday’]}

console.log(obj2);

The spread operator has the same problem as Object.assign(). The property whose value is an object cannot be copied into two different objects;

But if the attributes are all basic types of values, using the spread operator is more concise.

Deep copy

Shallow copy only creates a new object in the heap memory on the root attribute and copies the value of the basic type, but the complex data type, that is, the object, copies the same address.

The deep copy is a complete copy of an object from the memory, opening a new area from the heap memory to store the new object, and modifying the new object will not affect the original object.

JSON.stringify

JSON.stringify() is the most commonly used deep copy method in the current development process. The principle is to serialize an object into a JSON string, convert the content of the object into a string and save it in memory, and then use JSON. parse() deserialization turns the JSON string into a new object.

For example

let obj = {name:’Young handsome’, age: 18, friends: [‘john’], goodF: {name:’fruit’, age: 19, address:’Shanghai’, pets: [{name:’Watermelon’}, {name:’apple’}]}, bir: new Date()};

let newObj = JSON.parse(JSON.stringify(obj));

obj.goodF.pets[0].name =’Orange’;

console.log(newObj);console.log(obj);

There are several points to note when using JSON.stringify to implement deep copy:

1) If there is a function, undefined, symbol in the value of the copied object, the key-value pair in the JSON string serialized by JSON.stringify() will disappear;

2) Unable to copy non-enumerable properties, unable to copy object prototype chain

3) Copy the Date reference type will become a string

4) Copying RegExp reference type will become an empty object

5) If the object contains NaN, Infinity and -Infinity, the result of serialization will become null

Recursively implement deep copy

The specific implementation is as follows:

/** * Auxiliary function to determine whether it is an object * @param obj * @returns {boolean} */

function isObj(obj) {return obj instanceof Object;}

/** * Deep copy all the attributes/values ​​of the fromObj surface to the toObj object* @param fromObj copy object* @param toObj target object*/

function deepCopyObj2NewObj(fromObj, toObj) {

for (let key in fromObj) {

if(fromObj.hasOwnProperty(key)){

let fromValue = fromObj[key]; // If it is a value type, then copy the assignment directly

if (!isObj(fromValue)) {

toObj[key] = fromValue;

} else {// If it is a reference type, then call this method again, // copy all the properties of this object internally // What type of fromValue is, and create an empty object of that type

let tmpObj = new fromValue.constructor;

// console.log(tmpObj); // debugger;

deepCopyObj2NewObj(fromValue, tmpObj);

toObj[key] = tmpObj;

}

}

}}

Summary

1) In daily development, there is generally no need to copy many special reference types. Using JSON.stringify for deep copy objects is the most direct and simple method.

2) Realizing a complete deep copy is very complicated, and many boundary conditions need to be considered. If there is a copy requirement for a special reference type, it is recommended to use a third-party complete library, such as lodash.js.

Cloud Belivers

Everything you need for your next application task

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store