Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jamiebuilds
Last active June 6, 2018 18:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamiebuilds/bc3ed59479f28cd743e59d97ae19e5b2 to your computer and use it in GitHub Desktop.
Save jamiebuilds/bc3ed59479f28cd743e59d97ae19e5b2 to your computer and use it in GitHub Desktop.

Symbols

Syntax

let obj = {
  [Symbol('foo')]: 'hello!',
};

class Obj {
  [Symbol('foo')]() {
    // ...
  }
}

Symbol(), Symbol.*, Symbol.for()

Symbol('iterator') !== Symbol.iterator;
Symbol('iterator') !== Symbol('iterator');
Symbol.for('iterator') === Symbol.for('iterator');

Object.keys()

let obj = {
  [Symbol('foo')]: 1,
  bar: 2
};
Object.keys(obj); // ['bar'] (no symbols)

Object.getOwnPropertySymbols()

let obj = { [Symbol('foo')]: 'hello!' };
let symbols = Object.getOwnPropertySymbols(obj); // [Symbol(foo)]
console.log(obj[symbols[0]]); // logs: 'hello!'

Protocols

class Graph {
  constructor() {
    this.nodes = new Map();
  }
  
  // ...
  
  [Symbol.iterator]() {
    return this.nodes.entries();
  }
}

let graph = new Graph();
// ...

for (let [node, lines] of graph) {
  // ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment