Add elements inside Array conditionally in JavaScriptIn Javascript, how to conditionally add a member to an object?How do JavaScript closures work?How do I check if an element is hidden in jQuery?How do I remove a property from a JavaScript object?Which equals operator (== vs ===) should be used in JavaScript comparisons?How do I include a JavaScript file in another JavaScript file?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?Loop through an array in JavaScriptHow do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?

On what legal basis did the UK remove the 'European Union' from its passport?

LocalDate.plus Incorrect Answer

What is the best way for a skeleton to impersonate human without using magic?

Was there a contingency plan in place if Little Boy failed to detonate?

Why does TypeScript pack a Class in an IIFE?

Why did God specifically target the firstborn in the 10th plague (Exodus 12:29-36)?

How old is Captain America at the end of "Avengers: Endgame"?

Make all the squares explode

Guns in space with bullets that return?

Can you book a one-way ticket to the UK on a visa?

A musical commute to work

Why was this sacrifice sufficient?

Is it a Munchausen Number?

Is there enough time to Planar Bind a creature conjured by a 1-hour-duration spell?

Understanding basic photoresistor circuit

Is Simic Ascendancy triggered by Awakening of Vitu-Ghazi?

How to make a language evolve quickly?

Pre-1993 comic in which Wolverine's claws were turned to rubber?

Why does a C.D.F need to be right-continuous?

How do I get past a 3-year ban from overstay with VWP?

Is the homebrew weapon attack cantrip 'Arcane Strike' balanced?

Control variables and other independent variables

Set a camera to free fall like a Rigid Body?

Ex-manager wants to stay in touch, I don't want to



Add elements inside Array conditionally in JavaScript


In Javascript, how to conditionally add a member to an object?How do JavaScript closures work?How do I check if an element is hidden in jQuery?How do I remove a property from a JavaScript object?Which equals operator (== vs ===) should be used in JavaScript comparisons?How do I include a JavaScript file in another JavaScript file?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?Loop through an array in JavaScriptHow do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








30















When I try to merge two objects using the spread operator conditionally, it works when the condition is true or false:



let condition = false;
let obj1 = key1: 'value1'
let obj2 =
key2: 'value2',
...(condition && obj1),
;

// obj2 = key2: 'value2';


When I try to use the same logic with Arrays, it only works when the condition is true:



let condition = true;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition && arr1)];

// arr2 = ['value2', 'value1']


If the condition is false an error is thrown:






let condition = false;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition && arr1)];

// Error





Why is the behaviour different between Array and Object?










share|improve this question
























  • Not cleared. What do you want to achieve here? Can you please paste your (condition && arr) as well?

    – narayansharma91
    May 7 at 11:34











  • FYI, ...null and ...undefined won't throw error either. So, we can forgo that check as well if we are unsure if an object has value or not

    – adiga
    May 7 at 12:13







  • 1





    FWIW if you wanted to spread booleans, you could do something like Boolean.prototype[Symbol.iterator] = function* () (obviously don't do this in production code, it's a mere curio)

    – Conor O'Brien
    May 7 at 14:00











  • Is what you really want to achieve condition ? [...arr1, ...arr2] : arr1 or is this just a question on how the language works?

    – JollyJoker
    May 7 at 14:20






  • 2





    @JollyJoker it's just a question on how the language works. Thanks

    – João Rodrigues
    May 7 at 14:34

















30















When I try to merge two objects using the spread operator conditionally, it works when the condition is true or false:



let condition = false;
let obj1 = key1: 'value1'
let obj2 =
key2: 'value2',
...(condition && obj1),
;

// obj2 = key2: 'value2';


When I try to use the same logic with Arrays, it only works when the condition is true:



let condition = true;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition && arr1)];

// arr2 = ['value2', 'value1']


If the condition is false an error is thrown:






let condition = false;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition && arr1)];

// Error





Why is the behaviour different between Array and Object?










