DEV Community

Discussion on: JavaScript Quiz Part 2

Collapse
 
avalander profile image
Avalander • Edited

1.How to reverse a String Using Reduce Method.

const reverseStr = str =>
    (str.split('')
        .reduce((prev, c) => ([ c, ...prev ]), [])
        .join(''))

3.How to convert an object into a string?

Kinda depends on what you want.

const pony = {
    name: 'Twilight Sparkle',
    type: 'Unicorn',
    element: 'Magic',
}

// Option A because nothing beats '[object Object]' as a string representation
pony.toString() // '[object Object]'

// Option B
JSON.stringify(pony) // '{"name": "Twilight Sparkle", "type": "Unicorn", "element": "Magic"}'

// Option C
pony.toString = function () {
    return `${this.name}, ${this.type}, ${this.element}`
}
pony.toString() // 'Twilight Sparkle, Unicorn, Magic'

// Option D
pony.inspect = function () {
    return `Pony(${this.name}, ${this.type}, ${this.element})`
}
pony.inspect() // 'Pony(Twilight Sparkle, Unicorn, Magic)'

// Option E because why not
pony.toString = function () {
    return `${this.name}, ${this.type}, ${this.element}`
}
pony + '' // 'Twilight Sparkle, Unicorn, Magic'
Collapse
 
itsasine profile image
ItsASine (Kayla)

Slight error in your example: Twilight is an Alicorn. Source ❤️

Collapse
 
avalander profile image
Avalander

Haha, good catch! I'd update my post but I'm too lazy, so let's say I'm referencing the first season.

Collapse
 
loilo profile image
Florian Reuschel

Interesting fact for completeness: The JSON counterpart of toString() is toJSON(). If an object has a toJSON() method, it will be evaluated and its result will be stringified instead:

pony.toJSON = function () {
  return this.name
}

JSON.stringify(pony) === '"Twighlight Sparkle"'
Collapse
 
avalander profile image
Avalander

Nice! I wasn't aware of that!

Then we could potentially override that method to get [object Object] when converting it to JSON.

pony.toJSON = function () {
    return this.toString()
}

JSON.stringify(pony) // '[object Object]'
Thread Thread
 
loilo profile image
Florian Reuschel

That sounds... useful? 🙈
But yeah, it's a feature that I as well only discovered after many years of JS experience and since have never used in production. It's pretty cool though.

Thread Thread
 
loilo profile image
Florian Reuschel

Oh, and also the result would in fact be "[object Object]". The quotes are part of the serialized result (since it needs to be valid JSON).

Thread Thread
 
avalander profile image
Avalander

That sounds... useful? 🙈

I mean, the specification is that the object gets converted to a string. About the actual content of the string, the OP said nothing 😝