DEV Community

Sai gowtham
Sai gowtham

Posted on

JavaScript Quiz Part 2

If you want to answer part1 check out part1

1.How to reverse a String Using Reduce Method.

example: if you pass 'king' as an argument output is 'gnik'

2.what is the difference between slice and splice.

3.How to convert an object into a string?

Top comments (19)

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
 
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 😝

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
 
nektro profile image
Meghan (she/her) • Edited
// #1
"hello".split("").reduce((c,v,i,a) => c + a[a.length-i-1], "");

#2
// .slice returns a shallow copy of "substring" of elements in an Array
// .splice removes elements from elements at an index and can insert as well

#3
This is a bit of a trick question and depends on what you're looking for, and @avalander went into a lot of detail for this

Collapse
 
navi profile image
Navneet Sahota

1.How to reverse a String Using Reduce Method.

function reverseString(str) {
  const arr = str.split('');
  return arr.reduce((acc, val) => val + acc,"");
}

2.What is the difference between slice and splice?

  • Slice method is used to get some portion of the existing array/string.
  • Splice method actually mutates the existing array and can add or remove items from the array.

3.How to convert an object into a string?

  • Not Sure what you want as output. Others have explained it well though.
Collapse
 
learosema profile image
Lea Rosema (she/her) • Edited
  1. "Hello World".split('').reduce((a, b) => b + a)

  2. slice is a prototype function on Array and String. It doesn't mutate and returns a new Array/String that equals to an extract of the Array/String. splice is a prototype function on Array and is used to insert and delete elements at a given index of the array. It mutates the actual array and returns the deleted elements.

  3. You can explicitly call obj.toString() or you can use JavaScript's coercion: (obj + ""), so the obj.toString() method is implicitly called to convert it to a string. By default, the output is not too useful; it returns [object Object], but you can override the toString() method. Or, if you want to serialize the object into a string representation, you may want to use JSON.stringify(obj)

Collapse
 
sait profile image
Sai gowtham

Wow i was expecting this answer for reversing a string you can even do

const stringRev = (str)=>[...str].reduce((acc,e)=>e+acc)
Collapse
 
loilo profile image
Florian Reuschel • Edited

1) How to reverse a string using reduce method?

const rev = str => [...str].reduce((carry, char) => char.concat(carry), '')

Specifically, [...str] is superior to str.split('') because it correctly handles Unicode:

'😎'.split('') // ["�", "�"]
[...'😎'] // ["😎"]

2) What is the difference between slice and splice?

slice copies a range out of an array. splice deletes and/or inserts items at a given position in an array.

3) How to convert an object into a string?

The question's a little to broad imo, I'm gonna spare the time writing out exactly what Avalander did.

Collapse
 
jtkohne profile image
jtkohne
  1. First I just want to say why would you ever need to use the reduce method when working with a string when you can just simply do some casting from a string to array the back, especially since all you're trying to do is reverse the string. Since a lot of have already answered the question for the reduce method I offer you these two solutions instead...

"king".split("").reverse().join(""); // result will be "gnik"

You could also accomplish this with a simple loop

var str = "king";
var reversed = "";
var i = str.length-1;
while (i >=0) {
reversed += str[i];
i--;
}
// result in the reversed variable will be "gink"

  1. This one is constantly confused across JS developers. Splice actually returns a mutated version of the original array, and in the process actually modifies the array. Slice on the other hand can return a copy or a mutated version of the array, but the original array remains the way it was before the operation was executed. For example, if you try arr.splice(1, 1); it will literally remove a single item from an array starting at index 1. If you were to do the same thing with a slice operation, arr.slice(1, 1) it will start at index 1 and return 1 item in a new array (new array in memory). Splice also is used to manipulate arrays without the need to strore a returned result in a new variable since the original reference in memory is modified, whereas slice is intended to be used as a executable operation on an existing array and a returned value will either get passed as a parameter or stored in memory with it's own pointer and variable name.

  2. Avalander's answer is pretty concise, but if I were to give an answer based on how the question is worded it would have to be JSON.stringify(obj);

Collapse
 
ycmjason profile image
YCM Jason
reverseStr = ss => [ss].reduce(([...ss]) => ss.reverse().join(''));
Collapse
 
ben profile image
Ben Halpern

Loving these threads, Sai!

Collapse
 
thesudeep profile image
Sudeep Pandey

var input = "king";
var reverseString = input.split("").reduce((accumulator, currentValue, index, array)=> currentValue + accumulator);

Collapse
 
itsasine profile image
ItsASine (Kayla)

ELI5 version of #2: Slice returns a new array while splice modifies the original reference