Value types and reference types in JavaScript

Source: Internet
Author: User

First throws a question, Ali's written test surface question (very basic, but is actually Ali's written examination question)

var a = {"X": 1};

var B = A;

a.x = 2;

A = {"X": 3};

Console.log (b.x);

What do you think the final result in the console output is?

If your answer is 2, then you don't need to go. If not. Then you can continue to look to solve your doubts!

Value types and reference types in JavaScript

In JavaScript there are two types of variables, one is a value type and one is a reference type.

Value types: Numeric, Boolean, null, undefined

Reference types: Arrays, objects, functions

The exchange of a variable of a value type is an ordinary interchange. For example: var a = 1; var B = A; A = 2;console.log (b);//The result is 1. B will not change because of a change

Reference types and value types are different. For example: var a = [1,2];var B = a;//The assignment of a assignment B to the value type above is different. This can be understood by pointers, which can actually be used as a pointer to an array.

More image point, it can be understood as follows: compare [to] treasure, A is a treasure map. You can find this array based on a. where var b = A; it's equivalent to copying a treasure map to b,b. You can also find an array of []. Understand this is good to understand the following things.

If a[0] = 3, then Console.log (b) will output [3,2]. Because a[0] = 3 directly change what is inside the treasure. All B-obtained arrays have also changed.

Value types and reference types in JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.