in javascript a property is truthy if it exists

myThing.property = "some string"

if (myThing.property) { // true
  // do something
}

It works with everything except of course for falsy values

myThing.number = someNumberThatShouldNotBeEqualToZero

if (myThing.number) {
  // do something very important with that number that should not be equal to zero
}

// This can fail at anytime without warning

So you’ve got to be extra careful with that logic when you’re dealing with numbers.

I am not saying it’s wrong though. I’m saying it’s often annoying.

ah ok , I think I write this a bit more verbose when using other languages, instead of

if(thing)
{
   stuff;
}

I do


if(thing != null)
{
   stuff;
}

so checking for numbers being truthy & existing didn’t seem like an issue

In the case of a non-existing property, the value would be undefined rather than null.

And while == and != exist in JavaScript, most linters will throw an error and require a === and !== instead as they should be avoided.

null == undefined // true
null === undefined // false

Besides, null is a perfectly valid value for a property, just as 0. Working with API Platform, I couldn’t tell the number of times I used this kind of statement:

if (property || property === null) {
  // do some stuff
}

Probably just as much as

if (property || property === 0) {
  // do some stuff
}
Create a post

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

  • Posts must be relevant to programming, programmers, or computer science.
  • No NSFW content.
  • Jokes must be in good taste. No hate speech, bigotry, etc.
  • 1 user online
  • 21 users / day
  • 42 users / week
  • 135 users / month
  • 546 users / 6 months
  • 1 subscriber
  • 935 Posts
  • 3.3K Comments
  • Modlog