Semantic copy of value type in js

Viewed 69

I have started JS few months ago and i am really interested about what's under the hood when we run code into a console and how the data types are saved and read by the program.

What "implemented" and litteral syntax means compared to a non litteral syntax. I don't undersant the exemple they provide because in this case A has been overwrited so it should log 2 in the console. I don't understand what a copy semantic is .

For the second screen, it's even worse for me, because i don't really get the notion of lexical environement and what they means when they say : "two variables are added to the lexical environment; a and b. Their values are stored alongside their definition in the lexical environment in a key-value-pair mapping."

First Part of the article with exemple

Second part of the article with the lexical domain explenation

Thank for your help and i apologize if my question is damn stupid, Have a nice day !

1 Answers

The big source of confusion here is that some authors try to use concepts from other languages to describe how javascript works. This is where you hear words like "copy semantics", "pass by value", "pass by reference" etc. The truth is, these concepts simply do not apply in javascript.

In javascript, we've got values and variables. Values can be expressed by literals. A literal is a collection of characters that represents a value. Examples:

1    'Mary'   true    [4,5,6]    {name: 'Mary', age: 22}

[...] and {...} literals are different from others, because they always create a new value, even if they look the same. That's why

  'Mary' is equal to 'Mary`

but

  {name: 'Mary', age: 22} is not equal to {name: 'Mary', age: 22}

A variable is a string ("identifier") in your program that is linked ("bound") to a value. Examples:

let age = 3
let price = 12.99

Here, age is linked to the value 3 and price are linked to the value 12.99.

let checkers =  {name: 'Checkers', age: 5}
let myPet =  checkers

Here, checkers and myPet are linked to the same value {name: 'Checkers', age: 5}.

This link ("binding") is only visible in the block where it has been created and in any blocks that are inside that block in your program source. Inside some block, the list of visible bindings is its "lexical environment".

There are three things you can do with a variable:

  • use it in an expression or a function call e.g. age + 5 or console.log(myPet). In this case, what you're actually using is the value bound to the variable, not the variable itself

  • modify the bound value, e.g. myPet.age += 1. Only Object values can be modified this way, other values can not (they are "immutable")

  • create a new binding for it, e.g. age = 5. In this case, the old binding is lost, and the variable is not connected to the previous value anymore

This is basically all you need to know.

Related