All language subtitles for 8. Variable Environment Hoisting and The TDZ

af Afrikaans
ak Akan
sq Albanian
am Amharic
ar Arabic
hy Armenian
az Azerbaijani
eu Basque
be Belarusian
bem Bemba
bn Bengali
bh Bihari
bs Bosnian
br Breton
bg Bulgarian
km Cambodian
ca Catalan
ceb Cebuano
chr Cherokee
ny Chichewa
zh-CN Chinese (Simplified)
zh-TW Chinese (Traditional)
co Corsican
hr Croatian
cs Czech
da Danish
nl Dutch
en English
eo Esperanto
et Estonian
ee Ewe
fo Faroese
tl Filipino
fi Finnish
fr French
fy Frisian
gaa Ga
gl Galician
ka Georgian
de German
el Greek
gn Guarani
gu Gujarati
ht Haitian Creole
ha Hausa
haw Hawaiian
iw Hebrew
hi Hindi
hmn Hmong
hu Hungarian
is Icelandic
ig Igbo
id Indonesian
ia Interlingua
ga Irish
it Italian
ja Japanese
jw Javanese
kn Kannada
kk Kazakh
rw Kinyarwanda
rn Kirundi
kg Kongo
ko Korean
kri Krio (Sierra Leone)
ku Kurdish
ckb Kurdish (Soranรฎ)
ky Kyrgyz
lo Laothian
la Latin
lv Latvian
ln Lingala
lt Lithuanian
loz Lozi
lg Luganda
ach Luo
lb Luxembourgish
mk Macedonian
mg Malagasy
ms Malay
ml Malayalam
mt Maltese
mi Maori
mr Marathi
mfe Mauritian Creole
mo Moldavian
mn Mongolian
my Myanmar (Burmese)
sr-ME Montenegrin
ne Nepali
pcm Nigerian Pidgin
nso Northern Sotho
no Norwegian
nn Norwegian (Nynorsk)
oc Occitan
or Oriya
om Oromo
ps Pashto
pl Polish
pt-BR Portuguese (Brazil)
pt Portuguese (Portugal)
pa Punjabi
qu Quechua
ro Romanian
rm Romansh
nyn Runyakitara
ru Russian
sm Samoan
gd Scots Gaelic
sr Serbian
sh Serbo-Croatian
st Sesotho
tn Setswana
crs Seychellois Creole
sn Shona
sd Sindhi
si Sinhalese
sk Slovak
sl Slovenian
so Somali
es Spanish
es-419 Spanish (Latin American)
su Sundanese
sw Swahili
sv Swedish
tg Tajik
ta Tamil
tt Tatar
te Telugu
th Thai
ti Tigrinya
to Tonga
lua Tshiluba
tum Tumbuka
tr Turkish
tk Turkmen
tw Twi
ug Uighur
uk Ukrainian
ur Urdu
uz Uzbek
vi Vietnamese
cy Welsh
wo Wolof
xh Xhosa
yi Yiddish
yo Yoruba
zu Zulu

Original subtitles

1 1

The next topic we need to talk about 2

2

is a very misunderstood concept in JavaScript 3

3

and that is hoisting. 4

4

So we learned that an execution context 5

5

always contains three parts. 6

6

A variable environment, 7

7

the scope chain in the current context, 8

8

and the disk keyword. 9

9

We already learned about the scope chain 10

10

and so now it's time to take a closer look 11

11

at the variable environment 12

12

and in particular at how variables 13

13

are actually created in JavaScript. 14

14

So in JavaScript 15

15

we have a mechanism called hoisting. 16

16

And hoisting basically make 17

17

some types of variables accessible, 18

18

or let's say usable in the code 19

19

before they are actually declared in the code. 20

20

Now, many people simply define hoisting 21

21

by saying that variables are magically lifted 22

22

or moved to the top of their scope 23

23

for example, to the top of a function. 24

24

And that is actually what hoisting 25

25

looks like on the surface. 26

26

But behind the scenes 27

27

that's in fact not what happens. 28

28

Instead, behind the scenes 29