share|improve this question
























  • Not cleared. What do you want to achieve here? Can you please paste your (condition && arr) as well?

    – narayansharma91
    May 7 at 11:34











  • FYI, ...null and ...undefined won't throw error either. So, we can forgo that check as well if we are unsure if an object has value or not

    – adiga
    May 7 at 12:13







  • 1





    FWIW if you wanted to spread booleans, you could do something like Boolean.prototype[Symbol.iterator] = function* () (obviously don't do this in production code, it's a mere curio)

    – Conor O'Brien
    May 7 at 14:00











  • Is what you really want to achieve condition ? [...arr1, ...arr2] : arr1 or is this just a question on how the language works?

    – JollyJoker
    May 7 at 14:20






  • 2





    @JollyJoker it's just a question on how the language works. Thanks

    – João Rodrigues
    May 7 at 14:34













30












30








30


2






When I try to merge two objects using the spread operator conditionally, it works when the condition is true or false:



let condition = false;
let obj1 = key1: 'value1'
let obj2 =
key2: 'value2',
...(condition && obj1),
;

// obj2 = key2: 'value2';


When I try to use the same logic with Arrays, it only works when the condition is true:



let condition = true;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition && arr1)];

// arr2 = ['value2', 'value1']


If the condition is false an error is thrown:






let condition = false;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition && arr1)];

// Error





Why is the behaviour different between Array and Object?










share|improve this question
















When I try to merge two objects using the spread operator conditionally, it works when the condition is true or false:



let condition = false;
let obj1 = key1: 'value1'
let obj2 =
key2: 'value2',
...(condition && obj1),
;

// obj2 = key2: 'value2';


When I try to use the same logic with Arrays, it only works when the condition is true:



let condition = true;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition && arr1)];

// arr2 = ['value2', 'value1']


If the condition is false an error is thrown:






let condition = false;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition && arr1)];

// Error





Why is the behaviour different between Array and Object?






let condition = false;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition && arr1)];

// Error





let condition = false;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition && arr1)];

// Error






javascript ecmascript-6






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 8 at 0:00









CertainPerformance

105k166798




105k166798










asked May 7 at 11:31









João RodriguesJoão Rodrigues

288211




288211












  • Not cleared. What do you want to achieve here? Can you please paste your (condition && arr) as well?

    – narayansharma91
    May 7 at 11:34











  • FYI, ...null and ...undefined won't throw error either. So, we can forgo that check as well if we are unsure if an object has value or not

    – adiga
    May 7 at 12:13







  • 1





    FWIW if you wanted to spread booleans, you could do something like Boolean.prototype[Symbol.iterator] = function* () (obviously don't do this in production code, it's a mere curio)

    – Conor O'Brien
    May 7 at 14:00











  • Is what you really want to achieve condition ? [...arr1, ...arr2] : arr1 or is this just a question on how the language works?

    – JollyJoker
    May 7 at 14:20






  • 2





    @JollyJoker it's just a question on how the language works. Thanks

    – João Rodrigues
    May 7 at 14:34

















  • Not cleared. What do you want to achieve here? Can you please paste your (condition && arr) as well?

    – narayansharma91
    May 7 at 11:34











  • FYI, ...null and ...undefined won't throw error either. So, we can forgo that check as well if we are unsure if an object has value or not

    – adiga
    May 7 at 12:13







  • 1





    FWIW if you wanted to spread booleans, you could do something like Boolean.prototype[Symbol.iterator] = function* () (obviously don't do this in production code, it's a mere curio)

    – Conor O'Brien
    May 7 at 14:00











  • Is what you really want to achieve condition ? [...arr1, ...arr2] : arr1 or is this just a question on how the language works?

    – JollyJoker
    May 7 at 14:20






  • 2





    @JollyJoker it's just a question on how the language works. Thanks

    – João Rodrigues
    May 7 at 14:34
















Not cleared. What do you want to achieve here? Can you please paste your (condition && arr) as well?

– narayansharma91
May 7 at 11:34





Not cleared. What do you want to achieve here? Can you please paste your (condition && arr) as well?

– narayansharma91
May 7 at 11:34













FYI, ...null and ...undefined won't throw error either. So, we can forgo that check as well if we are unsure if an object has value or not

– adiga
May 7 at 12:13






FYI, ...null and ...undefined won't throw error either. So, we can forgo that check as well if we are unsure if an object has value or not

– adiga
May 7 at 12:13





