Home > Mobile >  Prefixing a String to an array vs Prefixing a string to an array of objects - React/JS
Prefixing a String to an array vs Prefixing a string to an array of objects - React/JS

Time:05-04

Why With the below declaration and assignment

const num = [1,2,3,4,5];

is this allowed and will give [1,2,3,4,5] "Jello"

console.log(num   "Jello");

But with the below declaration and assignment

const num = { Flavour: "Apple" };

This will not give you Apple "Jello"

console.log(num   "Jello");

CodePudding user response:

(Note: the below links to pages on MDN, which started out as the documentation for the JS in Mozilla browsers, but applies beyond that these days.)

Firstly, for a b to return a sensible result, a and b should be of the same type. If they're different types, they must be coerced to the same type (see also ECMAScript 2021, section 7.1 "Type Conversion").

Furthermore, the addition operator only works on two types: numbers and strings (see also ECMAScript 2021, section 13.8 "Additive Operators"). Basically, if the operands aren't both numbers, then they're coerced to strings basically by calling their toString() methods (the exact process is a little more involved, and takes into account primitives, such as null, that don't have a toString method).

For arrays, Array.prototype.toString will call toString() on each element and join the results with a comma (the meat of it is defined in the specification for Array.prototype.join). The more general Object.prototype.toString will, for an object literal, return simply '[object Object]'. This value is comes from the specification for Object.prototype.toString, and has the form `[object ${Tag}]`, where Tag is a string representing the builtin type of the object.

To get a string containing a representation of an object, you need to use something like JSON.stringify:

JSON.stringify({ Flavour: "Apple" })   ' Jello'

If you just want the values, and the object is flat (i.e. no values are themselves objects), you can use Object.values:

Object.values({ Cost: "Cheap", Flavour: "Apple" })   'Jello'

If you want to join the values with something other than a comma, explicitly call join with the separator:

Object.values({ Cost: "Cheap", Flavour: "Apple" }).join(' ')   ' Jello'
  • Related