Line 111, why is the variable shortUrl 'undefined' if it has just been defined above? Why isn't the variable global?

Hi all

Please help

Line 111, why is the variable shortUrl ‘undefined’ if it has just been defined above? Why isn’t the variable global?

Thanks for your time

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36

Challenge: URL Shortener Microservice

Link to the challenge:

Does it log undefined or does it throw an Uncaught ReferenceError: shortURL is not defined ?
Do you see this log? console.log('2 ' + shortUrl)?

You’re using loose comparison here:

if (urlPairFound != null) {
  var shortUrl = urlPairFound.shortUrl; 
  console.log('2 ' + shortUrl);

console.log('3 ' + shortURL);

If urlPairFound is undefined instead of null, this statement will be false and it’ll skip the if block. So I’d first check if urlPairFound is undefined.

Yes I see that log, as shown:

shortUrl and shortURL are not the same identifier.

Edit: BTW, it’s not global it’s function scoped.

Can I ask why are you redeclaring the variable 4 times? Personally, I would not suggest doing that. If you want block scoped unique variables use let or const. Otherwise, declare the var variable one time and reassign its value.

I managed to fix the problem

It consisted of two sub problems/mistakes

  1. A typo: I had written ‘shortURL’ instead of ‘shortUrl’ which was what I had used earlier when I declared the variable

  2. I was trying to use the ‘shortUrl’ variable OUTSIDE of the
    function(err, urlPairFound) {...}
    function, hence, the program had no clue what I meant by urlPairFound

Thanks for your time


This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.