The keyword let helps in defining variables scoped to a single block.
123456789101112131415
functionaboutme(){{letgfs=10;varwife=1;}console.log(wife);console.log(gfs);}// Let's invoke aboutmeaboutme();// Would result in :1ReferenceError:gfsisnotdefined.
gfs got a ReferenceEorror as it was in a block and declared with let, syntactically similar to var, but defines a variable in the current block. The above is a simple example, but let is more useful in creating closures in loops and works better than var.
GENERATORS :
Generators helps to build iterators, yield is not a keyword in ES6 so the syntax to declare a generator function is function* (){}
Let's see an example :
12345678910111213141516
function*Counter(){varn=0;while(1<2){yieldn;++n}}varCountIter=newCounter();CountIter.next()// Would result in { value: 0, done: false }// Again CountIter.next()¬//Would result in { value: 1, done: false }
The done attribute will be true once the generator has nothing more to yield. Interestingly a generator can also yield another generator! :)
PROXIES :
Proxies provide a meta-programming API, that helps the programmer to define primitive object behaviour using traps
123456789
varlife=Proxy.create({get:function(obj,value){returnvalue==="ans"?42:"Meh! Nothing like : "+value}});life.ans// Would return 42life.lol// Would return Meh! Nothing like lol.
The above can be extended to simulating __noSuchMethod__
Object.observe provides a runtime capability to observe changes to an object.
12345678910111213141516171819202122232425
>vartodos=["eat","code","code","sleep"];// Using Array.observe>Array.observe(todos,function(changes){console.log(changes);})>todos.pop()'sleep'>[{type:'splice',object:['eat','code','code'],index:3,removed:['sleep'],addedCount:0}]>todos.push("sleep")4>[{type:'splice',object:['eat','code','code','sleep'],index:3,removed:[],addedCount:1}]// Similarly with Object.observe>varobj={}>Object.observe(obj,function(changes){console.log(changes);})>obj.name="hemanth";'hemanth'>[{type:'new',object:{name:'hemanth'},name:'name'}]
COLLECTIONS (Maps and Sets) :
Map objects are simple key/value maps, but it is different when compared to Object :
Objects have default key/value pairs from prototype.
Keys of an Object are Strings, where they can be any value for a Map.
Keeping track of size for an Object is manual, but Maps have size attribute.
Set objects let you store unique values of any type, whether primitive values or object references, but we still can't iterate them in node :(
12345678910111213141516
>Object.getOwnPropertyNames(Set.prototype)['constructor','size','add','has','delete','clear']>Object.getOwnPropertyNames(Map.prototype)['constructor','size','get','set','has','delete','clear']varmyMap=newMap();myMap.set(NaN,"not a number");myMap.get(NaN);// "not a number"varmySet=newSet();vartodos=["eat","code","sleep","code","drink","code"]todos.forEach(function(t){mySet.add(t);})todos.length// 6mySet.size// 4