1

I am not understanding some piece of code of the videojs player:

if currentSrc?
    $(".video-js").replaceWith(
      "<div class='unsupported'><a href='#{currentSrc}'>Download</a></div>")

As I understand it, currentSrc has to be a bool to be checked for true or false in the if statement, but later integrated in the link it is a string. Does if var? check the var just for existence? Wouldn't that be an incorrect way to check it in JS?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
John Alba
  • 265
  • 2
  • 4
  • 14

2 Answers2

1

currentSrc has to be a bool to be checked for true or false in the if statement

Incorrect. JavaScript is a dynamically typed language. A string of non-zero length (which any URL will be) will be a true value.

var foo = "";
var bar = "some value";

if (foo) { console.log(foo); } else { console.log("foo is false"); }
if (bar) { console.log(bar); } else { console.log("bar is false"); }
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • So `ìf var?` is true, when var is a non-empty string and `if var` is true, when var is a string with content "true", do I get this right? – John Alba Oct 12 '16 at 11:24
  • Just to add clarity: this is due to the Truthy concept in JavaScript https://developer.mozilla.org/en-US/docs/Glossary/Truthy - when a string is evaluated as a boolean it will be true when it has non-zero length and false when it has 0 length. – skyline3000 Oct 12 '16 at 11:24
  • To correct myself: `if var?` is true when var is a non-zero length string and `if var` is true when var is a boolean with value true. – John Alba Oct 12 '16 at 11:32
  • But the question is CoffeeScript so `if(x)` and `if(x?)` are very different things. – mu is too short Oct 12 '16 at 16:51
-1

A nice easy way to see how javascript transforms booleans, is to use a double negation !!.

Not sure the downvote, but personally I find this technique usefull, mainly because I have Chrome open, if I'm unsure of a boolean evaluation, I just open the console and type what I'm checking.. eg. type !!-1 , in this case it would return true, some other languages might see this as false

eg.

console.log( "''", !!'' );  //false
console.log( "hello2", !!'hello' );  //true
console.log( "0", !!0 );  //false
console.log( "'0'", !!'0' );  //true
console.log( "1", !!1 ); //true
console.log( "true", !!true ); //true
console.log( "null", !!null ); //false
console.log( "undefined", !!undefined ); //false
Keith
  • 22,005
  • 2
  • 27
  • 44