


A brief analysis of JavaScript basic types and reference types_Basic knowledge
For JavaScript types, it can be simply summarized as: compared to strongly typed languages, it is a weak (loose) typed language; there are basic types and reference types, and the difference between them is that there is a fixed space in the stack memory. , an unfixed space is saved in heap memory and a pointer to the implementation location is saved in stack memory.
Many books on the market have a lot of space to talk about it. This article will cover several aspects that may require you to have some basic understanding of JavaScript, especially JavaScript types. If you still don’t understand it, you can pick up a book about JavaScript and read it before reading this article.
1. Basic types and reference types
1. Basic types: Undefined/Null/Boolean/Number/String
2. Reference types: Object/Array/Function/Date/RegExp/Error/Map/Set…
Why haven’t the reference types been enumerated? Because it’s enough for you to know this much, at least for this article I’m talking about. Others may be rarely used, and even things like Map and Set are not supported by all browsers.
2. Judgment of JavaScript type
There are two operators in JavaScript that can be used to determine types. They are typeof and instanceof, but the circle is very small, they don't mix well, and they are notoriously unreliable. It is correct in a few cases, but unreliable in many cases. Just take a look and you’ll know:
// When reliable:
typeof ' sofish' // string
new String('sofish') instanceof String // true
// When unreliable:
typeof [] // object
typeof null // object
'sofish' instanceof String // false
Hmm~ Maybe many beginner JavaScript programmers will curse because of this. Most people already have libraries such as jQuery when they need to use JS. They have encapsulated them so that you can easily detect types. Of course, in fact, it is not troublesome to detect, because the saying "In JavaScript, everything is an object", of course, as mentioned in many documents, undefined is actually just a global property like NaN and Infinity. You probably know that. But "object" can help us:
/* Detection Object type
* @param: obj {JavaScript Object}
* @param: type {String} JS type name starting with uppercase
* @return: {Boolean}
*/
function is(obj, type) {
return Object.prototype.toString.call(obj).slice(8, -1) === type;
}
In this case, we can use the is function to help us determine the type, and this simple function has good compatibility and can be used in your project. For example:
is('sofish', 'String' ) // true
is(null, 'Null') // true
is(new Set(), 'Set') // true
3. JavaScript type conversion
In JavaScript, the type of variables (properties) can be changed. The most common one seen is the conversion between String and Number. How to turn 1 '2' into 12? It is necessary to understand the operator, which is a mathematical operator and a string hyphen in JavaScript. Therefore, novices will often see an interesting phenomenon. When using the sign, sometimes the calculation is not what they want, but using the - sign can always get the "correct" answer.
1 '2' // '12'
1 ( '2') // 3
1 - '2' // -1
This is actually caused by the dual role of . In the above code, you can notice that the second expression uses a number in front of String, forcing its class to be converted to Number. As for the understanding of JavaScript type conversion, in most cases, it is enough to understand that it has dual roles. Other understandable classes can be modified using assignment/overloading, even Error:
var err = new Error();
console .log(err instanceof Error); // true
err = 'sofish';
console.log(err); // 'sofish'
4. JavaScript reference types
This is a difficulty in this article. Compared with basic types, references can add properties and methods to them; a value similar to a reference is a reference, and a value of a reference type is assigned to a variable, and they point to the same value stored in the heap memory. Variables (properties) can be overloaded, but copying can be a very interesting thing, we will talk about it in detail later.
1. Add properties and methods
We will see in the following code that if we assign a basically similar value, it will not report an error, but it will be invalid when getting it:
var arr = [1,2,3];
arr.hello = 'world';
console .log(arr.hello); // 'world'
var str = 'sofish';
str.hello = 'world';
console.log(str.hello); // undefined
2. Operations on reference type values
Since the reference type is stored in the stack memory as a reference, when we point to the same original value, the operation on the value will affect all references; here is an example of reassignment (not the operation of the value) Direct manipulation) will recreate an object without changing the original value. For example:
var arr = [1,2,3] , sofish = arr;
sofish.push('hello world');
console.log(arr); // [1, 2, 3, 'hello world']
// Non-identical type
sofish = ['not a fish']; // When sofish is changed similarly, the original value will not be changed
console.log(arr); // [1, 2 , 3, 'hello world']
3. Copying reference type values
Operations on the original value will affect all references, which is not necessarily what we want. Sometimes we need to copy a brand new object without affecting other references during the operation. In general, there are few specific operations like Date/Function/RegExp..., mainly operations such as adding items and properties to Array and Object. So the main thing we need to understand is how to copy Array and Object objects.
3.1 Copying arrays
In the Array object, there is a slice method that returns an intercepted array. In ES5, filter and so on also return a new array, so we may use this method to copy.
var arr = [1, 2, 3];
var sofish = arr.slice();
// Operating on the new array will not affect the original array
sofish.push('hello world');
console.log(arr); // [1, 2, 3]
3.2 Copy of Objects
We use the slice method to copy Array. In fact, for both Array and Object, we can use the for ... in loop to traverse and assign values to copy.
var obj = { name: 'sofish' }, sofish = {}, p;
for (p in obj) sofish[p] = obj[p];
//Operations on new objects will not affect the original value
sofish.say = function() {};
console.log(obj); // { name: 'sofish' }
3.3 Shadow / Deep Copy
Operations like the above are what we often call shallow copy (Shadow Copy). However, both Array and Object can have multiple layers (dimensions). A copy like this only considers the value of the top layer. Among the possible values, Array and Object still point to the original object. For example:
var arr = [1, { bio: ' not a fish' } ], sofish = [], p;
for(p in arr) {
sofish[p] = arr[p];
}
// Operations on the object `cat` contained in `sofish` will affect the original value
sofish[1].bio = 'hackable';
console.log(arr);// [1 , cat: { bio: 'hackable' } ]
So how to do it? Let’s use a copy() function to solve this problem:
/* Copy object
* @param: obj {JavaScript Object} Original object
* @param: isDeep {Boolean} Whether it is a deep copy
* @return: {JavaScript Object} Return a new object
*/
function copy(obj, isDeep) {
var ret = obj.slice ? [] : {}, p, prop;
// Use with is function
if(!isDeep && is(obj, 'Array')) return obj.slice();
for(p in obj) {
if(!obj.hasOwnProperty(p)) continue;
prop = obj[p];
ret[p] = (is(prop, 'Object') || is(prop, 'Array')) ?
copy(prop, isDeep) : prop;
}
return ret;
}
In this way, we can copy an Array or Object through the copy(obj, isDeep) function. You can test it:
var arr = [1, {bio : 'not a fish'}];
var sofish = copy(arr);
// The shallow copy operation on the first layer does not affect the original value, but affects the second layer
sofish.push('cat');
console.log(arr); // [1, {bio: 'not a fish'}]
sofish[1].bio = 'hello world';
console.log(arr) // [1, {bio: 'hello world'}]
// Deep copy will not affect the original value
sofish = copy(arr, 1);
sofish[1].bio = 'foo or bar';
console.log(arr) ; // [1, {bio: 'hello world'}]
That’s it. You should basically understand all the difficult points about types that you need to understand. Of course, copying is the most troublesome point. In addition to Array and Object that often need to be operated, there is also copying of Date/Function/RegExp.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6
Visual web development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
