Languages
[Edit]
EN

JavaScript - add value to Set and return true on success or false on fail

3 points
Created by:
Aston-Freeman
787

In this article, we would like to show you how to add value to Set and return true on success or false on fail in JavaScript.

Quick solution:

 

Practical examples

Edit

1. Using size accessor

Edit

In this example, we check the set size before and after adding a value to it. If the sizes are the same, it means the element hasn't been added and the function returns false, otherwise returns true.

 

2. Using has() method

Edit

In this example, we use has() method to check whether an element with the specified value exists in a Set object. If the value exist, it means the element can't be added and the function returns false, otherwise returns true.

 

References

Edit
  1. Set.prototype.size - JavaScript | MDN
  2. Set.prototype.has() - JavaScript | MDN

Alternative titles

  1. JavaScript - add value to Set and return bool
  2. JavaScript - add value to Set and return boolean
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join