Why can .pop() method change the structure of array that was defined as const variable?

Arrays and Functions

Hello! Why can .pop() method change the structure of array that was defined as const variable ?

15 Likes

Because only the variable name and structure type are constant. The elements themselves are mutable. What this means though is that we cannot clear the array with,

concept = []
        ^

TypeError: Assignment to constant variable.

like we can in the case of var or let. We must pop or shift until the array is empty to clear it.

while (concept.length) {
  console.log(`'${concept.pop()}' taken off the array.`);
}
console.log(concept);
'MUTATED' taken off the array.
'be' taken off the array.
'can' taken off the array.
'arrays' taken off the array.
[]

or,

while (concept.length) {
  console.log(`'${concept.shift()}' taken off the array.`);
}
console.log(concept);
'arrays' taken off the array.
'can' taken off the array.
'be' taken off the array.
'MUTATED' taken off the array.
[]
111 Likes

Thanks a lot for clarifying!

2 Likes

Hi,
I’m new. Thanks for addressing this topic! I’m still confused. You said that arrays that are declared constant actually only have constant variable names and structures. Does this hold for other variable types, too? For example, could I:

const fact = true;
fact = false;

This does not change the name or variable type. (My guess is that no, I can’t do this, but I don’t know why…)

Thanks!

2 Likes

And neither could it. const fact = true is akin to saying, const PI = Math.PI. There is no changing it. Trying to change it will throw an error.

A data structure is different, though. It is like a map with any number of locations. The two protected aspects are name and structure. The contents are still mutable.

4 Likes

MTF, thanks for responding to my question. I am still confused, but I think I’m starting to understand better. Please let me know if these are correct:

An array is not a regular variable.
You cannot change the value of constant variables, but you can change the contents of constant arrays.
A constant array just means that you can’t suddenly turn it into a string, or something.

Here’s one more question for you: Is there a simple way of creating an array in Javascript that has constant size and elements?

Thanks again for the help!

We can create a protected data structure, but protecting the contents and size means we need to build safeguards into the code itself, namely make no assignments to the array (other than to create and fill it) and use it for read-only purposes. Using for..of is a read-only loop, for instance.

2 Likes

Ok, thank you! Good to know.

Something just occured to me… What about a string? String objects are immutable. We can still traverse them, and if declared as a const they cannot be replaced or removed so persist for the entire session.

Eg. (not practical, but demonstrative)

 > test = (new Array(26).fill('a')).join('|')
<- "a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a"
6 Likes

In JavaScript the const word means that the value of the variable cannot be changed.

How can this be when you can change an array stored in a variable?

Simple the variable’s value is NOT the array, the variable’s value is a reference to the array, that is to say the variable stores a note that redirects you to where to array is really stored. This is how multiple variables can point to the same array and when the array changes all the variables will changes too, they don’t all have copies of the array, they all just redirect you to the same array. You can replace array with any of the reference types : array, object or function.

With Primitive types (number, bigint, boolean, string, undefined, null, symbol) they are all immutable. Because they are immutable the only way to update a variable that has a primitive type as its value to to change the value.

So with const what you are saying is the variable value cannot change and when that value is a reference, you cannot change that reference (you still have to point to the same array, object or function) but what is being referenced can change internally (the items in an array for example, or the values on an object).

15 Likes

There is a way to find out where the hooks are planted.

g = x => x.toString();

g is automatically bound to the global namespace via the window object.

 > window.g(5)
<- "5"
 > g('ab')
<- "ab"
 > 

g is mutable.

Let’s port it to f.

 > const f = g
 > f(42)
<- "42"
 > 

Now let’s change the mutable g.

g = x => x.toString().toUpperCase();

What happens to f?

 > f('ab')
<- "ab"
 > g('ab')
<- "AB"
 > 

f was originally assigned g. However, g has now changed, but f has not. Why is that?

f is a reference to the object. Just because we decided to change the object to which g is tied, does not preclude this binding. We only really changed what g references. The object to which f is bound still exists in the namespace and will persist for the duration of the session.

Botton line, f and g only share a reference when it is the same object they point to. Change one reference and that sharing ends. The other reference still applies, especially being a const.

This logic can be applied across scopes, and is likely very useful though I won’t venture to summon up any examples. Can anybody show us some?

9 Likes

Fantastic explanations, thank you so much!

1 Like

Yeah I understood that we can’t change the array name it is const type variable. But what do you mean by structure type? Also tell me why it’s giving error…is it because we can’t have empty array? Also tell me if it is correct to say const variable or only const (pronounced as constant) we should call because const and variable are two entirely opposite things in maths.

Anything that can hold multiple pieces of data is a structure. An array, an object, and a set are all structures.

We can have an empty array, that’s not a problem. The error message tells us why in this case we cannot assign to a constant variable. A constant can only be assigned once in the session and it stays what it is. The object is constant. However its size and contents are completely variable.

‘Variable’ is a programming term meaning, ‘name’ or ‘label’. It is similar to maths. The fact that constants don’t vary is a given. What disallows a const from varying is the declaration. It places a restriction on that named object. The assignment is fixed.

Arrays and objects are merely references to data within them. That data is mutable.

3 Likes

thank you for clearing my doubts.

1 Like

After all this questioning I still have a doubt: If I create an array inside a block (e.g. a function), will that array exist only inside that block? Will this array exist only once the block is ‘called’ ? And once it exists, if I call that same block again, will there be a new array?

Variables declared in function or block scope cease to exist after the function or block has been exited. That goes for any arrays, as well.

1 Like

Ok, so in case I need to do something function related with an array, but I need to store this array globally, I should always declare a variable for this array on the global scope, right? (or at least in the topmost level in which it could be required).

It’s okay to declare an array in a function, but if it is going to be needed by other functions or other parts of the program then it would be returned.

const foo (x) {
    y = []
    for (let i = 1; i <= x; i++) {
        y.push(i)
    }
    return y
}

nums = foo(10)
console.log(nums)

//  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Now we have the array in global scope. Each time we call the function with a different argument, it will return a new array. We can either assign it to a new variable (so nums is still intact) or it can be assigned back onto the nums variable.

4 Likes

Nice, thanks for the answer!

1 Like