0

I was trying to add some form validation to a simple form I was working on earlier and I wrote the following snippet

      if (!lesson.title && lesson.title.trim().length == 0) throw Error("Kindly provide a lesson title");

Then it occurred to me to try something unconventional, instead of the logic "length EQUALS zero", I wanted to try "length NOT EQUAL TO OR LESS THAN zero", then I came up with the following snippet

      if (!lesson.title && lesson.title.trim().length <=! 0) throw Error("Kindly provide a lesson title");

To my surprise, I worked, but I didn't really understand the logic behind that so I tried out a couple of assertions with the outcomes:

"s".length <=! 0 // TRUE
"sm".length <=! 0 // FALSE

"s".length =! 0 || "s".length < 0 // TRUE
"s".length =! 0 && "s".length < 0 // FALSE
"sm".length =! 0 && "sm".length < 0 // FALSE
"sm".length =! 0 || "sm".length < 0 // TRUE

Can someone kindly explain to me what is going on here? I'm confused.

VLAZ
  • 26,331
  • 9
  • 49
  • 67

1 Answers1

3

<=! is not an operator. It is two operators:

Therefore, the expression

"s".length <=! 0

can be re-written more clearly as:

"s".length <= !0

which reads as "the length of the string s should be less than or equal to NOT zero".


The value 0 is falsy, therefore inverting it with a NOT produces boolean true

console.log( !0 )

Now we can re-write the expression to the equivalent:

"s".length <= true

Next thing comes in with how relational operators compare different types. In short, if you compare a number and a boolean, then the boolean will be coerced to a number. The value true coerces to 1

console.log( Number(true) )

Therefore, the final re-write of the expression is:

"s".length <= 1

In the end, <=! 0 is a very roundabout way of getting the wrong comparison.


instead of the logic "length EQUALS zero", I wanted to try "length NOT EQUAL TO OR LESS THAN zero", then I came up with the following snippet

There is no "not equal to or greater" as we saw. The opposite operators for relationships are:

  • == <-> !=
  • === <-> !==
  • > <-> <=
  • >= <-> <

If you want "not equal to or less than" the exact opposite is "greater than":

console.log( "5 <= 4", 5 <= 4 );
console.log( "5 > 4 ", 5 > 4 );

console.log( "5 <= 5", 5 <= 5 );
console.log( "5 > 5 ", 5 > 5 );

console.log( "5 <= 6", 5 <= 6 );
console.log( "5 > 6 ", 5 > 6 );

The other option is to negate the whole comparison which will give identical results:

console.log( "5 <= 4",   5 <= 4 );
console.log( "5 > 4 ", !(5 <= 4) );

console.log( "5 <= 5",   5 <= 5 );
console.log( "5 > 5 ", !(5 <= 5) );

console.log( "5 <= 6",   5 <= 6 );
console.log( "5 > 6 ", !(5 <= 6) );
VLAZ
  • 26,331
  • 9
  • 49
  • 67