How do value types and reference types work in Javascript?

I know that in C # there are value types and reference types and one of the differences between them is in memory management. What decides how variables will behave is their type, so if it's a int it's going to be a value type, if it's an instance of a class Cliente, for example, it's going to be a reference type.

In Javascript there is no difference in types. All variables are instantiated with the Keyword var. So how does memory management work in the Javascript? Is there such a difference, that some variables are stored directly in the stack and others are stored in the heap only having a reference in the stack?

Author: Maniero, 2014-01-29

4 answers

In Javascript there is no difference in types. All variables are instantiated with the Keyword var.

JavaScript does have a type system

When you store a value in a variable, that value has a type. The type of a given value never changes, but the value stored in a variable can be changed. Any variable can contain a value of any type at any time, and so it makes no sense to declare the type of the variable. The type is a characteristic of values, and variables (think of them as places where values are stored) are agnostic about them. In other words, variables are not tied to any type, but always contain values that belong to any of the available types.

The types

Five of the six types in JavaScript have values primitive : Undefined, Null, Boolean, String, and Number. Primitive values such as undefined, null, true, "texto" and 10 are immutable. Undefined and Null they are special types that have only one value each, respectively undefined and null.

The sixth type is Object, which includes arrays, functions, and others. Objects are sets of properties, which can hold values of any of the types already mentioned. Properties can be added to or removed from an object at any time, and property values can also be changed. Therefore, objects are changeable.

There are still other types that the specification defines for own use, to describe how the language should work. They are not available to language users (nodes), nor do they need to have direct correspondents in the implementation.

Value versus reference

I don't know C# well, but from what I understood about value types and reference types, it is possible to draw a parallel with JavaScript. Leave aside the issue of the location of allocation, which I will discuss later, and focus on the behavior of types when a value is assigned to a variable or passed to a function or method.

Primitive JavaScript types can be considered to work like value types, while objects work like reference types. I will explain with an example:

var meuObjeto = {};

Here an object is created, which is stored in the variable meuObjeto. But is it really? What is stored in this variable is a value of type Object. The object itself (with its properties, methods, etc.) is stored somewhere in memory, managed by the language interpreter. And the value of type Object is a reference to that object.

To say that objects are references means only that with the reference in hand you can access the object, and not that the reference is a pointer to where the object is stored in memory. This distinction is very important. Think of the reference as a value like any other. Now consider the following example:

var a, b;
a = {};
b = a;
b.umaPropriedade = "um valor";
b == a; // true
a.umaPropriedade; // "um valor"
b = { outroObjeto: true };
b == a; // false

Here, b is not " a reference to a"; b contains a reference to a particular object, and a contains another reference to the same object. Thus, one can change a property of that same object by means of a or b. But you cannot overwrite the object that is in a by assigning a new value to b. What b = { outroObjeto: true } does is only store in b a new reference, to another object. We first object continues to exist, and the reference contained in a still points to it.

This same concept also serves to understand how objects are passed to functions:

function teste(obj) {
    obj.novaProp = "foo";        // o objeto fora da função é afetado
    obj = { outraProp: "bar" };  // o objeto fora da função NÃO é afetado
}
var o = {};
teste(o);
o.novaProp;  // "foo"
o.outraProp; // undefined

This means that in JavaScript there is no "by reference" passage. The object is passed by value, only the value passed in teste(o) is a reference.

So how does memory management work in Javascript? There is this difference, of some variables being stored directly in the stack and others are stored in the heap only having a reference in the stack?

When programming in JavaScript, keep in mind that memory access is the responsibility of the language interpreter. You don't manipulate memory directly in JavaScript. The language specification does not even mention how the memory should be treated, this is entirely in charge of the implementation. So it is not possible to say where each data is stored without knowing well how each interpreter works. I don't know that, so I can't say anything about it.

But if you are concerned about memory usage by Your JavaScript, remember the following:

  • there is a garbage collector in the JavaScript engines
  • this garbage collector runs at arbitrary times (usually when the interpreter is not busy with your code)
  • the garbage collector only release the memory occupied by an object if there is no "living" reference to that object.
  • meaning: beware of objects captured in closures , they may end up occupying memory forever!

the doubts that arose when preparing and finalizing this answer generated a question in Soen, with a very interesting answer.

 15
Author: bfavaretto, 2020-06-11 14:45:34

Javascript has a difference between Yes data types, despite being a weak typing language . You can find the data types that javascript supports here .

Therefore, Javascript does not allow passing values by reference, but it is possible to circumvent this limitation by passing an object as a parameter , as can be seen in the following example:

var A = new Array();

function swap(A, a, b){
        var c = A[a];
        A[a] = A[b];
        A[b] = c;
}

And, in addition to being weakly typed, like most languages in scripting, Javascript has dynamic typing , which, along with being weakly typed, makes the language more dynamic.

 9
Author: Felipe Avelar, 2014-01-29 14:57:41

In Javascript there are primitive types and complex types.

Primitives would be string, number, boolean, and undefined. Primitive types are copied by value. Then:

var x = 1, y = x;
x = 2;
console.log(x);//vai mostrar 1

Complexes are objects, functions, and arrays. Complex types are copied by reference. Then:

var x = [1,2], y = x;
y[0] = 3;
console.log(x);//vai mostrar [3,2]

So I believe it looks like C#.

Reference: https://github.com/airbnb/javascript#types

 3
Author: Erik, 2014-01-29 15:10:01

Javascript is a "weakly typed" language.

The type of the variable is determined by the interpreter at runtime and can be changed during program execution as the content of the variable changes.

Several languages that are defined this way, mainly languages interpreted as javascript.

 1
Author: pablosaraiva, 2014-01-29 14:49:16