0

EDITS MADE: based on people's suggestions below, I made the following edits to my code.

The code is returning undefined. And nothing is getting console logged out. What am I doing wrong?

function test(arr, initialValue) {

      let reverseStr; 

      if (initialValue === {}) {
        reverseStr = {};
      } else {
        reverseStr = '';
      }

      console.log(reverseStr)

    }


    test(['a', 'b', 'c', 'd'], {})

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

I have the following code below:

function test(arr, initialValue) {

  console.log(initialValue)

  if (initialValue === {}) {
    let reverseStr = {};
  } else {
    let reverseStr = '';
  }

  console.log(reverseStr)

}


test(['a', 'b', 'c', 'd'], {})

I am expecting the invoked function to console log {}. Instead, I get ReferenceError: reverseStr is not defined

What am I doing wrong?

PineNuts0
  • 4,740
  • 21
  • 67
  • 112
  • `let` is block scoped – CertainPerformance May 26 '19 at 23:53
  • Also see [What's the difference between using “let” and “var”?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var) – Herohtar May 26 '19 at 23:54
  • It's not accessible outside of the `{}` it's defined in (the `if/else` statements). Declare it outside, and assign the value inside. – Jack Bashford May 26 '19 at 23:55
  • The issue with your first snippet is two fold. It returns undefined, since there is no return. That makes sense. You say it logs nothing, but it actually DOES log something, it's logging the empty string. Perhaps you were expecting an object, given the arg list you put into it. The reason you are not getting the object back is because objects are compared by reference equality, i.e: their identity, not by value. For example: `{} === {}` is always false in a JS console. Consider something like this for the check instead https://underscorejs.org/#isEmpty – Vaughan Hilts May 27 '19 at 00:51
  • Ah! Vaughan .. that makes sense; thank you for the detailed explanation – PineNuts0 May 27 '19 at 00:53

0 Answers0