0

I have an instance of a class, in which several number and string properties are initialized to 0 or "" respectively. When accessing these properties they are "undefined". Initializing these properties to anything else, ie 0.1 or " " and it is considered defined.

Why? Are 0 and "" equivalent to undefined?

export class Car {
     id = 0
     name = ""
}

If I have an instance of Car and try to access a property it will be "undefined",

let myCar = new Car
if (myCar.id) {
    console.log('yay')
} else {
    console.log('boo')
}

It will show 'boo'.

1
  • 1
    0 and empty string are default values for those types respectively and will evaluate to false. change if(myCar.id) to if(myCar.id !== undefined) Commented Aug 8, 2019 at 20:29

1 Answer 1

2

In javascript, the value 0 is evaluated as a falsy statement. Same for an empty string "". If you want to test if the property is undefined you need to do so explicitely

let myCar = new Car
if (myCar.id !== undefined) {
    console.log('yay')
} else {
    console.log('boo')
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.