29

the code is basically scanned 30

30

for variable declarations before it is executed. 31

31

So this happens during the so-called 32

32

creation phase of the execution context 33

33

that we talked about before. 34

34

Then for each variable that is found in the code, 35

35

a new property is created 36

36

in a variable environment object. 37

37

And that's how hoisting really works. 38

38

Now, hoisting does not work the same 39

39

for all variable types. 40

40

And so let's analyze the way hosting works 41

41

for function declarations, 42

42

variables defined with var 43

43

variables defined with let or const 44

44

and function expressions, 45

45

and also arrow functions. 46

46

So function declarations are actually hoisted 47

47

and the initial value in the variable environment 48

48

is set to the actual function. 49

49

So in practice, what this means 50

50

is that we can use function declarations 51

51

before they are actually declared in the code, 52

52

again, because they are stored 53

53

in the variable environment object, 54

54

even before the code starts executing. 55

55

And I actually told you before 56

56

that function declarations work this way, 57

57

but now you understand why. 58

58

It is because of hoisting. 59

59

And just to make this table a bit more complete 60

60

so that it serves as a nice overview for you, 61

61

I also show here that function declarations 62

62

are block scoped as we learned before. 63

63

Just keep in mind that this is only true 64

64

for strict mode. 65

65

So if you're using a sloppy mode, 66

66

which you shouldn't , 67

67

then functions are functioned sculpt. 68

68

Next, variables declared with var 69

69

are also hoisted, but hoisting works 70

70

in a different way here. 71

71

So unlike functions, 72

72

when we try to access a var variable 73

73

before it's declared in a code, 74

74

we don't get the declared value 75

75

but we get undefined. 76

76

And this is a really weird behavior for beginners. 77

77

You might expect that you simply get an error 78

78

when using a variable before declaring it 79

79

or to get the actual value. 80

80

But not to get undefined 81

81

because getting undefined is just really weird 82

82

and it's not really useful either, right? 83

83

And actually this behavior 84

84

is a common source of bugs in JavaScript. 85

85

So this is one of the main reasons 86

86

why in modern JavaScript 87

87

we almost never use var. 88

88

Now on the other hand, 89

89

let and const variables are not hoisted. 90

90

I mean, technically they are actually hoisted 91

91

but their value is basically set to an initialized. 92

92

So there is no value to work with at all. 93

93

And so in practice, it is as if hoisting 94

94

was not happening at all. 95

95

Instead, we say that these variables 96

96

are placed in a so-called Temporal Dead Zone or TDZ 97

97

which makes it so that we can't access the variables 98

98

between the beginning of the scope 99

99

and to place where the variables are declared. 100

100

So as a consequence, 101

101

if we attempt to use a let or const variable 102

102

before it's declared, we get an error. 103

103

Also keep in mind that let and const are block scoped. 104

104

So they exist only in the block 105

105

in which they were created. 106

106

And all these factors together 107

107

is basically the reason why let and const 108

108

were first introduced into the language, 109

109

and why we use them now instead of var 110

110

in modern JavaScript. 111

111

Okay. 112

112

But now what about function expressions 113

113

and arrow functions? 114

114

How does hoisting work for this? 115

115

Well, it depends if they were created 116

116

using var or const or let. 117

117

Because keep in mind that these functions 118

118

are simply variables. 119

119

And so they behave the exact same way 120

120

as variables in regard to hoisting. 121

121

This means that a function expression 122

122

or arrow function created with var 123

123

is hoisted to undefined. 124

124

But if created with let or const, 125

125

it's not usable before it's declared in a code 126

126

because of the Temporal Dead Zone 127

127

so again, just like normal variables, right? 128

128

And this is actually the reason why I told you earlier 129

129

that we cannot use function expressions 130

130

before we write them in the code, 131

131

unlike function declarations. 132

132

Okay. 133

133

But now before finishing, 134

134

let's take a more detailed look 135

135

at this mysterious Temporal Dead Zone. 136

136

So in this example code 137

137

we're gonna look at the job variable. 138

138

