allenGKC / Just-Javascript-Reading-Notes

This is a reading notes of Just Javascript.
https://github.com/allenGKC/Just-Javascript-Reading-Notes
164 stars 56 forks source link

[Just JavaScript] 03. Values and Variables #3

Open allenGKC opened 4 years ago

allenGKC commented 4 years ago

03. Values and Variables

First look at this code:

let reaction = 'yikes';
reaction[0] = 'l';
console.log(reaction);

What is this code's output?

Here’s the answer. This code will either print "yikes" or throw an error depending on whether you are in strict mode. It will never print "likes".

Primitive Values Are Immutable

let arr = [212, 8, 506];
let str = 'hello';

console.log(arr[0]); // 212
console.log(str[0]); // "h"

arr[0] = 420;
console.log(arr); // [420, 8, 506]

str[0] = 'j'; // ???

All primitive values are immutable.

If you attempt to set a property on a primitive value, be it a number or a string or something else, JavaScript won’t let you do that. Whether it will silently refuse your request or error depends on which mode your code is running in.

image

A Contradiction?

Then look at this code:

let pet = 'Narwhal';
pet = 'The Kraken';
console.log(pet); // ?

What is this code's output?

The answer is "The Kraken". It may seem to be confusing.

Variables Are Wires

We only said it’s the primitive values that can’t change. We didn’t say anything about variables!

Variables are not values. Variables point to values.

A variable is a wire. It has two ends and a direction: it starts from a name in my code and it ends pointing at some value in my universe.

let pet = 'Narwhal';

image

There are two things I can do to a variable after that.

Assigning a Value to a Variable

pet = 'The Kraken';

image

Note that I can’t just put anything on the left side:

'war' = 'peace'; // Nope. (Try it in the console.)

The left side of an assignment must be a “wire”.

The right side of an assignment must be an expression.

Reading a Value of a Variable

Read the value of variable — for example, to log it:

console.log(pet);

But note that it is not the pet variable that we pass to console.log. We might say that colloquially, but we can’t really pass variables to functions. We pass the current value of the pet variable.

It turns out that a variable name like pet can serve as an expression too! When we write pet, we’re asking JavaScript a question: “What is the current value of pet?” To answer our question, JavaScript follows the pet’s “wire”, and gives us back the value at the end of this “wire”.

Nouns and Verbs

function double(x) {
  x = x * 2;
}

let money = 10;
double(money);
console.log(money); // ?

The answer is 10.

Putting It Together

let x = 10;
let y = x;
x = 0;

image image image

Variables always point at values.

Recap

tin80122 commented 1 year ago

Short quiz: https://eggheadio.typeform.com/to/RWJg3m?typeform-source=yu.mantoufan.com