Intro to JS question

from Novice to Ninja

If the variable references a non-primitive data type, such as an array, function or object, then using const will not make it immutable . This means the underlying data inside the object can change (known as mutating the object).

please clairfy :slight_smile:

2 Likes

When you declare an object as a ā€˜constā€™ you are reserving memory for that const.
The assigned object is in a different memory location and the const is a reference to the memory location od the object
The system knows that it is an object and when you change the object you are changing the object not the const.
When you change the object it can either overwrite the existing object or create a new object and deleting the existing object and changing the reference.
Think of const as a container for an object and you can change what goes into the container but not the container.
That is the simple aprox. answer.

Constants cannot be reassigned.

const obj = { c: 2 }

const obj = { d: 3 }
// Uncaught SyntaxError: Identifier 'obj' has already been declared

obj = { d: 3 }
// Uncaught TypeError: Assignment to constant variable.

The contents of reference types can be changed though. They are mutable.

Objects

// adding a property to the object
obj.d = 3
console.log(obj)
//  { c: 2, d: 3 }

// deleting a property from the object
delete (obj.c)
console.log(obj)
// { d: 3 }

The same for Arrays, another reference type.

Arrays

const arr = [1, 2, 3, 4]

arr = [6, 7, 8]
// Uncaught TypeError: Assignment to constant variable.

// add an item to the array
arr.push(5)
console.log(arr)
// [1, 2, 3, 4, 5]

// remove the last item
arr.pop()
console.log(arr)
// [1, 2, 3, 4]

In short if a reference type is assigned to a const you can still change itā€™s contents. It is mutable.

2 Likes

As this relates to the Novice to Ninja course/book I have moved it to the appropriate category :slight_smile:

1 Like

many thanks!

follow up question

let b = 2;
{ b = 4; b; }<< 4

Now check the value of b outside the block:

Copy

b;<< 4

In this example, b is defined globally outside the block and given the value of 2. Then we reassign the value of b to 4 inside the block, but without using let. This means that it still refers to the global variable outside the block, so the value of b is the same both inside and outside the block and it gets overwritten globally to be a value of 4.

i need help with understanding

Then we reassign the value of b to 4 inside the block, but without using let. This means that it still refers to the global variable outside the block, so the value of b is the same both inside and outside the block and it gets overwritten globally to be a value of 4.

maybe re-phrase

go slow and simple for meā€¦ its intimating off the bat for me :slight_smile:

So letā€™s cover a few basics.

the curly braces are being used to define a block. A segment of code that is a sub-section of the main execution space. All functions are blocks, etc.

In effect, inside of a block, javascript maintains a variable reference table specific to that block. Anything defined inside the block is local to that block, also called scoped to that block. let, const, var define variables.

When resolving a variable reference, the code will first try to resolve the variable against the current blockā€™s table; if it does not find a resolution, it will bubble up and check the parent scope (repeat as necessary until you come to the main scope; if it fails to resolve in the main scope, an error is thrown as the variable is undefined in any scope.)

So lets look at the example.

let b = 2;
{ b = 4; b; }

First line is pretty simple, it defines a variable. For sake of ease, I will assume this is in the main scope (but it could be any number of layers deep, the result holds true regardless of how many parents are above this scope!). So b is defined in the main scope as a variable (ie: not a constant), with value 2.

The second line is a bit jammed together. It may help if i spread it out a bit.

let b = 2;
{ 
  b = 4; 
  b; 
}

so;
{ opens a new block (scope).
b = 4 tries to set a value to the variable b. Note that thereā€™s no let here, so weā€™re not defining a new variable, weā€™re trying to set a value of an existing one. So Javascript looks at the blockā€™s variable table. Thereā€™s nothing there, because the block hasnt defined any variables. So it goes to the parent. The parent has a variable called b. So the code latches on to that reference, and assigns the value 4 to that variable.
b; just outputs the current value of b. Again, javascript will look locally, find nothing, and go to the parent.
} closes the block; when the code gets here, javascript can dump anything in the variable reference table for the block; its no longer relevant.

But what if we DID define a new variable inside the block?

Letā€™s change the example a little bit.

