JavaScript weakMap.has() Method

Below is the example of weakMap.has() method.

  • Example:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script> 
        function gfg() { 
    const weakmap = new WeakMap(); 
    const key = {}; 
    weakmap.set(key, 'gfg'); 
      
    document.write(weakmap.has(key)); 
        
        gfg(); 
    </script> 

    chevron_right

    
    

  • Output:
    true

The weakMap.has() is an inbuilt function in JavaScript which is used to return a boolean value which indicates whether an element with a particular key presents in the weakmap object or not.

Syntax:

weakMap.has(key);

Parameters: It accepts a parameter ‘key’ which is the key of the element which is going to be tested for presence in the object weakmap.

Return values: It returns true if the element with the specified key is present in the weakmap object otherwise it returns false.



Example:

Input: weakmap1.has(key1)
Output: true

JavaScripts to show the working of this function:
Code #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
  
   // Creating a WeakMap() object
   const weakmap1 = new WeakMap();
     
   // Creating a key "key1"
   const key1 = {};
     
   // setting element 'gfg' to the key "key1"
   weakmap1.set(key1, 'gfg');
     
   // Testing whether the key is present 
   // in the weakMap() object or not
   document.write(weakmap1.has(key1));
  
</script>

chevron_right


Output:

true

Code #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
  
   // Creating a WeakMap() object
   const weakmap1 = new WeakMap();
     
   // Creating a key "key1"
   const key1 = {};
     
   // Testing whether the key is present 
   // in the weakMap() object or not
   document.write(weakmap1.has(key1));
  
</script>

chevron_right


Output:

false

Here output is false because the key “key1” has not been set at the end of the weakMap object.

Supported Browsers:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Apple Safari
  • Opera

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.