Skip to content

Variables — let and const

JavaScript Lesson 2 2:20 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
A variable is a box with a name on it. 变量就是一个贴着名字的盒子。
This line makes a box called city and puts the word Cairo into the box. 这一行做了一个叫 city 的盒子, 把 Cairo 这个词放进盒子里。
Notice the word at the front — const — which is how you make one in JavaScript. 注意最前面那个词——const—— 在 JavaScript 里就是用它来创建变量的。
From then on the name stands for whatever is inside, so when you use the name on the next line, the console prints Cairo without the word ever appearing there. 从此以后这个名字就代表盒子里的东西,所以下一行用这个名字时, 控制台打印出 Cairo,而那一行里根本没有出现这个词。
There are two words for making a variable, and choosing between them says something useful. 创建变量有两个词,选哪一个本身就说明了一件有用的事。
A const cannot be given a new value later — try it and the program stops with a TypeError. const 之后不能被赋予新值——试一下,程序会以 TypeError 停下来。
A let can be reassigned as often as you like. let 则可以想重新赋值多少次就多少次。
So the habit worth building is const first, and let only when you know the value has to move. 所以值得养成的习惯是:默认用 const,只有当你确定这个值必须变化时才用 let。
Then anyone reading your code can tell which is which at a glance. 这样任何读你代码的人一眼就能分清哪个是哪个。
This line looks strange the first time: total equals total plus five. 这一行第一次看会觉得奇怪:total = total + 5。
As mathematics it is nonsense — but it is not mathematics, it is an instruction, and it happens in three steps. 作为数学式它是说不通的——但它不是数学,而是一条指令,而且分三步发生。
Read the old value, ten. 先读出旧的值,10。
Work the sum out, fifteen. 再算出这个和,15。
Store it back under the same name. 最后把它存回同一个名字下面。
The right-hand side is always finished before anything is stored, which is why the line makes sense. 右边总是先算完,然后才存进去,所以这一行才讲得通。
Now the lesson's second task: a rectangle four wide and three high, and you want the area. 现在做课程里的第二道题:一个宽 4、高 3 的长方形,你要求它的面积。
Name the two measurements first, one variable each. 先给两个量各取一个变量名。
Then multiply them and name the result as well — area equals w times h. 然后把它们相乘,并且也给结果取个名字—— area = w * h。
That last line reads exactly like the formula, which is the point of naming things. 最后那一行读起来就和公式一模一样, 而这正是给东西取名字的意义。
Log it, and the console shows twelve. 把它打印出来,控制台显示 12。
Four things to take with you. 带走四点。
One: const, a name, equals, a value — that names a value. 第一:const、名字、等号、值——这样就给一个值取了名字。
Two: a const cannot be given a new value afterwards. 第二:const 之后不能再被赋予新值。
Three: use let when the value really must change, like a running total. 第三:当这个值确实需要改变时才用 let,比如一个累计的总数。
Four: in any assignment the right side is worked out, then stored into the name on the left. 第四:任何赋值都是先算完右边,再存进左边的名字里。
Now do the three tasks; the third one updates a let. 现在去做那三道题;第三题要更新一个 let。

Log in or create account

IGCSE, A-Level & AP