let b = 2;
{ 
  let b = 4; 
  console.log(b); 
}
b;

(Q: ā€œWhy do you need console.log?ā€ A: Because I want to output multiple times, I cant rely on the inherent console return until the very end of the code.)

This time, I define b inside the block. This puts it into the local scope for the block.

Give the code a try, but before you push enter, what do you think will happen? Why?

first, thank you

some follow up

what is this?

Novice to Ninja hasnā€™t covered this, so i am a bit confused

kindly clarify the followingā€¦ maybe re-explain or word it differently

unfortunately i need help here too :frowning:

i am just into Novice to Ninja

i know this is a lot at once, but it is where i am coming from

again, i am thankful for your time and troubleā€¦ and for NOT making me feel like an idiot!

Everybody starts somewhere. When youā€™re an expert ripping scripts out left right and center, just remember that when the next person comes along and needs the beginnings :wink:

Soā€¦ the Javascript engine (andā€¦ for that matter, pretty much ANY programming language) needs to know what variables exist, where their values are stored in memory, so they can go look the value up when it needs to.

Think about it like a warehouse. Youā€™ve got a very big warehouse. Someone comes up to you and asks you to get ItemX from the warehouse. Things will be a lot easier if youā€™ve got a checklist somewhere that says ItemX is on Row 7, Shelf B; or, that ItemX isnt even in the warehouse at all! Without having to walk up and down every aisle.

So the engine keeps track of these things. The exact mechanics of how Javascript does this are beyond the scope of beginner knowledge; so suffice it to say, Javascript is writing down what variables are in its warehouse. Every time you start a block, you startā€¦ a warehouse inside the warehouse. Okay my analogyā€™s slipping away a bit thereā€¦ butā€¦itā€™s 10 oā€™clock at night, so i dont have a better analogy for storage-inside-storage.

So letā€™s go back to the warehouse-inside-the-warehouse. Someone (the line of code thatā€™s trying to assign a value) comes to your inner warehouse and says ā€œIā€™d like b please. I want to put this 4 there.ā€.

The warehouse operator looks at his sheet of stuffā€¦ but thereā€™s no b there. (Thereā€™s nothing there at all, actually, because this block hasnā€™t defined any variables). So he calls up to the outer warehouse, and asks if theyā€™ve got any bā€™s. The outer warehouse does, so the request goes off to the outer warehouse to put its 4 away.

Notably, this line of communication only works one way - the inner warehouse can call the outer warehouse, but it cant call any other warehouse, and the outer warehouse canā€™t call it either.

thanks!

please break this down to its simplest form / definitionā€¦ ā€œvariableā€, ā€œreferenceā€, ā€œtableā€ and ā€œblockā€

BTW

well said! i am glad youā€™re so cool with helping me!

for now, i will try to digest the above, likely have a follow up post :slight_smile:

thanks for your time and guidanceā€¦ and i am especially appreciative of your patience!

so sorry!

i forgot to mention you provided a great analogy. they can be a help!

ā€œvariable reference tableā€ is a singular phrase.

In the analogy, itā€™s that checklist. Itā€™s the place where the engine puts information about what variables have been defined inside this block, and where their data lies. It is a table, that is used to reference, variables by their identifier (name).

