JS Reminder 1 Data type, let vs var, hoisting

Youngmin Park
3 min readJan 4, 2021

Variable

1. let (added in ES 6)

you can declare ‘park’ to variable name → park is printed on console.

then declare ‘hello’ to variable name → hello is printed on console.

block scope

block scope

but if you use block scope, name is no longer printed.

Global scope

global scope

if you declare ‘global name’ to variable globalName outside of block scope, it will be printed either inside of block and also outside of block.

2. var

but you should not use var

here are some example

var age is on the last line which mean age was not defined on first line but it still didn’t print error but undefined.

after define age = 4, it will print 4 on the console.

if you do this same with ‘let’

it shows error said cannot access ‘name’ before initialization.

Therefore if we use ‘var’ it will really hard to find error. you should use ‘let’ instead of ‘var’ from ES6

Hoisting

like I said earlier, var declared on line 19, but use it on line 18 before declared.

this is called ‘Hoisting’

according to digitalocean.com

if we console.log(age) the very top on line 1

it will print undefined on very top of console.

so it move declaration from bottom to top.

and there is another reason you should not use ‘var’ is

‘var’ has not block scope unlike ‘let’

var age is declared inside of block, but cosole.log(age) on line 22 will be printed ‘4’ on the console.

Just use ‘let’. don’t ever use ‘var’

3. Constants

unlike ‘let’ const is immutable(let is mutable)

There are few reasons to use ‘const’ instead of ‘let’

once you declared variable with const, you can’t redeclared.

In short, use always ‘let’ except when you need to fix some variable value.

thank you

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Youngmin Park
Youngmin Park

No responses yet

Write a response