0

I have this Coffeescript:

console.log 'TEST'
console.log index
console.log (index is not 0)
console.log (index > 0)
unless index is 0
    console.log "passed test"

This is the compiled Javascript:

console.log('TEST');
console.log(index);
console.log(index === !0);
console.log(index > 0);
_results.push(index !== 0 ? console.log("passed test") : void 0);

This is the console output

TEST
0
false
false
passed test
TEST
1
false
true
passed test

Question 1) Why does (index is not 0) return false when index is 1? (index > 0) returns true for 1, so why doesn't (index is not 0)?

Question 2) Why does the unless index is 0 test get passed when index is 0?

2 Answers 2

3

Why does (index is not 0) return false when index is 1? (index > 0) returns true for 1, so why doesn't (index is not 0)?

CoffeeScript doesn't use is not for inequality, it uses != and isnt. By looking at the compiled code, we can see that it's actually interpreting (index is not 0) as (index is (not 0)).

Why does the unless index is 0 test get passed when index is 0?

When I tried it myself the test did not pass. This behaviour is probably being caused by something in your testing code that you haven't included in your post.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly. Confusing is not with isnt in CoffeeScript is a common mistake.
1

This is fiddly:

console.log(index === !0);

It gets treated in the same way as:

console.log(index === (!0));

0 is a falsey constant, so you could replace (!0) with true. The real code is then:

console.log(index === true);

So it will only log "true" when index is boolean true without type coercion.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.