There are two most important terms to understand when you execute some code based on an "if else" statement. Truthy and Falsy value.
Truthy value: Data types that return true by default are called truthy.
False value: Data types that return false by default are called falsy
- All values are truthy except these values
- +0 or -0
- BigInt zero (0n)
- Empty String ("")
- null, undefined, and NaN
For example below this code we are performing a Linear search. But when I apply a condition for "value not found" I have a complexity for array index 0. Because it's a falsy value if I use the findIndex variable value as an 'if' condition. I solved this in my way. But there have several ways to solve this.
Top comments (2)
Truthiness and Falsiness can be a difficult concept when coming from more strongly typed languages.
I quite often see things like
if (array.length > 1)
, which is necessary for languages like C#, but can be achieved withif (array.length)
in JavaScript.Another stumbling block I sometimes have is assuming values that should be
boolean
are boolean because they are truthy. This can lead to strange results, until converted, e.g.!!truthyValue
It should be noted, that there are some other stumbling blocks in Javascript, that might cause an uexpected behavoir:
1. Dynamic Type conversion
Calculations may cause unwanted behavoir
In Javascript, 1+'1' = '11', so it is larger than 5.
2. Default operators
You can use a default value for an 'undefined'
This works for all stored values, but 0. If you store 0, x will be set to five 5. Same ist true for all values that evaluate to "false", as JS cannot distinguish between
undefined
,null
,false
,0
,NaN
or""
. The only exception is "0", which is not zero....