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:

const set = new Set();

if (set.size !== (set.add('Some value ...'), set.size)) {
    console.log('Some value added!');
}

 

Practical examples

1. Using size accessor

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.

// ONLINE-RUNNER:browser;

const addValue = (set, value) => set.size !== (set.add(value), set.size);


// Usage example:

const set = new Set();

console.log(addValue(set, 'a'));  // true
console.log(addValue(set, 'a'));  // false
console.log(addValue(set, 'b'));  // true
console.log(addValue(set, 'c'));  // true

 

2. Using has() method

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.

// ONLINE-RUNNER:browser;

const addValue = (set, value) => set.has(value) ? false : (set.add(value), true);
// or: const addValue = (set, value) => !set.has(value) && (set.add(value), true);


// Usage example:

const set = new Set();

console.log(addValue(set, 'a'));  // false
console.log(addValue(set, 'a'));  // true
console.log(addValue(set, 'b'));  // false
console.log(addValue(set, 'c'));  // false

 

References

  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
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