1

<script>
  var name;
  var marks;
  var pass_status=true;
  document.writeln("name are:"+name);
  document.writeln("pass status is:"+pass_status);
  document.writeln("marks are:"+marks);
</script>

Can you explain why variable name is not showing me undefined?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
susmitha
  • 11
  • 1

2 Answers2

3

name is global variable ,just try :

console.log(window);

you will see that it has name property.that's why it is not undefined.

Smit Vora
  • 470
  • 3
  • 10
1

If you declare a var variable outside of any function, it’s assigned to the global object, which means window inside the browser. Since name is a standard property of window it already exists before your code snippet is executed. Check https://developer.mozilla.org/en-US/docs/Web/API/Window/name

So in your case calling name equals to window.name which is an empty string by default. To avoid such side effects it is recommended to use ES6 let/const variable declaration.

let name;
console.log(name);

The result will be undefined since name in this case is not attached to a global object.

Alexander
  • 77
  • 1
  • 1
  • 6