Search code examples
javascriptvarlet

let vs var in the global scope


Why this will print the names as expected:

var firstName = 'Charlie',
    lastName  = "Brown"

function showFullName() {
    console.log(this.firstName+' '+this.lastName);
}

window.showFullName();

but, if I replace 'var' for 'let', I will get 'undefined' for both firstName & lastName?

I also see that the variables declared using 'var' get attached to the window Object, but the ones declare using 'let'.

Appreciate the help.


Solution

  • Let allows to declare variables which are limited to a particular scope, can be block or expression. Where as var is used for global or local declaration. We can use var instead of let but the reverse fails.