Skip to content

Instantly share code, notes, and snippets.

@mheiber
Last active February 19, 2016 01:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mheiber/305b9d480cabc2881c79 to your computer and use it in GitHub Desktop.
Save mheiber/305b9d480cabc2881c79 to your computer and use it in GitHub Desktop.

Symbols

What

  • Like strings or UIDs, but guaranteed to be unique
  • (almost) private
  • low usefulness-to-comprehensibility ratio

Symbols have nothing to do with Ruby symbols (:ruby_symbol)

How

Create symbols (don't use new!)

Symbol() === Symbol() // false

You can associate a symbol with a string for debugging purposes

Symbol('foo') === Symbol('foo') // false
console.log(Symbol('foo')) // "Symbol('foo')"

Why

One use case: Use like private properties for encapsulation

const privateMethodKey = Symbol('privateMethod')

class Foo {
	constructor(){
		
		this[privateMethodKey] = () => 42
	}
	sayHello(){
		console.log('hi')
	}
}

Quiz

What will this code print?

const foo = new Foo()
const newSymbol = Symbol('privateMethodKey')

console.log(Object.keys(foo))
console.log(foo[newSymbol])
console.log(foo[privateMethodKey])

Other Uses:

  • used internally in JS (example: Symbol.iterator)
  • use like enums
  • monkey patching
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment