-3

When trying to write the following JavaScript code snippet in the Firefox web console then I get the following unexpected behaviour. Please refer to the below image.

When I declared a variable x then the undefined check evaluated to true. But when I defined it as "var a" then I get a seemingly wrong answer. I have checked it for Google Chrome, and it is working fine. What is the explanation for this obscure behaviour?

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    You must read [ask] – Amit Jul 15 '16 at 17:53
  • 2
    You must have defined `a` variables and then cleared the console and wrote this code again... In that case, `a` is not `undefined` – Rayon Jul 15 '16 at 17:54
  • Amit :Sorry ,I am new to this forum.I have read the "How to ask" webpage but I cant find any error.Can you please figure out ,at which point I made a mistake in asking?Thanks. – Harsh Krishna Jul 15 '16 at 18:04
  • More generally for the Firefox web console and "undefined": *[Chrome/Firefox console.log always appends a line saying 'undefined'](https://stackoverflow.com/questions/14633968)* – Peter Mortensen Oct 20 '20 at 18:19

2 Answers2

0

There's probably already a global variable named a and it has a value. The var a; declaration then doesn't create a new variable. Try changing your code to:

if (a === undefined) {
    console.log("undefined is true");
} else {
    console.log("undefined is false, a = " + a);
}

so you can see the value of the variable.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

I performed this same test in Chrome (v51.0.2704.106) and Firefox (v47.0.1), and found consistent results:

enter image description here

TheScrappyDev
  • 4,375
  • 2
  • 21
  • 25