Home > Blockchain >  set returned values of function to variables js
set returned values of function to variables js

Time:12-21

How do I set multiple variables to the returned values of a function in javascript? This method does not work, names is undefined.

function data() {
    var names = ["logan", "harry", "josh", "harris", "jacob"]
    var nameFind = "harris"
    return names, nameFind
}

names, nameFind = data()

CodePudding user response:

JavaScript doesn't do tuples. Return an array or object instead.

You can use destructuring to simplify assigning the return values

// array
function data() {
  const names = ["logan", "harry", "josh", "harris", "jacob"]
  const nameFind = "harris"

  return [ names, nameFind ]
}

const array = data()
const names = array[0]
const nameFind = array[1]

// or with destructuring

const [ names, nameFind ] = data()
// object
function data() {
  const names = ["logan", "harry", "josh", "harris", "jacob"]
  const nameFind = "harris"

  return {
    names: names,
    nameFind: nameFind
  }

  // or with shorthand property names

  return { names, nameFind }
}

const obj = data()
const name = obj.name
const nameFind = obj.nameFind

// or with destructuring

const { names, nameFind } = data()

CodePudding user response:

In JavaScript, functions can only return a single value. The closest you can get to this is to return the values in an array:

return [names, nameFind]

...and then parse the array in the calling code

var result = data()
var names = result[0], nameFind = result[1]

Also, depending on the environment you're working in, the most modern versions of JS support de-structuring the returned value inline, like this:

[names, nameFind] = data()
  • Related