1




1





FWIW if you wanted to spread booleans, you could do something like Boolean.prototype[Symbol.iterator] = function* () (obviously don't do this in production code, it's a mere curio)

– Conor O'Brien
May 7 at 14:00





FWIW if you wanted to spread booleans, you could do something like Boolean.prototype[Symbol.iterator] = function* () (obviously don't do this in production code, it's a mere curio)

– Conor O'Brien
May 7 at 14:00













Is what you really want to achieve condition ? [...arr1, ...arr2] : arr1 or is this just a question on how the language works?

– JollyJoker
May 7 at 14:20





Is what you really want to achieve condition ? [...arr1, ...arr2] : arr1 or is this just a question on how the language works?

– JollyJoker
May 7 at 14:20




2




2





@JollyJoker it's just a question on how the language works. Thanks

– João Rodrigues
May 7 at 14:34





@JollyJoker it's just a question on how the language works. Thanks

– João Rodrigues
May 7 at 14:34












3 Answers
3






active

oldest

votes


















36














When you spread into an array, you call the Symbol.iterator method on the object. && evaluates to the first falsey value (or the last truthy value, if all are truthy), so



let arr2 = ['value2', ...(condition && arr)];


results in



let arr2 = ['value2', ...(false)];


But false does not have a Symbol.iterator method.



You could use the conditional operator instead, and spread an empty array if the condition is false:






let condition = false;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition ? arr1 : [])];
console.log(arr2);





(This works because the empty array does have the Symbol.iterator method)



Object spread is completely different: it copies own enumerable properties from a provided object onto a new object. false does not have any own enumerable properties, so nothing gets copied.






