Created
August 12, 2017 03:34
-
-
Save f1yn/df82fa927178dc92a3c22f25e2971f41 to your computer and use it in GitHub Desktop.
Proper usage of the let keyword
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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