DEV Community


Discussion on: JavaScript Quiz Part 2

jtkohne profile image
  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];
// 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);