Reputation: 1081
There is a portuguese IT company that is looking for some developers in a few areas and just out of curiosity (since I already have a job, thankfully) I went to check the job postings.
When I went to check out the JS developer posting, they provided a piece of JS code that caught my attention. I've worked for some time with JS and I find myself getting back to programming with JS from time to time but to be honest I've never seen anything even similar to the code given.
This is the code:
!(function(x){
'6D 61 6E'.split(' ').forEach(function(a){
x+=String.fromCharCode(parseInt(a,16));
});
return x;
})('');
I went and wrote this on Chrome's JS console and the output is 'false'. If I understand it correctly, the "strange" code, and according to the ASCII table reads 'm a n', and parseInt is supposed to return an integer based on a hexadecimal radix. It then gets converted once again into a string, this time based on the chars decimal value. To finish it all, we evaluate the return 'x' by "negating it" (not the word I was looking for but can't remember a better one at the time... evaluate maybe?).
Then, why is the output false? If we don't evaluate the return the result is the expected one 'man', but I don't see why we get false on this particular instance.
Anyone care to elaborate?
Upvotes: 2
Views: 180
Reputation: 150030
As you seem to have worked out,
return x;
...will return the string "man". But your question seems to boil down to why !"man"
gives false
?
From MDN, logical not !
:
Returns
false
if its single operand can be converted totrue
; otherwise, returnstrue
.
The empty string ""
is falsey, so !""
is true
, but any other string is truthy, so !"any other string"
is false
.
Upvotes: 3