JavaScript Symbols
Video
JavaScript Notes
JavaScript
// A symbol is a JavaScript Primitive data type
// Every symbol value returned from Symbol( ) is unique.
// A symbol may be used as an identifier for object properties; this is the datatype’s only purpose
let log = consol.log;
const s1 = Symbol( );
const s2 = Symbol(123);
const s3 = Symbol('steve');
log(s1);
log(s2);
log(s3);
log( Symbol( ) == Symbol( ) ); // will always return false, as Symbol ( ) returns a unique value
log( Symbol( ) === Symbol( ) ); // will always return false, as Symbol ( ) returns a unique value
log(typeof s2); // returns ‘symbol’
log(s3.toString()); // returns the string "Symbol('steve')"
log( Symbol.for( ) == Symbol( ) ); // false - key of Symbol will not match description of Symbol
log( Symbol.for( ) == Symbol.for( ) ); // true – key of Symbol will match key of Symbol
let s5 = Symbol.for(555); // sets key to be 555
log( Symbol.keyFor(s5) ); // returns 555, as they key for s5
// OBJECTS
let obj = { };
obj['prop1'] = 'value1';
obj['prop2'] = 'value2';
obj[Symbol( )] = 'value3';
obj['prop4'] = Symbol( );
for( let p in obj) {
log (p, obj[p]); // for in loop does not enumerate properties that are Symbols!
}
log(JSON.stringify(obj)); // does not return any property that has a Symbol as its key or value
let s4 = Symbol.for('fred');
log (s4);
let k4 = Symbol.keyFor(s4);
log(k4);
Feedback
Submit and view feedback