# javascript: var vs. let ## var * function scope * hosting: var variables will be initialized with undefined before the code is run ```javascript= function checkVar(){ var foo = "foo"; console.log("foo:", foo); // foo: foo // it can work, because dog is in checkVar function scope and hosting reason console.log("dog:", dog); // dog: undefined if(true){ var dog = "dog"; } // it can work, because dog is in checkVar function scope console.log("dog:", dog); // dog: dog // it can work, because of hosting console.log("bar:", bar); // bar: undefined var bar = "bar"; } checkVar() // foo: foo // dog: undefined // dog: dog // bar: undefined try{ // it cannot work, because it is out of function scope console.log(foo); // error } catch { console.log('not find foo'); } // not find foo ``` ## let * block scope * cannot be hosted (let variables are not initialized until their definition is evaluated) ```javascript= function checkLet(){ let foo = "foo"; console.log("foo:", foo); // foo: foo if(true){ let dog = "dog"; // it can work, because it is in the same block scope console.log("foo:", foo); // foo: foo } try{ // it cannot work, because it is out of block scope console.log("dog:", dog); // error } catch { console.log('not find dog'); } try{ // let cannot be hosted console.log("bar:", bar); // error let bar = "bar"; } catch { console.log('not find bar'); } } checkLet() // foo: foo // foo: foo // not find dog // not find bar try{ // it cannot work, because it is out of block scope console.log(foo); // error } catch { console.log('not find foo'); } // not find foo ```