Javascript: si las declaraciones verifican tanto la expresión como la declaración de definición Esto es confuso

var boolTrue = true;
var randomObject;

if (boolTrue)
// this will fire

if (randomObject)
// this will fire, because the object is defined

if (!objectNotDefined)
// this will fire, because there is no defined object named 'objectNotDefined'

Coming from a C++ and C# background, I am very familiar with the basic if(expression) syntax. However, I think it is not very readable to have both expressions (true/false) and have object existence also being a expression. Because now if I see a function like below, i don't know if the data coming in is an object (existence/undefined check) or a boolean.

function(data) {
   if (data)
      // is this checking if the object is true/false or if the object is in existence?
}

Is this just the way it is? I mean, is there anyway to easily read this? Also, where is this documented anywhere in the JS spec (curious)?

preguntado el 09 de marzo de 12 a las 16:03

Tu ejemplo está mal. if (randomObject) will NOT fire, it's false. if (!objectNotDefined) dará un error "objectNotDefined is not defined". -

Está documentado aquí: es5.github.com/#x9.2 -

4 Respuestas

In Javascript everything is "true" (or "truthy" to be more precise using Javascript parlance) except false, 0, undefined, null, NaN y cuerda vacía.

To avoid confusion use:

 if (data === true) // Is it really true?

y

if (typeof data === 'undefined') // Is the variable undefined?

Respondido 05 Abr '13, 16:04

You can check for (non-)existence separately:

if ( typeof variable == 'undefined' ) {
  // other code
}

However, the syntax you show is commonly used as a much shorter form and is sufficient in most usecases.

respondido 09 mar '12, 16:03

The following values are equivalent to false in conditional statements:

false
null
undefined
The empty string ”
The number 0
The number NaN

respondido 09 mar '12, 16:03

It checks whether it is veraz.

In JavaScript, everything is truthy except false, 0, "", undefined, null y NaN.

¿Entonces true will pass, as well as cualquier object (also empty objects/arrays/etc).

Note that your third comment is true if you mean "declared but not defined" - a variable that has never been declaró lanza un ReferenceError on access. A declared, non-defined variable (var something;) es undefined (so, not truthy) so it will indeed pass the condition if you negate it.

respondido 09 mar '12, 16:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.