-1

I am trying the ES6 destructuring assignment feature to pass an options object containing multiple parameters to a function, but one of the parameters is being overridden by a DOM element with the same id!

 //javascript function call:  
     createPicture({name: "aaa", width: 100, height: 100, tags: [] }) 

     //javascript function declaration:  
    createPicture({name, width, height, tags}) {   
    console.log(tags) //prints a DOM element with id "tags" instead of an empty array!  
    }

I know that DOM elements with ids create global variables in JS, but it is really weird to me that it overrides the attributes within the object in the function call. there is some way to protect the javascript code?

EDIT: I added a JSFiddle as suggested to confirm the issue. the problem appears if in the function declaration tags has a default value. if it is let empty, then there is no error. Fiddle here

cesarpachon
  • 1,179
  • 2
  • 10
  • 23
  • 4
    No. A destructuring pattern parameter does indeed create local variables. There's no way this is getting a DOM element unless you are passing it in or assigning it inside the function. – Bergi Nov 18 '19 at 22:00
  • 3
    Please post a [mcve] - the code you posted works as expected (after fixing the syntax error) – Bergi Nov 18 '19 at 22:01
  • hello @Bergi I added the fiddle as requested. I confirm the problem arises if the tags variable in the declaration has a default value. if it is let empty, then there is no error. – cesarpachon Nov 19 '19 at 12:21

1 Answers1

0

the problem appears if in the function declaration tags has a default value

function createPicture({name, width, height, tags: []}) { … }

That's not a default value, that's further destructuring - into an empty array pattern. It doesn't declare any parameter, it doesn't introduce any local variables, so when you log tags you do indeed get the global one (which refers to the DOM element for legacy reasons).

Your pattern works like

function createPicture(arg) {
    var name = arg.name,
        width = arg.width,
        height = arg.height,
        [] = arg.tags;
    …
}

The default initialiser you actually wanted is written as

function createPicture({name, width, height, tags = []}) { … }
//                                                ^
Bergi
  • 630,263
  • 148
  • 957
  • 1,375