Saturday, March 4, 2017

ES6 Symbols

Primitive types:
Number
string
object
boolean
null
undefined

7th primitive type is symbol

Symbols are unique
We can’t loop over them

  const classRoom = {
    
    'Ganesh':{grade:50, gender:'male'},
    'Bunty':{grade:60, gender:'male'},
    'Bunty':{grade:70, gender:'female'},

  };
  //Instead of doing the above, we could use symbols

  const symbolRoom = {
    
    [Symbol('Ganesh')]:{grade:50, gender:'male'},
    [Symbol('Bunty')]:{grade:60, gender:'male'},
    [Symbol('Bunty')]:{grade:70, gender:'female'},

  };

//symbols are not enumerable
 //but we can grab all the symbols contained by symbolRoom

  const syms=Object.getOwnPropertySymbols(symbolRoom);
  //syms.forEach(sym=>{console.log(sym.value)});
  //forEach doesn't work here
  //But we can map over the symbols
  //symbols here are keys for the array symbolRoom, so we can access them
  const symbolData=syms.map(sym=> symbolRoom[sym]);
  console.table(symbolData);
  //Remember that Symbol starts with a capital S!

No comments:

Post a Comment