Search code examples
javascriptnodesethereummetamask

Square Brackets for String in Javascript


I do not understand why I need to add square brackets around the "account" variable below, for the "accounts" variable constitutes a string.

 export default {
  name: 'App',
  data () {
   return {
    web3: null,
    account: null,
    contractInstance: null
   }
 },
 mounted () {
  web3Cont().then((res) => {
   this.web3 = res
   this.contractInstance = new this.web3.eth.Contract(contractAbi, contractAddress)
   this.web3.eth.getAccounts().then((accounts) => {
    [this.account] = accounts
  })
 }

Solution

  • From the name, I'm guessing that getAccounts returns multiple accounts, presumably as an array (or at least, some kind of iterable). Without the [], you're assigning that array to this.account. With the [], though, you're using destructuring to pick out just the first account from the array/iterable.

    Here's a simpler example:

    const accounts = ["a", "b", "c"];
    let variable1;
    let variable2;
    
    variable1 = accounts;
    console.log(typeof variable1, variable1); // "object" ["a", "b", "c"]
    
    [variable2] = accounts;
    console.log(typeof variable2, variable2); // "string" "a"

    I suspect you probably want some API other than getAccounts that returns a single account matching some criteria.