[Javascript] The hidden transform in Javascript

[] + []

Answer: ""

Both arrays ([]) are first converted to their string representations before the + operator is applied. In JavaScript, arrays are converted to strings by concatenating their elements with commas in between. Since the arrays are empty, their string representations are empty as well.

 

[] + ![]

Answer: "false"

  • ![] is evaluated first:

    • In JavaScript, [] (an empty array) is truthy, so ![] evaluates to false.
  • Now the expression becomes [] + false:

    • The + operator, when used with an array and a non-array value, coerces both operands to strings.
    • [] (empty array) is coerced to an empty string "".
    • false is coerced to the string "false".
  • String concatenation:

    • "" + "false" results in "false".

 

Object to primitive

Let's go deep to understand why is so in low level

obj + obj = ?

When javascript see +operator, it will first convert Object to primitive type, it follow rules:

First, will check whether has [Symbol.toPrimitive]: fn ()

const obj = {
  [Symbol.toPrimitive]: function () {
     return 'wef' // here return value has to be a primitive type, if you return {},[], it will throw error
  }
}

console.log(obj + 1) // wef1

 

If we don't have [Symbol.toPrimitive], then it will check valueOf()

const obj = {
  valueOf() {
    return 'wef' // has to be primitive value
  }
}

console.log(obj + 1) // wef1

 

Lastly we check against toString()

const obj = {
  valueOf() {
    return {} // won't throw error, but also it won't be able to convert to primitive
  },
  toString() {
    return "wef"
  }
}

console.log(obj + 1) // wef1

 

If all of those do not exist, then it throw TypeError: Cannot convert object to primitive value

 

Now let's back to the question and try again

[][Symbol.toPrimitive] // undefined
[].valueOf() // [], not a primitive
[].toString() // ''
[1,2,3].toString() // '1,2,3'

[] + [] // '' + '' = ''

 

But ![] is different! It not doing object to primitive convertion, it's doing boolean check. And ![] is false

[] + ![] // '' + false = 'false'

For boolean check, those values are consdiered as falsey value

null, undefined, 0, NaN, false, ""

 

posted @   Zhentiw  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-10-10 [Typescript] Type and Interface for performance
2022-10-10 [Typescript] Tips: Create autocomplete helper which allows for arbitrary values
2022-10-10 [Typescript] Tips: DeepPartial
2019-10-10 [Svelte 3] Use Svelte 3 transitions to gracefully show and hide DOM elements
2019-10-10 [TypeScript ] Using the Null Coalescing operator with TypeScript 3.7
2019-10-10 [TypeScript] Optional Chaining with TypeScript 3.7
2019-10-10 [Flutter] Custom a Slider with SliderTheme
点击右上角即可分享
微信分享提示