it would help to diagnose what the problem is if you posted your entire html + javascript file so we can see exactly what is happening and where you are running the document.write()
your function doesn’t actually output anything. It just assigns values to variables and nothing else.
This works for me.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var n=5;
var x=n + n;
var y=n + n;
function get_xyz () {
var x = n;
y = n;
z = n;
[COLOR=red]alert('x = '+ x + "\
y = " + y + "\
z = " + z);
[/COLOR]
}
get_xyz();
</script>
</head>
<body>
</body>
</html>
It’s also worth noting that “x” inside of the function is instantiated using “var”, so it’s a local variable to that function, which is the point of the exercise - to demonstrate scoping in JavaScript
If you would use an alert outside of the function it would use the “x” that was defined at the start before the function, but after the function is called, x and y will have their values re-assigned.
Consider:
<script type="text/javascript">
var n=5;
var x=n + n;
var y=n + n;
function get_xyz () {
var x = n;
y = n;
z = n;
alert("Inside function:\
x = "+ x + "\
y = " + y + "\
z = " + z);
}
alert("1st Outside function:\
x = "+ x + "\
y = " + y + "\
z = "); // z is not defined yet
get_xyz();
alert("2nd Outside function:\
x = "+ x + "\
y = " + y + "\
z = " + z);
</script>
yep, it can get messy when you use variable names previously assigned to global variables as local variables in a function.
imho you should avoid using the same variable name as both local and global variables.
I’m not sure if that was the point of the exercise or if it was just an accidental error.
I think a clearer way of demonstrating scope would be something like:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var x=5; //global variable
alert('x outside function = '+ x);
function scope_demo() {
var y = 10; //local variable
alert('x inside function = '+ x +"\
y inside function = "+y);
}
scope_demo();
alert("\
y outside function = "+ y); //will generate an error saying y is undefined
</script>
</head>
<body>
</body>
</html>