0

I have this code in typescript:

console.log ('collection[0]  -> ' + collection[0] );
console.log ('collection[0] !== null -> ' + collection[0] !== null);

but this is the result on the console:

console.log src/services/service.ts:122
  collection[0]  -> null
console.log src/services/service.ts:123
  true

4 Answers 4

1

I bet your collection[0] is a string containing 'null', not the primitive value null. Try:

console.log (collection[0] !== 'null');

It could also be an object that results in 'null' when cast to string:

const item = collection[0];
const isWeirdNullObj = typeof item === 'object' && item !== null && String(item) === 'null';

This could happen with something like the following:

const item = {
  valueOf() {
    return 'null';
  }
};
console.log('item is ' + item);
console.log(typeof item);

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

5 Comments

same result :-)
Check its type: typeof collection[0]
typeof collection[0] -> object
Guess it's an object that results in 'null' when cast to string. Pretty weird
Did this actually solve the problem? I think my answer is wrong, and that the other answer is right
1

Addition operator has precedence over the equality operator.

So, in your code the addition operation is being evaluated first. Try the following :-

console.log ('collection[0] !== null -> ' + (collection[0] !== null));

Comments

0

You have been burned by JavaScript's type coercion. The + operator in JS has a lot of operations associated with it. I suggest you don't concat with it and string interpolate instead.

console.log(`collection[0] !== null -> ${collection[0] !== null}`);

Your other option is to separate out the two operations with a comma. console.log can take an arbitrary number of arguments and combines them for you

console.log ('collection[0] !== null -> ', collection[0] !== null);

Comments

0

Use , instead of + if you want to log some variable:

var collection = [null];
console.log ('collection[0]  -> ', collection[0] );
console.log ('collection[0] !== null -> ', collection[0] !== null);

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.