It is a const so it's scoped only to this if block 139

139

and it's gonna be accessible 140

140

starting from the line where it's defined. 141

141

Why? 142

142

Well, because there is this Temporal Dead Zone 143

143

for the job variable. 144

144

It's basically the region of the scope 145

145

in which the variable is defined, 146

146

but can't be used in any way. 147

147

So it is as if the variable didn't even exist. 148

148

Now, if we still tried to access the variable 149

149

while in the TDZ like we actually 150

150

do in the first line of this if block, 151

151

then we get a reference error 152

152

telling us that we can't access job 153

153

before initialization. 154

154

So exactly as we learned 155

155

in the last slide, right? 156

156

However, if we tried to access a variable 157

157

that was actually never even created, 158

158

like in the last line here 159

159

where we want to log x, 160

160

then we get a different error message 161

161

saying that x is not defined at all. 162

162

What this means is that job is 163

163

in fact in the Temporal Dead Zone 164

164

where it is still initialized, 165

165

but the engine knows that it will 166

166

eventually be initialized 167

167

because it already read the code before 168

168

and set the job variable in the variable environment 169

169

to uninitialized. 170

170

Then when the execution reaches the line 171

171

where the variable is declared, 172

172

it is removed from the Temporal Dead Zone 173

173

and it's then safe to use. 174

174

So to recap, basically each and every 175

175

let and const variable get their own 176

176

Temporal Dead Zone that starts 177

177

at the beginning of the scope 178

178

until the line where it is defined. 179

179

And the variable is only safe to use 180

180

after the TDZ, 181

181

so the Temporal Dead Zone. 182

182

Alright, now what is actually the need 183

183

for JavaScript to have a Temporal Dead Zone? 184

184

Well, the main reason that the TDZ 185

185

was introduced in ES6 is that 186

186

the behavior I described before 187

187

makes it way easier to avoid and catch errors. 188

188

Because using a variable that is set to undefined 189

189

before it's actually declared 190

190

can cause serious bugs 191

191

which might be hard to find. 192

192

And I will show you a small example 193

193

in the next lecture. 194

194

So accessing variables before declaration 195

195

is bad practice and should be avoided. 196

196

And the best way to avoid it 197

197

is by simply getting an error 198

198

when we attempt to do so. 199

199

And that's exactly what a Temporal Dead Zone does. 200

200

A second and smaller reason why the TDZ exists 201

201

is to make const variables 202

202

actually work the way they are supposed to. 203

203

So as you know, we can't reassign const variables. 204

204

So it will not be possible 205

205

to set them to undefined first 206

206

and then assign their real value later. 207

207

Const should never be reassigned. 208

208

And so it's only assigned when execution 209

209

actually reaches the declaration. 210

210

And that makes it impossible 211

211

to use the variable before. 212

212

Okay? Makes sense? 213

213

Now, if hoisting creates so many problems, 214

214

why does it exist in the first place? 215

215

I get this question all the time. 216

216

And so let's quickly talk about that here. 217

217

So the creator of JavaScript basically 218

218

implemented hoisting 219

219

so that we can use function declarations 220

220

before we use them. 221

221

Because this is essential 222

222

for some programming techniques, 223

223

such as mutual recursion. 224

224

Some people also think that it makes code 225

225

a lot more readable. 226

226

Now, the fact that it also works for var declarations 227

227

is because that was the only way hoisting 228

228

could be implemented at the time. 229

229

So the hoisting of var variables 230

230

is basically just a byproduct 231

231

of hoisting functions. 232

232

And it probably seemed like a good idea 233

233

to simply set variables to undefined, 234

234

which in hindsight is not really that great. 235

235

But we need to remember that JavaScript 236

236

was never intended to become the huge 237

237

programming language that it is today. 238

238

Also, we can't remove this feature 239

239

from the language now. 240

240

And so we just use let and const to work around this. 241

241

Alright, great. 242

242

And with all that being said, 243

243

let's now work on some practical hoisting examples.

Can't find what you're looking for?
Get subtitles in any language from opensubtitles.com, and translate them here.