Search code examples
javascriptsetstring-interpolationtemplate-literals

Javascript Set delete method syntax


In working with a new Set as opposed to a new Array, because the Set handles duplicate entries well, I struggled with the syntax passed using the delete() method. This would apply to other methods but my problem primarily pertained to the delete() method in this case.

In passing a constant to the delete() Set method the response was false even though the Set was built from the same Array data.

In outputting the set to the console the objects were as follows:

Set(12) {'10165', '122', '88', '884', '10224', …}

I was finding that if I hardcoded the object value console.log(someSet.delete('122')); the delete() method would return true and the object was successfully deleted from the Set.

However, if I referenced a constant console.log(someSet.delete(someConst.id)); the delete() method would return false even though it was the same value as the hardcoded version indicated above.

With some experimentation, the following occurred:

console.log(someSet.delete(someConst.id)); // false, value passed 122
console.log(someSet.delete("'"+someConst.id+"'")); // false, value passed '122' (same as hardcoded value)
console.log(someSet.delete('"'+someConst.id+'"')); // false, value passed "122"
console.log(someSet.delete(`'${someConst.id}'`)); // false, value passed '122' (same as hardcoded value)
console.log(someSet.delete(`${someConst.id}`)); // true, value passed 122 (different than hard coded value)

Why is it that variable interpolation with template literals (backtick) resulted in true where the direct reference to the constant resulted in false? Why is it that the hardcoded value '122' resulted in true where 122 from the interpolated var/const also resulted in true.

console.log(someSet.delete(someConst.id)); // false
console.log(someSet.delete(`${someConst.id}`)); // true

Do Set methods check data type as part of the usage even though a Set can hold any value of any data type?

Even though using interpolation for the var/const proved successful I wanted to understand why.


Solution

  • Sets use the SameValueZero algorithm to determine equality. According to this, strings and numbers are never equal (since they are of different types). Since your set is storing strings, you have to pass strings to delete.

    To convert a number to a string, you can concatenate it with an empty string, use the String function, or call .toString:

    someSet.delete('' + someConst.id);
    someSet.delete(String(someConst.id));
    someSet.delete(someConst.id.toString());