To clarify the situation, I conducted a simple test, and below is a runnable code snippet:

function test() {
    const str = 'abcdef';
    alert(Array.prototype.reduce.call(str, (result, _, i, _str) => {
        if(!i) result.push(`typeof str: ${typeof str}`);
        else if(i === 1) result.push(`typeof _str: ${typeof _str}`);
        else if(i === 2) result.push(`_str == str: ${_str == str}`);
        else if(i === 3) result.push(`_str === str: ${_str === str}`);
        else if(i === 4) result.push(`str: "${str}", _str: "${_str}"`);
        else result.push(`_str instanceof String: ${_str instanceof String}`);
        return result;
    }, []).join('\n'));
}
<button onclick="test()">Click me to run the test!</button>

The test showed the result I didn't expected: _str is an object and str is a string primitive, they are not equal if checked with === – however, if to join them to another string, both result in "abcd". I often call Array.prorotype functions (mostly – forEach) upon strings and till recently was sure that it is a much better option in terms of performance, than e.g. [...str].forEach or [...str].reduce, because calling does not convert a string to an array, but, as turned out to be, the string is converted under the hood to some object! Am I missing something?

UPD: this mysterious _str object is an instance of String.

0

There are 0 best solutions below