share|improve this answer
































    13














    false is not spreadable.



    You need a spreadable object (the one where Symbol.iterator is implemented) which returns nothing, if spreaded.



    You could use an empty array as default value. This works even if arr is falsy.






    let condition = false;
    let arr1 = ['value1'];
    let arr2 = ['value2', ...(condition && arr || [])];

    console.log(arr2);








    share|improve this answer

























    • would add parenthesis to make it clearer ((condition && arr) || [])

      – Grégory NEUT
      May 7 at 11:37






    • 5





      This could really use the ?: operator instead of a chained ||.

      – deceze
      May 7 at 11:37












    • @deceze, it really depends on the use case.

      – Nina Scholz
      May 7 at 11:39







    • 6





      I think this is a use case where ?: is a lot more appropriate. ;)

      – deceze
      May 7 at 11:39


















    9














    This is a specification difference between the spread syntax for object literals and for array literals.



    MDN briefly mentions it here -- I highlight:




    Spread syntax (other than in the case of spread properties) can be applied only to iterable objects




    The difference comes from the EcmaScript 2018 specification:




    • Concerning object spread syntax, see 12.2.6.8 Runtime Semantics: PropertyDefinitionEvaluation:



      • It calls CopyDataProperties(object, fromValue, excludedNames) where the fromValue is wrapped to an object with ToObject, and therefore becomes iterable, even if fromValue is a primitive value like false. Therefore ...false is valid EcmaScript.



    • Concerning array spread syntax, see 12.2.5.2 Runtime Semantics: ArrayAccumulation:



      • It merely calls GetValue(spreadRef) which does not do the above mentioned wrapping. And so the subsequent call to GetIterator will trigger an error on a primitive value, as it is not iterable. Therefore [...false] is invalid EcmaScript.






    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56021631%2fadd-elements-inside-array-conditionally-in-javascript%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      36














      When you spread into an array, you call the Symbol.iterator method on the object. && evaluates to the first falsey value (or the last truthy value, if all are truthy), so



      let arr2 = ['value2', ...(condition && arr)];


      results in



      let arr2 = ['value2', ...(false)];


      But false does not have a Symbol.iterator method.



      You could use the conditional operator instead, and spread an empty array if the condition is false:






      let condition = false;
      let arr1 = ['value1'];
      let arr2 = ['value2', ...(condition ? arr1 : [])];
      console.log(arr2);





      (This works because the empty array does have the Symbol.iterator method)



      Object spread is completely different: it copies own enumerable properties from a provided object onto a new object. false does not have any own enumerable properties, so nothing gets copied.






      share|improve this answer





























        36














        When you spread into an array, you call the Symbol.iterator method on the object. && evaluates to the first falsey value (or the last truthy value, if all are truthy), so



        let arr2 = ['value2', ...(condition && arr)];


        results in



        let arr2 = ['value2', ...(false)];


        But false does not have a Symbol.iterator method.



        You could use the conditional operator instead, and spread an empty array if the condition is false:






        let condition = false;
        let arr1 = ['value1'];
        let arr2 = ['value2', ...(condition ? arr1 : [])];
        console.log(arr2);





        (This works because the empty array does have the Symbol.iterator method)



        Object spread is completely different: it copies own enumerable properties from a provided object onto a new object. false does not have any own enumerable properties, so nothing gets copied.






        share|improve this answer



























          36












          36








          36







          When you spread into an array, you call the Symbol.iterator method on the object. && evaluates to the first falsey value (or the last truthy value, if all are truthy), so



          let arr2 = ['value2', ...(condition && arr)];


          results in



          let arr2 = ['value2', ...(false)];


          But false does not have a Symbol.iterator method.



          You could use the conditional operator instead, and spread an empty array if the condition is false:






          let condition = false;
          let arr1 = ['value1'];
          let arr2 = ['value2', ...(condition ? arr1 : [])];
          console.log(arr2);





          (This works because the empty array does have the Symbol.iterator method)



          Object spread is completely different: it copies own enumerable properties from a provided object onto a new object. false does not have any own enumerable properties, so nothing gets copied.






          share|improve this answer















          When you spread into an array, you call the Symbol.iterator method on the object. && evaluates to the first falsey value (or the last truthy value, if all are truthy), so



          let arr2 = ['value2', ...(condition && arr)];


          results in



          let arr2 = ['value2', ...(false)];


          But false does not have a Symbol.iterator method.



          You could use the conditional operator instead, and spread an empty array if the condition is false:






          let condition = false;
          let arr1 = ['value1'];
          let arr2 = ['value2', ...(condition ? arr1 : [])];
          console.log(arr2);





          (This works because the empty array does have the Symbol.iterator method)



          Object spread is completely different: it copies own enumerable properties from a provided object onto a new object. false does not have any own enumerable properties, so nothing gets copied.






          let condition = false;
          let arr1 = ['value1'];
          let arr2 = ['value2', ...(condition ? arr1 : [])];
          console.log(arr2);





          let condition = false;
          let arr1 = ['value1'];
          let arr2 = ['value2', ...(condition ? arr1 : [])];
          console.log(arr2);






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited May 7 at 14:30









          Nzall

          3,03331950




          3,03331950










          answered May 7 at 11:34









          CertainPerformanceCertainPerformance

          105k166798




          105k166798























              13














              false is not spreadable.



              You need a spreadable object (the one where Symbol.iterator is implemented) which returns nothing, if spreaded.



              You could use an empty array as default value. This works even if arr is falsy.






              let condition = false;
              let arr1 = ['value1'];
              let arr2 = ['value2', ...(condition && arr || [])];

              console.log(arr2);








              share|improve this answer

























              • would add parenthesis to make it clearer ((condition && arr) || [])

                – Grégory NEUT
                May 7 at 11:37






              • 5





                This could really use the ?: operator instead of a chained ||.

                – deceze
                May 7 at 11:37












              • @deceze, it really depends on the use case.

                – Nina Scholz
                May 7 at 11:39







              • 6





                I think this is a use case where ?: is a lot more appropriate. ;)

                – deceze
                May 7 at 11:39















              13














              false is not spreadable.



              You need a spreadable object (the one where Symbol.iterator is implemented) which returns nothing, if spreaded.



              You could use an empty array as default value. This works even if arr is falsy.






              let condition = false;
              let arr1 = ['value1'];
              let arr2 = ['value2', ...(condition && arr || [])];

              console.log(arr2);








              share|improve this answer

























              • would add parenthesis to make it clearer ((condition && arr) || [])

                – Grégory NEUT
                May 7 at 11:37






              • 5





                This could really use the ?: operator instead of a chained ||.

                – deceze
                May 7 at 11:37












              • @deceze, it really depends on the use case.

                – Nina Scholz
                May 7 at 11:39







              • 6





                I think this is a use case where ?: is a lot more appropriate. ;)

                – deceze
                May 7 at 11:39













              13












              13








              13







              false is not spreadable.



              You need a spreadable object (the one where Symbol.iterator is implemented) which returns nothing, if spreaded.



              You could use an empty array as default value. This works even if arr is falsy.






              let condition = false;
              let arr1 = ['value1'];
              let arr2 = ['value2', ...(condition && arr || [])];

              console.log(arr2);








              share|improve this answer















              false is not spreadable.



              You need a spreadable object (the one where Symbol.iterator is implemented) which returns nothing, if spreaded.



              You could use an empty array as default value. This works even if arr is falsy.






              let condition = false;
              let arr1 = ['value1'];
              let arr2 = ['value2', ...(condition && arr || [])];

              console.log(arr2);








              let condition = false;
              let arr1 = ['value1'];
              let arr2 = ['value2', ...(condition && arr || [])];

              console.log(arr2);





              let condition = false;
              let arr1 = ['value1'];
              let arr2 = ['value2', ...(condition && arr || [])];

              console.log(arr2);






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited May 7 at 11:42

























              answered May 7 at 11:36









              Nina ScholzNina Scholz

              204k16117187




              204k16117187












              • would add parenthesis to make it clearer ((condition && arr) || [])

                – Grégory NEUT
                May 7 at 11:37






              • 5





                This could really use the ?: operator instead of a chained ||.

                – deceze
                May 7 at 11:37












              • @deceze, it really depends on the use case.

                – Nina Scholz
                May 7 at 11:39







              • 6





                I think this is a use case where ?: is a lot more appropriate. ;)

                – deceze
                May 7 at 11:39

















              • would add parenthesis to make it clearer ((condition && arr) || [])

                – Grégory NEUT
                May 7 at 11:37






              • 5





                This could really use the ?: operator instead of a chained ||.

                – deceze
                May 7 at 11:37












              • @deceze, it really depends on the use case.

                – Nina Scholz
                May 7 at 11:39







              • 6





                I think this is a use case where ?: is a lot more appropriate. ;)

                – deceze
                May 7 at 11:39
















              would add parenthesis to make it clearer ((condition && arr) || [])

              – Grégory NEUT
              May 7 at 11:37





              would add parenthesis to make it clearer ((condition && arr) || [])

              – Grégory NEUT
              May 7 at 11:37




              5




              5





              This could really use the ?: operator instead of a chained ||.

              – deceze
              May 7 at 11:37






              This could really use the ?: operator instead of a chained ||.

              – deceze
              May 7 at 11:37














              @deceze, it really depends on the use case.

              – Nina Scholz
              May 7 at 11:39






              @deceze, it really depends on the use case.

              – Nina Scholz
              May 7 at 11:39





              6




              6





              I think this is a use case where ?: is a lot more appropriate. ;)

              – deceze
              May 7 at 11:39





              I think this is a use case where ?: is a lot more appropriate. ;)

              – deceze
              May 7 at 11:39











              9














              This is a specification difference between the spread syntax for object literals and for array literals.



              MDN briefly mentions it here -- I highlight:




              Spread syntax (other than in the case of spread properties) can be applied only to iterable objects




              The difference comes from the EcmaScript 2018 specification:




              • Concerning object spread syntax, see 12.2.6.8 Runtime Semantics: PropertyDefinitionEvaluation:



                • It calls CopyDataProperties(object, fromValue, excludedNames) where the fromValue is wrapped to an object with ToObject, and therefore becomes iterable, even if fromValue is a primitive value like false. Therefore ...false is valid EcmaScript.



              • Concerning array spread syntax, see 12.2.5.2 Runtime Semantics: ArrayAccumulation:



                • It merely calls GetValue(spreadRef) which does not do the above mentioned wrapping. And so the subsequent call to GetIterator will trigger an error on a primitive value, as it is not iterable. Therefore [...false] is invalid EcmaScript.






              share|improve this answer





























                9














                This is a specification difference between the spread syntax for object literals and for array literals.



                MDN briefly mentions it here -- I highlight:




                Spread syntax (other than in the case of spread properties) can be applied only to iterable objects




                The difference comes from the EcmaScript 2018 specification:




                • Concerning object spread syntax, see 12.2.6.8 Runtime Semantics: PropertyDefinitionEvaluation:



                  • It calls CopyDataProperties(object, fromValue, excludedNames) where the fromValue is wrapped to an object with ToObject, and therefore becomes iterable, even if fromValue is a primitive value like false. Therefore ...false is valid EcmaScript.



                • Concerning array spread syntax, see 12.2.5.2 Runtime Semantics: ArrayAccumulation:



                  • It merely calls GetValue(spreadRef) which does not do the above mentioned wrapping. And so the subsequent call to GetIterator will trigger an error on a primitive value, as it is not iterable. Therefore [...false] is invalid EcmaScript.






                share|improve this answer



























                  9












                  9








                  9







                  This is a specification difference between the spread syntax for object literals and for array literals.



                  MDN briefly mentions it here -- I highlight:




                  Spread syntax (other than in the case of spread properties) can be applied only to iterable objects




                  The difference comes from the EcmaScript 2018 specification:




                  • Concerning object spread syntax, see 12.2.6.8 Runtime Semantics: PropertyDefinitionEvaluation:



                    • It calls CopyDataProperties(object, fromValue, excludedNames) where the fromValue is wrapped to an object with ToObject, and therefore becomes iterable, even if fromValue is a primitive value like false. Therefore ...false is valid EcmaScript.



                  • Concerning array spread syntax, see 12.2.5.2 Runtime Semantics: ArrayAccumulation:



                    • It merely calls GetValue(spreadRef) which does not do the above mentioned wrapping. And so the subsequent call to GetIterator will trigger an error on a primitive value, as it is not iterable. Therefore [...false] is invalid EcmaScript.






                  share|improve this answer















                  This is a specification difference between the spread syntax for object literals and for array literals.



                  MDN briefly mentions it here -- I highlight:




                  Spread syntax (other than in the case of spread properties) can be applied only to iterable objects




                  The difference comes from the EcmaScript 2018 specification:




                  • Concerning object spread syntax, see 12.2.6.8 Runtime Semantics: PropertyDefinitionEvaluation:



                    • It calls CopyDataProperties(object, fromValue, excludedNames) where the fromValue is wrapped to an object with ToObject, and therefore becomes iterable, even if fromValue is a primitive value like false. Therefore ...false is valid EcmaScript.



                  • Concerning array spread syntax, see 12.2.5.2 Runtime Semantics: ArrayAccumulation:



                    • It merely calls GetValue(spreadRef) which does not do the above mentioned wrapping. And so the subsequent call to GetIterator will trigger an error on a primitive value, as it is not iterable. Therefore [...false] is invalid EcmaScript.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited May 7 at 11:55

























                  answered May 7 at 11:44









                  trincottrincot

                  134k1697133




                  134k1697133



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56021631%2fadd-elements-inside-array-conditionally-in-javascript%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

                      Circuit construction for execution of conditional statements using least significant bitHow are two different registers being used as “control”?How exactly is the stated composite state of the two registers being produced using the $R_zz$ controlled rotations?Efficiently performing controlled rotations in HHLWould this quantum algorithm implementation work?How to prepare a superposed states of odd integers from $1$ to $sqrtN$?Why is this implementation of the order finding algorithm not working?Circuit construction for Hamiltonian simulationHow can I invert the least significant bit of a certain term of a superposed state?Implementing an oracleImplementing a controlled sum operation

                      Magento 2 “No Payment Methods” in Admin New OrderHow to integrate Paypal Express Checkout with the Magento APIMagento 1.5 - Sales > Order > edit order and shipping methods disappearAuto Invoice Check/Money Order Payment methodAdd more simple payment methods?Shipping methods not showingWhat should I do to change payment methods if changing the configuration has no effects?1.9 - No Payment Methods showing upMy Payment Methods not Showing for downloadable/virtual product when checkout?Magento2 API to access internal payment methodHow to call an existing payment methods in the registration form?