Boolean primitive values versus boolean object

12

I am seeing JavaScript and I came across this that I do not understand the Boolean objects and the Boolean primitives .

  • If I use a Boolean object to compare it in a if will it give me false ?

  • Or why the documentation of Grammar and Types (MDN) says that should not be confused with these two things?

      

    Boolean Literal

         

    Boolean type literals have 2 possible values: true and false .

         

    Do NOT confuse the Boolean primitive values true and false with the true and false values of the Boolean Object. The Boolean object is a container around the Boolean Primitive data type. For more information check Boolean .

  • asked by sommer0123 01.12.2016 в 05:36
    source

    3 answers

    12

    Boolean literals are just two: true and false.

    var a = true;
    var b = false;
    

    By 'literal' one must understand the representation of a value in the same source code, in this sense the variable a stores a Boolean primitive value that evaluates to true while the variable b stores a Boolean primitive value that evaluates to false .

    if(a) 
        alert("Verdadero"); //Imprime "Verdadero"
    else
        alert("Falso");
    

    Boolean objects are a type of entity that act as 'containers' of a Boolean value:

    var o = new Boolean(false);
    

    According to the documentation , when an object is created Boolean can take two initial values: false or true, depending on the parameters that are passed to him when constructing the object. The following Boolean objects have false initial status:

    var p = new Boolean();
    var p = new Boolean(0);
    var p = new Boolean(-0);
    var p = new Boolean(null);
    var p = new Boolean(false);
    var p = new Boolean(undefined);
    var p = new Boolean(NaN);
    var p = new Boolean("");
    

    as well as any expression passed as a parameter and evaluate to 0, -0, null, false, undefined, NaN or "". In any other case, it will have an initial state of true.

    On the other hand, any object in Javascript is susceptible to being evaluated in an if, going back to the documentation, any object whose value is not undefined or null evaluates to true when passed in an if This implies that although the state of the boolean object that was created is false, it will always evaluate true when it passes in an if conditional. Therefore:

    var name = "Daniel";
    var edad = 24;
    var programador = true;
    var mujer = false;
    var incognita;
    var rico = new Boolean(false);
    
    if(name) { console.log(name); } //Imprime "Daniel"
    if(edad) { console.log(edad); } //Imprime 24
    if(mujer) { console.log(mujer); } //No imprime nada, mujer es primitivo booleano y su valor es false
    if(incognita) { console.log(incognita); } //No imprime nada, el valor por defecto de una variable creada es undefined y por lo tanto evalúa a false
    if(rico) { console.log("Rico"); } //Imprime rico, a pesar que el valor del objeto es false, evalúa a verdadero en el condicional.
    
        
    answered by 01.12.2016 в 07:13
    4

    The basic premise is, whenever possible, use a primitive data type instead of an Object because it is the most basic level and therefore the most efficient.

      
  • Used a Boolean object to compare it in if will give false ?
  •   

    It depends on what and how you compare it, however if you always use it as the only member of the expression it will give you true . The details below.

      

    Or why the documentation of Grammar and Types (MDN) says that should not be confused with these two things?

    The text quoted includes a link to a page that does not exist in Spanish but does exist in English: Boolean . On this page it says

      

    Any object of which value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement.

    The translation would be

      

    Any object whose value is not undefined or null , including a Boolean object whose value is false , evaluates true when it is passed to a conditional statement.

    Here are some examples of this:

    // Creamos un Objeto Booleano con valor falso.
    var x = new Boolean(false);
    
    // Comparación abstracta. Devuelve Verdadero
    if(x == false){
      console.info('Verdadero');
    } else {
      console.info('False');
    }
    
    // Comparación estricta. Devuelve Falso
    if(x === false){
      console.info('Verdadero');
    } else {
      console.info('Falso');
    }
    
    // Sin realizar una comparación. Devuelve verdadero.
    if(x){
      console.info('Verdadero');
    } else {
      console.info('Falso');
    }

    A Boolean primitive and a Boolean object should not be confused because JavaScript converts the type of arguments when they are not of the required type, which in an if is a Boolean context.

    At the ECMAScript 2016, about ConditionExpression it is indicated:

      

    NOTE
      The grammar for a ConditionalExpression in ECMAScript is   slightly different from that in C and Java, which each allow the   second subexpression to be an Expression but restrict the third   expression to be a ConditionalExpression. The motivation for this   difference in ECMAScript is to allow an assignment expression to be   governed by either arm of a conditional and to eliminate the confusing   and fairly useless case of a comma expression as the center   expression.

    Here is an attempt to translate the above:

      

    NOTE The grammar for ContidionalExpression in ECMAScript is   slightly different from that in C and Java, where each one allows   that the second subexpression will be an Expression but restricts the   third expression to be a ConditionalExpression. The motivation of   this difference in ECMAScript is to allow an expression of   assignment is governed by any arm of a conditional and for   eliminate the confusion and practically useless house of an expression   eat as the center of expression.

    More code to help understand this, where a Boolean Object with value false is created and assigned to variable x .

    // Crear el Objeto Booleano con valor false
    var x = new Boolean(false);
    // Comparación abstracta de x con el primitivo Booleano con valor false.
    console.info(x == false);  // Devuelve verdadero
    // Comparación del valor de la propiedad toString() con el primitivo Booleano con valor false.
    console.info(x.toString() == false); // Devuelve false
    // Comparación del valor de la propiedad valueOf() con el primitivo 
    console.info(x.valueOf() == false); // Devuelve verdadero
    // Operador ternario, en caso verdadero devolverá true, en caso contrario, devolverá false
    console.info(x ? true: false); // Devuelve verdadero

    Regarding what the standard says about this, in 12.14.3 Runtime Semantics: Evaluation , the algorithm is included to evaluate the exprsion, where one of the first step is to convert to Boolean, which is described in 7.1.2 ToBoolean (argument) , where the following is indicated:

      

    The abstract operation ToBoolean converts argument to a value of type   Boolean according to Table 10:

         

    Table 10: ToBoolean Conversions

         
    Argument Type    Result
    Undefined        Return false.
    Null             Return false.
    Boolean          Return argument.
    Number           Return false if argument is +0, -0, or NaN; otherwise return true.
    String           Return false if argument is the empty String (its length is zero); 
                     otherwise return true.
    Symbol           Return true.
    Object           Return true.
    

    Note that it is indicated that when the argument is of type object, true is returned.

        
    answered by 12.07.2017 в 21:44
    0

    In two words.

    The Boolean primitive can only take the two values 'true' or 'false' but the Boolean Object can be Null if it has not been assigned to a value previously.

        
    answered by 15.07.2017 в 02:51