473,836 Members | 1,598 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Weird variable scope

Over the weekend I attended a session on JavaScript at the No Fluff
Just Stuff conference and learned an interesting quirk that I wanted to
ask a question about..

Take this code:

x = 5;

function foo() {
alert(x);
var x = 10;
alert(x);
}

foo();

The first alert will display 'undefined', and the second will display
10. Apparently JavaScript recognizes the 'var x = 10' declaration
inside foo() even before that line is reached - it spots the
declaration, but not the initialization to 10. Only after x is set to
10 and the second alert is reached will the 10 be displayed.

My question is... is there any way from this code to access the global
x variable (5) from within foo()?

Mar 15 '06 #1
13 1442

Joe Attardi wrote:
Over the weekend I attended a session on JavaScript at the No Fluff
Just Stuff conference and learned an interesting quirk that I wanted to
ask a question about..

Take this code:

x = 5;

function foo() {
alert(x);
var x = 10;
alert(x);
}

foo();

The first alert will display 'undefined', and the second will display
10. Apparently JavaScript recognizes the 'var x = 10' declaration
inside foo() even before that line is reached - it spots the
declaration, but not the initialization to 10. Only after x is set to
10 and the second alert is reached will the 10 be displayed.

My question is... is there any way from this code to access the global
x variable (5) from within foo()?


Try the following:

alert(window.x) ;

or

alert(window["x"]);

Mar 15 '06 #2
Joe Attardi wrote:
Over the weekend I attended a session on JavaScript at the No Fluff
Just Stuff conference and learned an interesting quirk that I wanted to
ask a question about..

Take this code:

x = 5;

function foo() {
alert(x);
var x = 10;
alert(x);
}

foo();

The first alert will display 'undefined', and the second will display
10. Apparently JavaScript recognizes the 'var x = 10' declaration
inside foo() even before that line is reached - it spots the
declaration, but not the initialization to 10.
No - it returns that x is undefined. That is, 'x' has not yet been
defined. You define it on the following line.
Only after x is set to
10 and the second alert is reached will the 10 be displayed.
Because now, x has been defined.
My question is... is there any way from this code to access the global
x variable (5) from within foo()?


Declare the global x variable as:
var x = 5;
Mar 15 '06 #3
On 15/03/2006 21:44, Joe Attardi wrote:

[snip]
x = 5;
All variables, including globals, should be explicitly declared using a
var statement.
function foo() {
alert(x);
var x = 10;
alert(x);
}

foo();

The first alert will display 'undefined', and the second will display
10. Apparently JavaScript recognizes the 'var x = 10' declaration
inside foo() even before that line is reached - it spots the
declaration, but not the initialization to 10. Only after x is set to
10 and the second alert is reached will the 10 be displayed.
Variable instantiation occurs before code execution begins, as described
in section 10.1.3 Variable Instantiation, ECMA-262 3rd Ed.[1]

Simply put, when the foo function is called, formal arguments, function
declarations, and variable declarations are processed to create local
variables. After that, execution begins with variable initialisation
occurring as assignments are evaluated.
My question is... is there any way from this code to access the global
x variable (5) from within foo()?


Yes, by access the global variable as a property of the global object.

With the code as-is, one can use the this operator to reference the
global object:

var x = 5;

function foo() {
alert(this.x); // 5
alert(x); // undefined
var x = 10;
alert(this.x); // 5
alert(x); // 10
}
foo();

However, as the value of the this operator can change depending on how a
function is called, an alternative may be necessary. Another option is
to use some variable that refers to the global object. The window
variable suffices in most cases, though I prefer to use my own:

var global = this,
x = 5;

function foo() {
alert(global.x) ;
alert(x);
var x = 10;
alert(global.x) ;
alert(x);
}
foo();

Mike
[1] <http://www.ecma-international.o rg/publications/standards/Ecma-262.htm>

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Mar 15 '06 #4
Tony wrote:
No - it returns that x is undefined. That is, 'x' has not yet been
defined. You define it on the following line. Not defined, but it has been declared. Otherwise, if no variable called
x was found at that point in foo, it would move up to the parent
environment (in this case the global scope) and find an x there. The
fact that it doesn't go up to the global scope means that at the first
call to foo(), the function DOES know about x. It just doesn't know its
value yet because it hasn't been defined. If you remove the var x = 10,
then both alerts refer to the x in the global scope (5).
Declare the global x variable as:
var x = 5;

That didn't work, because it's still finding something declared as x in
a more inner scope (the local var x within foo).

Mar 15 '06 #5
> Yes: alert(window.x) ;
That did it. Thanks!
By the way, "before that line is reached" isn't quite right.
Javascript functions are parsed before they are executed.
During that process, local storage for "x" is allocated because
it is declared as "var".

