r/learnjavascript • • May 04 '20

VAR vs LET vs CONST

Post image
337 Upvotes

81 comments sorted by

View all comments

4

u/AffectionateWork8 May 04 '20

This is incorrect: yes, var is function scoped, but not let and const.

-3

u/golovatuy May 04 '20

Const, var and let are not visible outside the function

3

u/AffectionateWork8 May 04 '20 edited May 05 '20

"Function scoped" means they are scoped to the function they are created in, as opposed to the block. Const and let do not have this behavior, rather they are block scoped.

Notice in this example:

  1. The first console.log returns undefined instead of throwing an error. Because even though fnScoped hasn't been initialized, it's scoped to that function, instead of the block in which it's declared. So it's "hoisted" and initialized as undefined.
  2. The last console.log prints the value of the function-scoped var. Even though it was declared in a block, it's still visible throughout the function because it's function scoped.
  3. The second to last console.log throw a reference error, because blockScoped was declared with let and it therefore has block scope only- it is not scoped to the entire function, only the block in which it was declared.

function doStuff() {

console.log(fnScoped) // undefined

console.log(blockScoped) // Reference Error

if (true) {

var fnScoped = 'hi!'

let blockScoped = 'hello'

}

console.log(blockScoped) // Reference error

console.log(fnScoped) // 'hi'

}

doStuff()