0

If I declare a variable and don't pass it a value it should be undefined. I'm confused why console logging my undefined variable name returns 'undefined' (as expected) but returns "string" when I use the typeof operator.

var name;
console.log(name); // undefined

typeof name; // "string"

This isn't important, just a curiosity. I also tried this with something similar, like:

var nameVar;
typeof nameVar; // "undefined"
console.log(nameVar); // undefined

The only thing I found poking around is that name might refer to a DOM element and (though this is just a guess) that might make it behave weirdly in this context? As far as I can tell there's no keyword, and if there was, I wouldn't be able to use it as a variable name.

Anthony
  • 330
  • 3
  • 13
  • 2
    `console.log(name); // undefined` Can't reproduce. Are you typing *directly into the console*? (If so, you're misinterpreting it - `console.log` returns `undefined`, but `name` exists as the empty string) – CertainPerformance Sep 15 '18 at 03:34
  • 1
    You can use `let` or `const` to shadow `name` on the global object. – MinusFour Sep 15 '18 at 03:38
  • @CertainPerformance I think I might be dealing with Chrome not clearing stuff out of memory very well. I refreshed the page several times and did all this just to make sure. – Anthony Sep 15 '18 at 03:47
  • I'm doubtful, I think it's more likely that you're misinterpreting what the console prints out, can you make a [MCVE]? – CertainPerformance Sep 15 '18 at 03:49
  • @CertainPerformance I don't think there's a need for condescension. What I typed in was behaving the way I said it would in my console. I did it several times before asking a question. I refreshed several times and it was still behaving this way. I just re-opened it and it's behaving differently. I'd have been happy to post a screenshot but the issue is resolved. – Anthony Sep 15 '18 at 03:50
  • Sorry, I'm not trying to be condescending, I just wanted to be able to reproduce the problem for myself (because if it were, then none of the answers on the linked question answer the question here, and this one could be re-opened :) ) – CertainPerformance Sep 15 '18 at 03:54
  • @CertainPerformance It's all good, I had read the posting guidelines and was trying to keep it within them. I read the other question you linked to and that seems to be what I was experiencing. Thank you for providing some information. Have a good night! – Anthony Sep 15 '18 at 03:59

0 Answers0