You're right. It was bad wording on my part. What I meant was more to
the effect of the instruction pointer, program counter, or whatever the
equivalent in JavaScript is, arrives at that line. Before that point,
the local storage is allocated (as you mentioned) but the value of 10
has not yet been assigned.

Mar 15 '06 #6
web.dev wrote:
Joe Attardi wrote:
My question is... is there any way from this code to access the global
x variable (5) from within foo()?


Try the following:

alert(window.x) ;

or

alert(window["x"]);


No, don't. We have discussed this ad nauseam before.
PointedEars
Mar 17 '06 #7
Joe Attardi wrote:
Yes: alert(window.x) ;

That did it. Thanks!


alert(this.x);

(if called as method of the Global Object) or

var _global = this, x = 42;

function foo()
{
alert(_global.x );
}

(no matter how it is called)

is much better. The host-defined `window' property of the Global Object
usually refers to the owning (Global) Object. But there does not need to
be such a host-defined property, that depends entirely on the environment
the script runs in.
PointedEars
Mar 17 '06 #8
Thomas 'PointedEars' Lahn wrote:
The host-defined `window' property of the Global
Object usually refers to the owning (Global) Object. But there does
not need to be such a host-defined property, that depends entirely on
the environment the script runs in.


And in a browser context (which is assumed on this group) that is always
true.
Using 'window' as the global object works in all browsers that support JS.

Writing:

var global = this;
or
var __GLOBAL = this;
etc

creates an unnecessary global variable which may actually be over-written by
any other code running on the same page.

Using 'window' as the global object for scripting in a browser environment
is the better practice, IMO.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Mar 17 '06 #9
Matt Kruse wrote:
Thomas 'PointedEars' Lahn wrote:
The host-defined `window' property of the Global
Object usually refers to the owning (Global) Object. But there does
not need to be such a host-defined property, that depends entirely on
the environment the script runs in.


And in a browser context (which is assumed on this group) that is always
true.


No, it is not.
PointedEars
Mar 17 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
1707
by: Afzal Mazhar | last post by:
What is wrong with this? class Example1 { public static long myClassVar; public static void Main() { { long myClassVar = 5;
23
19213
by: Russ Chinoy | last post by:
Hi, This may be a totally newbie question, but I'm stumped. If I have a function such as: function DoSomething(strVarName) { ..... }
22
2070
by: Daniel Rucareanu | last post by:
I have the following script: function Test(){} Test.F = function(){} Test.F.FF = function(){} Test.F.FF.FFF = function(){} Test.F.FF.FFF.FFFF = function(){} //var alias = function(){}; var alias = Test.F.FF.FFF.FFFF;
12
1768
by: sparks | last post by:
My boss and I both have access 97 and access 2003 installed on our systems. Lately he has been having a lot of problems. Databases that won't close. The database looks like it closes but access will not. And other weird things...I just passed it off as just MS nothing new. Yesterday I asked him to look at a little project...nothing much of anything. I put it up on our server and he opened it and went into design view. Its a form with...
2
2356
by: vlsidesign | last post by:
Here is my a portion of my program: #include <stdio.h> main() { int fahr, celsius; int lower, upper, step; int fc_conv(int fahr); ... snip ... }
1
25708
pbmods
by: pbmods | last post by:
VARIABLE SCOPE IN JAVASCRIPT LEVEL: BEGINNER/INTERMEDIATE (INTERMEDIATE STUFF IN ) PREREQS: VARIABLES First off, what the heck is 'scope' (the kind that doesn't help kill the germs that cause bad breath)? Scope describes the context in which a variable can be used. For example, if a variable's scope is a certain function, then that variable can only be used in that function. If you were to try to access that variable anywhere else in...
2
1534
by: Matt Nordhoff | last post by:
Sebastjan Trepca wrote: Python doesn't like when you read a variable that exists in an outer scope, then try to assign to it in this scope. (When you do "a = b", "b" is processed first. In this case, Python doesn't find a "value" variable in this scope, so it checks the outer scope, and does find it. But then when it gets to the "a = " part... well, I don't know, but it doesn't like it.)
112
5504
by: istillshine | last post by:
When I control if I print messages, I usually use a global variable "int silent". When I set "-silent" flag in my command line parameters, I set silent = 1 in my main.c. I have many functions that may print some messages. foo(...) { if (!silent)
11
1393
by: ssecorp | last post by:
I am never redefining the or reassigning the list when using validate but since it spits the modified list back out that somehow means that the modified list is part of the environment and not the old one. i thought what happend inside a function stays inside a function meaning what comes out is independent of what comes in. Meaning if I want the list I send as a parameter to the function I have to do x = func(x) and not just func(x) and x...
0
9671
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10553
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10596
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6980
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5829
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4459
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4021
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3116
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.