Daniel.Schroeder Daniel.Schroeder - 1 year ago 40
Javascript Question

JavaScript Function That Reverses Name Not Working Correctly (example from Learning JavaScript - O'Reilly)

I'm learning some JavaScript through Ethan Brown's "Learning JavaScript" book, and I've stumbled upon an example that doesn't perform as expected and I can't seem to figure out what the error is. I'm sure it's something obvious, I'm only on day 2 of learning this stuff but this is frustrating!

The section the code is from focuses on using the "this" keyword, and this example is supposed to show the correct way to use "this" in a nested function.

Here is the code (taken from the book, but I used my name instead of "Julie"!):

NOTE this book focuses on ES6, not ES5

const o = {
name: "Daniel",
greetBackwards: function() {
const self = this;
function getReversedName() {
let nameBackwards = "";
for (let i = self.length - 1; i >= 0; i--) {
nameBackwards += self.name[i];
return nameBackwards;
return `${getReversedName()} si eman ym , olleH`;

Expected output:


"leinaD si eman ym , olleH"

Actual output:


" si eman ym , olleH"



for (let i = self.length - 1; i >= 0; i--) {

Should be:

for (let i = self.name.length - 1; i >= 0; i--) {

As self refers to the object o. If you want the name, it has to be self.name.

Edit: You can implement the entire getReversedName function with:

return [...self.name].reverse().join(''); // ES6 spread operator