0

I have found out that in JavaScript it is possible to use bare string in if condition. I mean something like this:

var condition = "";
if (condition) {
    //we will never come here 
}

However, it feels very weird for me because, for example, in Java this code would not compile. I try to understand what is happening with this string behind the scene, but fail for now.

Could you explain to me what happens in this case?

P.s. Moreover, if the variable condition is not initialized at all then it is still fine and the result will be the same. Feels that JavaScript allows quite a lot of these things.

Rufi
  • 2,529
  • 1
  • 20
  • 41

4 Answers4

0

JavaScript is not strongly typed. In this instance this means that the interpreter takes the variable and tries as hard as he can to convert that to a boolean. This means that the integer 0, null, "" and "0" (and I think undefined as wel) all get converted to false, while the integer 1, "1" and non-null objects all get converted to true.

Johannes Hahn
  • 363
  • 3
  • 18
0

Javascript convert "" string to boolean which is false

Check equallity and comparision

Check about language:

Static/Dynamic vs Strong/Weak

Wikipedia

Community
  • 1
  • 1
Sarjan Desai
  • 3,683
  • 2
  • 19
  • 32
0

I understand your problem, I also come from a strong typed background. The Javascript concept here is truthy or falsy.

What is to understand here is that Javascript uses type coercion, so the verification of

if (condition) {}

where condition was initialized a string, will lead to false.

As per definition: A falsy value is a value that translates to false when evaluated in a Boolean context. Example of falsy values:

if (false)
if (null)
if (undefined)
if (0)
if (NaN)
if ('')

Have a read on the truthy falsy in Javascript to have a better understanding.

julia
  • 452
  • 6
  • 15
0

In javascript if(condition), the condition is an expression that will finally converted to boolean type, the language defined that undefined, null, NaN, 0, '' will all be casted to boolean false, you can check using !! operator to explicitly convert to boolean, check:

!!'' === false
!!0 === false
!!null === false
!!undefined === false
!!NaN === false

all the above expression is true, besides,

''==0
null==undefined

The above expression also is true

So, in your condition, '' == 0, and will be casted into false

That's the magic of javascript, and it's have been used widely.

James Yang
  • 1,306
  • 4
  • 15
  • 25