473,763 Members | 1,382 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 1434

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
1703
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
19203
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
2064
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
1762
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
2355
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
25697
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
1527
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
5471
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
1388
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
9563
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9386
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
10145
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9998
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...
0
9822
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6642
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
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3917
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

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.