Comparison position in conditionals JavaScript

Viewed 29

I'm curious about, why some programers compares before the value than the variable ?

For example, if I want to create a simple if, I'll do something like this:

  const foo = 'success';
 
  if(foo === 'success') {
   console.log('works fine!');
  } else {
   console.log('don\'t work');
  }

BUT I've seen some programers that do that:

  const foo = 'success';
  
  // Note the position of the success value!
  if('success' === foo) {
   console.log('works fine!');
  } else {
   console.log('don\'t work');
  }

I want to know which way is better and WHY ?

Thanks.

1 Answers

It's Yoda conditions. Programmers do for null safe.

I try compare strings. If my variable null and I try call method of includes() I will get exception, but if I call includes() for literal it's save from exception.

const someString = null; 

// I will get exception
if (someString.includes("literal")) {

}

// Null safe
if ("literal".includes(someString)) {

}

BUT: if you matter know about something variable that it's null, then not need use yoda condition. Try handle this exception.

Related