Defining variables

How can x be a variable in this script if it’s not declared using “var”?

<html>
<body>

<p id="intro">Hello World!</p>

<script type="text/javascript">
x=document.getElementById("intro");
document.write(x.firstChild.nodeValue);
</script>

</body>
</html>

JavaScript doesn’t require explicit declaration of variables. Any var that is instantiated without a “var” statement belongs to the global scope. Any var instantiated with the “var” statement belongs to the scope it was defined in.

In your case, because you have assigned a value to “x”, it is now a global var.

e.g.:

var x = 5;

y = 2;

function test() {
	var y;
	x = 10; //modifying the global
	y = 8; //y is defined in side the method with "var", so it is local
	z = 7; //also modifying the global
}
test();
console.log(x); //10
console.log(y); //2
console.log(z); //7

Didn’t know that. Thanks.