Getting started with JavaScriptFunctionsArraysObjectsAJAXClassesArithmetic (Math)Comparison OperationsConditionsLoopsPromisesRegular expressionsDateError HandlingGeolocationCookiesIntervals and TimeoutsGeneratorsHistoryStrict modeCustom ElementsJSONBinary DataTemplate LiteralsWeb StorageFetchScopeModulesScreenInheritanceTimestampsDestructuring assignmentWorkersVariable coercion/conversionDebuggingNotifications APIBuilt-in ConstantsWebSocketsWeb Cryptography APIAsync functions (async/await)StringsConstructor functionsexecCommand and contenteditablePerformance TipsMapCreational Design PatternsrequestAnimationFrameReserved KeywordsMethod ChainingGlobal error handling in browsersUnary OperatorsFile API, Blobs and FileReadersCommentsConsoleTail Call OptimizationDetecting browserEnumerationsSymbolsLocalizationSelection APICallbacksSetDeclarations and AssignmentsFunctional JavaScriptModals - PromptsData attributesThe Event LoopBattery Status APIData ManipulationBitwise operatorsTranspilingBOM (Browser Object Model)Unit Testing JavascriptLinters - Ensuring code qualityAutomatic Semicolon Insertion - ASIIndexedDBAnti-patternsNavigator ObjectModularization TechniquesProxySame Origin Policy & Cross-Origin CommunicationArrow Functions.postMessage() and MessageEventWeakMapWeakSetEscape SequencesBehavioral Design PatternsServer-sent eventsAsync IteratorsNamespacingEvaluating JavaScriptMemory efficiencyDate ComparisonHow to make iterator usable inside async callback functionContext (this)Setters and GettersVibration APIPrototypes, objectsDatatypes in JavascriptBitwise Operators - Real World Examples (snippets)Fluent APITilde ~Security issuesUsing javascript to get/set CSS custom variablesJavaScript VariablesEvents

WeakSet

Other topics

Remarks:

For uses of WeakSet see ECMAScript 6: what is WeakSet for?.

Creating a WeakSet object

The WeakSet object is used for storing weakly held objects in a collection. The difference from Set is that you can't store primitive values, like numbers or string. Also, references to the objects in the collection are held weakly, which means that if there is no other reference to an object stored in a WeakSet, it can be garbage collected.

The WeakSet constructor has an optional parameter, which can be any iterable object (for example an array). All of its elements will be added to the created WeakSet.

const obj1 = {},
      obj2 = {};

const weakset = new WeakSet([obj1, obj2]);

Adding a value

To add a value to a WeakSet, use the .add() method. This method is chainable.

const obj1 = {},
      obj2 = {};

const weakset = new WeakSet();
weakset.add(obj1).add(obj2);

Checking if a value exists

To check if a value exits in a WeakSet, use the .has() method.

const obj1 = {},
      obj2 = {};

const weakset = new WeakSet([obj1]);
console.log(weakset.has(obj1)); // true
console.log(weakset.has(obj2)); // false

Removing a value

To remove a value from a WeakSet, use the .delete() method. This method returns true if the value existed and has been removed, otherwise false.

const obj1 = {},
      obj2 = {};

const weakset = new WeakSet([obj1]);
console.log(weakset.delete(obj1)); // true
console.log(weakset.delete(obj2)); // false

Syntax:

  • new WeakSet([iterable]);
  • weakset.add(value);
  • weakset.has(value);
  • weakset.delete(value);

Contributors

Topic Id: 5314

Example Ids: 18903,18904,18905,18906

This site is not affiliated with any of the contributors.