I've seen examples of code that uses only operators and ""
to perform complex string operations. Basically, the idea was that something like ((+"+")+"")[+""]
gives you a letter N
, etc. I forgot where I found it, and I'm having no luck finding proper google keywords. Does anyone have a link at hand?
Asked
Active
Viewed 244 times
1

georg
- 211,518
- 52
- 313
- 390
1 Answers
6
Basically there are two main concepts used here:
- making a
Number
out of string, i.e.Number(str)
, which shortcut is+str
; - stringifying numeric values, i.e.
String(n)
, which shortcut isn+""
.
Hence, if we look at the expression thoroughly, we'll see:
+"+" === NaN
NaN + "" === "NaN"
+"" === 0
"NaN"[0] === "N"
There are a lot of things you can do in JavaScript in the same way. One funny example is provided in the following question: What are JavaScript's builtin strings?
-
+1 Following the same two concepts, there is a crappy IE 6-7-8 detection script that goes like that : `if(!+"\v1")`, Javascript interpreter will always try to do something before giving up, which can be a mess on other browsers unless you really know what you're doing. – Frederik.L Apr 29 '13 at 08:04
-
Yes, I knew it was somewhere on SO. Thanks a lot! – georg Apr 29 '13 at 10:23