Created
February 16, 2023 17:13
-
-
Save prof3ssorSt3v3/602b498ad96d14cad9e9495359019c30 to your computer and use it in GitHub Desktop.
Code from video about Weak References, WeakSet, and WeakMap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const log = console.log; | |
//Strong Ref and Reachability - the default state | |
let person = { id: 123, name: 'Shaggy' }; | |
let list = [person]; | |
person = null; //destroys one reference | |
//person list[0] | |
// log(list); | |
// log(person); | |
//Set - unique list of values, any datatype, strong ref | |
//WeakSet - values must be objects, no loop, weak ref | |
let kids = new WeakSet(); | |
let son = { name: 'Alex' }; | |
let daughter = { name: 'Bree' }; | |
kids.add(son); | |
kids.add(daughter); | |
// log('has son', kids.has(son)); | |
// log('has daughter', kids.has(daughter)); | |
son = null; | |
// log('has son', kids.has(son)); | |
// log('has daughter', kids.has(daughter)); | |
//Map - key value pairs, unique, keys are objs, remembers order | |
//WeakMap - no looping, weak ref | |
let theGang = new WeakMap(); | |
let fred = { id: 123, gender: 'male' }; | |
let daphne = { id: 456, gender: 'female' }; | |
let velma = { id: 789, gender: 'female' }; | |
theGang.set(fred, 'blue'); | |
theGang.set(daphne, 'purple'); | |
theGang.set(velma, 'orange'); | |
log(theGang.has(fred)); | |
log(theGang.has(daphne)); | |
log(theGang.has(velma)); | |
let scooby = fred; | |
daphne = null; | |
fred = null; | |
log(theGang.has(fred)); | |
log(theGang.has(scooby)); | |
log(theGang.has(daphne)); | |
log(theGang.has(velma)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment