var and let the difference in JavaScript

Javascrit has something called Hoisting. This is when all variables and functions are loaded before the program runs.

function loadProfiles(userNames){
// some code...

    var loadingMessage = "Hold a sec... Profiles loading!";
// some code...
}

var loadingMessage = "Loading your profile!";

What will happen here is that the first declaration of loadingMessage will be loaded first,then the second declaration will be loaded and overwrite the first. Which will not give us what we want.
To solve this issue ES6 or ES2015 came with a solution: let !

function loadProfiles(userNames){
// some code...

    let loadingMessage = "Hold a sec... Profiles loading!";
//some code...

}

let loadingMessage = "Loading your profile!";

These variables will load locally, saving memory without overwriting each other. If you console.log the loadingMessage variable after the loadProfiles method, the result will be different from if you ran inside the loadProfiles scope.
What is a scope? I’ll tell you later.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s