简体   繁体   中英

Javascript and Python variable differences

I've just started learning Javascript and used to Python previously.

Python variables work as a reference to, a 'block' in memory. Other aliases can point to block in memory and which is cleaned up by the garbage collection when there are no more references remaining which point to it.

However I'm not sure if this is the same in Javascript? Does Javascript use direct pointers, rather than references? So does javascript have the same shallow or deep copy differences that Python does? (I've heard that JS may not have the concept of mutability or immutability, so this may not be the case).

Can anyone explain how Javascript variables work in detail as I can't picture this well?

Thanks.

PS I'm still pretty new to programming so apologies if my terminology is a bit wonky.

Yes, javascript works in a similar way.

booleans, numbers, and strings are stored by value. So, in this code snippet, for example,

var a = 122;
var b = 122;

a === b will be true.

Everything else, however, is stored by reference and automatically garbage-collected as you described in your question. So, for example, in this code snippet,

var a = [1, 2, 3, 4]
var b = [1, 2, 3, 4]

a === b will be false.

Edit:

In Python, array and dictionary equality are by value, but class instances are equal only if they are the same instance. In javascript, an Object is basically a dictionary where the keys must be strings. Because Objects are used in javascript to fill the same role as class instances in Python (you'd be surprised at how well it works), Objects are equal only if they are the same Object. Arrays inherit from Object, so they are also by reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM