Skip to content

Instantly share code, notes, and snippets.

@f1yn
Created August 12, 2017 03:34
Show Gist options
  • Select an option

  • Save f1yn/df82fa927178dc92a3c22f25e2971f41 to your computer and use it in GitHub Desktop.

Select an option

Save f1yn/df82fa927178dc92a3c22f25e2971f41 to your computer and use it in GitHub Desktop.
Proper usage of the let keyword
// proper let usage
function properLetExample(){
let checked = Math.random() * 10;
if (checked > 5){
let name = 'bob marley';
console.log('name:', name); // should output 'name: bob marley
} else {
console.log('nobody is home');
}
console.log(typeof name); // should be undefined
}
// improper usage of let iterative (really bad performance)
function badIterativeExample(){
let checked = Math.random() * 10;
if (checked > 5){
let i = 10; // this is a proper let
// only anchored to the scope of the check
while (i--){
let name = new Array(i + 1).join('bob '); // improper
// because we recreate/declare name each loop, the V8 engine
// is forced to optimize this code while performing extra checks
console.log(name + 'marley');
// should output 'bob' i # of times, and then marley
}
} else {
console.log('nobody is home');
}
console.log(typeof name); // should be undefined
}
// proper usage of let iterative (better performance)
function goodIterativeExample(){
let checked = Math.random() * 10;
if (checked > 5){
let i = 10, // proper use of let
name; // (only exists within block)
while (i--){
name = new Array(i + 1).join('bob ');
// name already points to a memory location,
// so checking/recreation isn't required.
console.log(name + 'marley');
// should output 'bob' i # of times and then marley
}
} else {
console.log('nobody is home');
}
console.log(typeof name); // should be undefined
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment