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?

Did you find this post useful? Show some love!

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'

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"'

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]'

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.

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).

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 😝

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

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

// #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

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.
Ben Halpern DEV.TO FOUNDER

Hey there, we see you aren't signed in. (Yes you, the reader. This is a fake comment.)

Please consider creating an account on dev.to. It literally takes a few seconds and we'd appreciate the support so much. ❤️

Plus, no fake comments when you're signed in. 🙃

  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)

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

const stringRev = (str)=>[...str].reduce((acc,e)=>e+acc)

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.

  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);

reverseStr = ss => [ss].reduce(([...ss]) => ss.reverse().join(''));

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

Classic DEV Post from Mar 3

Tools you need to use in your react components development 

As a react developer, I believe that everyone who is working on a react project must develop all the components separately for taking advantage of that components philosophy behind this amazing front-end framework.

READ POST
Follow @elaziziyoussouf to see more of their posts in your feed.
Sai gowtham
JavaScript developer, Writer & Aws certified solutions architect.
More from @saigowthamr
Build Your Own redux from scratch
#react #redux #javascript #webdev
JavaScript Quiz
#webdev #javascript #challenge
Trending on dev.to
Log and Exponential for Programmers
#explainlikeimfive #beginners #algorithms
Open source: Cookie notifier, MailChimp mod, Editable job listings & more
#showdev #opensource #webdev #javascript
Maps in Javascript ES6
#javascript
Proxymise Your Async Code
#javascript #coding
TIL: Element.prototype.matches can be used to check if an element includes a certain class
#javascript
Who are up to talk to and advice or seek for it?
#discuss #javascript #showdev
Memoization in a Nutshell
#explainlikeimfive #beginners #javascript
Programming revolves around this 3 things
#beginners #programmer