There are some subtle differences, most of which are described here. However, the behavior you're seeing is because blank.length
is always greater than sentence[i].length
, and substring
swaps the arguments in this case. From MDN:
If
indexA
is larger thanindexB
, then the effect ofsubstring
is as if the two arguments were swapped; for example,str.substring(1, 0) == str.substring(0, 1)
.
But slice
doesn't do this. If the first argument is larger than the second, the result will be an empty string (assuming both are positive).
Try this:
for(var i = 0; i < sentence.length; i += 1) {
console.log(sentence[i] + blank.substring(blank.length, sentence[i].length) + i); //works
console.log(sentence[i] + blank.slice(sentence[i].length, blank.length) + i); //works
}
Or even this:
for(var i = 0; i < sentence.length; i += 1) {
console.log(sentence[i] + blank.substring(blank.length, sentence[i].length) + i);
console.log(sentence[i] + blank.slice(0, -sentence[i].length) + i);
}