ā€œblockā€: A section of code, denoted and isolated from other sections of code. Blocks may contain blocks. Generally defined by curly braces {} in Javascript. Youā€™ll find them in lots of places; a for loop is a block, because it goes
for (let x = 0; x<3; x++) { //Do Some code. x is defined here, because its part of the for loop declaration. }
functions contain blocks for their execution space. function doAThing(y) { //More curly braces, more block. y is defined here, because its part of the function declaration. }
(Though it should be pointed out that curly braces donā€™t just make blocks; objects are denoted by curly braces too, so context is important.)

1 Like

having trouble here

i suspect its at my end, not yours

i donā€™t feel your analogy is the problem here

i am trying to understand what you have written, just canā€™t wrap my mind around the concept, yet

i feel i may simply need more time to get that ah-ha moment

again, your analogy and your follow up seems clear and i just havenā€™t figured it out yet :slight_smile:

So put yourself in Javascriptā€™s shoes.

I come to you and I tell you. ā€œIā€™m going to store something called a kerflabp. To start with, put this sock in itā€™s storage location.ā€ (Yes, iā€™m using intentionally odd things.)

So you, being an ever-helpful system and it being your job to do such things, decide on a place to put my sock somewhere in your massively large warehouse. You put the sock there, and then you go back to work, storing things, pulling them out again, helping people do silly mundane tasks like figuring out how many seconds have elapsed since an arbitrarily decided moment in time. Setting timers for things, and then doing those things when the timer goes bing. Youā€™re not actively keeping in mind every thing in this warehouse, cause thereā€™s billions of things.

A few days/weeks/months later, I come back to you. I say ā€œIā€™d like kerflabp please.ā€

How do you find my sock? How do you know if anythingā€™s actually been given to the warehouse called a kerflabp?

ok,

<script>
const kerflabp = sock;
</script>

is that right?

well it would be right if the sock is never going to be replaced. (const) Which it may be, I didnt specify in this particular instance.

But put aside the code for the moment, and think about the concept. 90% of coding is in the description of the program; knowing how computers think, being able to lay out, in order, what you need to do at each step of the program to get to the right ending.

1 Like

i find your sock, or find out if its even there, with a variable reference table

its in a variable reference table, the place the engine puts information about what variables have been defined inside this block and where their data lies, specifically, in this example, variable const and value sock

It is a table, that is used to reference, variables by their identifier here ā€œkerflabpā€.

its in my checklist named kerflabp

And thatā€™s all your checklist, and the table, do. You understand the concept. Every time you define a variable, it makes a new entry in the table. Every time you use a variable thats already defined, It looks at the table, it goes and gets whatever is stored at the place the table says to look. If you tell it to put something new there, it looks it up, goes and replaces whatā€™s stored there with the new thing (and throws the old thing away).

Now, consts are a little different, and a little bit more complex in some ways. A constant canā€™t be replaced - once you define a constant, it gets glued to your warehouse shelf. Simple, right?

Well, the trick is when the constant is an array, or an object - adding something to an array, removing something from an array - those operations dont replace the array in storage, they modify the object thatā€™s already there, which is allowed. Itā€™s common to say that a constant canā€™t be changed, but thatā€™s not true. It canā€™t be replaced. (In technical-speak, itā€™s a constant reference, rather than a constant value)

THANK YOU!!

i will give you 0.00000000001% of my first million!

sound fair?

ok, pleaseā€¦

back to the earlier post, please, if you think i am ready for it :slight_smile:

Hereā€™s another example where we define a global variable and then overwrite it from within the block:

Copy


let b = 2;

{ b = 4; b; }<< 4

Now check the value of b outside the block:

Copy


b;<< 4

is ā€œvariable referenceā€ the same thing as ā€œvariable reference tableā€

BTW what does b;<< 4 do for me?

In this example, b is defined globally outside the block and given the value of 2. Then we reassign the value of b to 4 inside the block, but without using let. This means that it still refers to the global variable outside the block, so the value of b is the same both inside and outside the block and it gets overwritten globally to be a value of 4.

maybe its the time away, i may be beginning to understand this concept, but not the whole way there yet

not here yet in Novice to Ninjaā€¦ loops, loops declaration, functions etcā€¦

thanks again!

so a ā€œvariable reference tableā€ holds many "variable reference"s. in this case a reference to b.

so what thats trying to show you is that if you put b; into your code (or console, more likely), it will output the value 4. the << is being used to say ā€œthe value/output of this statement isā€¦ā€

Javascriptā€™s behavior, if your code line is just a variable, is to output/return the value of that variable. If your code is multiple lines long, the console will return the value of the last execution line (which is why youā€™ll often see undefined as a return if youā€™re using the console a lot)

Usually, when debugging code, we will explicitly call console.log to output some piece of information weā€™re looking at; variable values, text lines, etc. rather than relying on the last-line return.

from novice to ninja

In this example, b is defined globally outside the block and given the value of 2. Then we reassign the value of b to 4 inside the block, but without using let.

i get the concept up till here

kindly clarify from here onā€¦ i know you followed up with this concept

i do not mean to frustrate you

thanks for your patience