Jasper Jarlsen Jasper Jarlsen - 1 month ago 10
CoffeeScript Question

JavaScript: if var? where var is no bool

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?

Answer

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"); }

Comments