0

My variable passed in a function is not being picked, look at the foollowing example:

<html>
<head>
</head>

<body> 
</body>

<script>
function sample (item, value){
    var object = {
    item: value
    }

console.log(object);
}

sample("one", false);
</script>

</html>

This will output:

{ item: "false" }

instead of:

{ "one": "false" }

why item is not being picked as input?

Dark Night
  • 451
  • 1
  • 4
  • 7
  • The "why" is because object literals/initialisers don't parse keys/properties as *Expression*s. When you provide an identifier, the name of the identifier itself is what's used. It's meant to be a convenience by allowing the quotations around the keys to be optional in many cases. – Though, as I mentioned in another comment, placing brackets around the key is a new syntax option that will determine the key from an *Expression*, allowing you to use variables, etc. – Jonathan Lonowski Mar 06 '16 at 05:09

1 Answers1

0

JavaScript object definition works this way. The interpreter assumes item is a string, rather than a variable. You should do this instead:

function sample(item, value){
    var obj = {};
    obj[item] = value;
    return obj;
}
JCOC611
  • 19,111
  • 14
  • 69
  • 90
  • 1
    In [supporting browsers/engines](https://kangax.github.io/compat-table/es6/#test-object_literal_extensions), this can now be `return { [item]: value };`. – Jonathan Lonowski Mar 06 '16 at 05:02
  • `{ \`${item}\`: value }` would make more sense tbh – JCOC611 Mar 06 '16 at 05:04
  • Perhaps. As of ES6, that isn't valid syntax (still need the brackets around the template string). Might be worth suggesting on [es-discuss](https://mail.mozilla.org/listinfo/es-discuss). – Jonathan Lonowski Mar 06 '16 at 05:14