3 ms·
Not sure what js shell he uses, since it is an old video but in browser or node you will get predictable results for his examples. What you need to know that i
by vasergen 4y ago
Not sure what js shell he uses, since it is an old video but in browser or node you will get predictable results for his examples.
What you need to know that in js '+' sign will add numbers only if both operands are numbers, otherwise it will coerce both to string type, which is true for {} or []. To convert to string js will use '.toString()' method like this {}.toString() and [].toString(). Now {}.toString() is equal to a string '[object Object]' and [].toString() is equal to an empty string '' (for non empty arrays it will print numbers separated by comma). So if we add anything in JS and on both sides are not numbers we actually add strings! And adding strings means concatenation and it works as you would expect, just put two strings together.
Having that, let's take a look on those examples again
1. [] + {} equal to '[object Object]'
2. {} + [] equal to '[object Object]'
3. {} + {} equal to '[object Object][object Object]'
So no 'magic' involved there. Note that some results are different as in the video, you can check it in console in your browser
UPD: typo
- crdrost 4y agoNone of the behaviors mentioned in the video have changed; they are all pinned down by ECMAScript standards and to change them would be a breaking change to the internet. The behavior of your console might be slightly different from the behavior of his console, but there are still many reasonable ways to replicate his results. See my comment below if you're still unsure about this point.
- threatofrain 4y agoI'm getting inconsistent results in Node (19.8), Deno (v8 11.2), Chrome (112), Safari (16.4).
- vasergen 4y ago> but there are still many reasonable ways to replicate his results But can you replicate his results for js in any modern browser or node environment? I agree that standards are fixed, but there is definitely a difference between implementation of those standards in different environments
- crdrost 4y agoYes. It is very easy to replicate his results for JS in every modern browser and Node.js environment, because these results are part of the ECMAScript standard and can never ever ever ever be changed. Again, if you are unsure about this point, please read the other comments I have left in these conversational threads. (Just to be clear, I'm not saying any of this to jump on a bashing-JS train. Think of e.g. the abiding love of having been married for 20+ years, it's not like your spouse has no sandpapery parts or faults, we can healthily admit them to each other at this point -- I just have learned not to rub against them.)
- deleted 4y ago[deleted]