473,769 Members | 2,348 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

undefined variables

yb
Hi,

Looking for clarification of undefined variables vs. error in
JavaScript code.

e.g.
<script>
alert( z ); // this will be an error, i.e. an exception
</script>

<script>
alert( this.z );
alert( window.z ); // both equivalent, no error, but window.z is
'undefined'
</script>

why is it that 'z' alone without the global object generates an error,
shouldn't it also be undefined? for example if i did

z = 0;

the javascript interpreter knows to create a global variable z

Feb 21 '06 #1
17 3350
yb wrote:
e.g.
<script>
The required `type' attribute is missing.
alert( z ); // this will be an error, i.e. an exception
</script>

<script>
See above.
alert( this.z );
alert( window.z ); // both equivalent, no error, but window.z is
'undefined'
The statements are not equivalent. `window' does not need to refer to
the Global Object. In fact, if the Global Object has a `window' property,
the second expression equals `this.window.z' implicitly.
</script>

why is it that 'z' alone without the global object generates an error,
Because it is specified so. See ECMAScript 3 Final, 8.7.1.
shouldn't it also be undefined?
No, it should not. See above.
for example if i did

z = 0;

the javascript interpreter knows to create a global variable z


That only seems so. You may add a property to the Global Object through
the scope chain with this; in global context the result would be equivalent
to that of `this.z = 0' then. However, the next object in the scope chain
may be a host object instead that does not allow for augmentation (or its
properties to be overwritten). IOW: assignment to undeclared identifiers
without base object are error prone. Always declare such as a variable
with the `var' keyword (a VariableStateme nt does not use the scope chain)
or use a base object reference.
PointedEars
Feb 21 '06 #2
yb
Thanks, that clarifies several questions I had.

I'm reading JavaScript 4ed by David Flanagan. On p.55, it indicates
that the scope chain includes the variables declared with 'var'
keywords.

Sorry I'm referencing a text that isn't online, I plan to do a more
thorough study of the official specs but am a bit confused by the
information in Mr. Flanagan's text.

Hope someone can clarify

Feb 21 '06 #3
yb wrote:
Looking for clarification of undefined variables vs.
error in JavaScript code.
Given that javascript has a primitive data type called - undefined - it
would be better to talk of undeclared variables rather than undefined
variables, as declared variables may have the value undefined.
e.g.
<script>
alert( z ); // this will be an error, i.e. an exception
</script>

<script>
alert( this.z );
alert( window.z ); // both equivalent, no error, but window.z is
'undefined'
</script>
An unqualified Identifier is evaluated by resolving it against the scope
chain and producing an instance of the internal Reference type as the
result. An Identifier naming an undeclared variable will result in a
Reference type that had - null - as its Base object and the Identifier
as the property name.

The constructs - this.z - and - window.z - are (dot notation) property
accessors. Property accessors also result in a Reference type when
evaluated, but if the part of the property accessor before the dot (or
opening square bracket in a bracket notation property accessor) does not
resolve as an Object type (and cannot be type-converted into an Object
type) an exception is thrown. The object that is the evaluated value of
the part of the property accessor before the dot becomes the Base object
of the Reference type that results from the evaluation of the property
accessor.

It is the difference in the value of the Base object in the two
Reference types that explains the difference in outcome. Any attempt to
recover a value with a Reference type that has a null Base object will
throw an exception. While any attempt to read the value of a
non-existent property with a Reference type that has a non-null base
object results in the - undefined - value.
why is it that 'z' alone without the global object generates
an error, shouldn't it also be undefined? for example if i did

z = 0;

the javascript interpreter knows to create a global variable z


The difference here is that the action is the assignment of a value
rather than its retrieval. Given an attempt to assign a value using a
Reference type that has a null Base object the interpreter uses the
global object in place of the non-existent Base object. Thus assignment
to an undeclared, unqualified Identifier results in the creation of a
property of the global object, and the assignment of a value to that
property.

Strictly this is does not represent the creation of a global variable,
but since declared global variables are created as properties of the
global object there is little practical distinction between a declared
global variable and a property of the global object created by
assignment at runtime. Declared global variable cannot be deleted and
dynamically created properties of the global object can be, but that is
not often a significant distinction.

However, it is good practice to never use an Identifier that refers to a
property of the global object without first declaring that Identifier as
a global variable. This 'best practice' helps to avoid and identify
scripting errors as it becomes obvious which Identifiers are intended to
refer to global variables, and which may just be leaking out of their
intended scope. It also avoids naming collision issues with properties
of the global object created by IE to represent DOM Elements that have
ID attributes, and are resistant to assignment in their natural state.

Richard.
Feb 21 '06 #4
Richard Cornford wrote:
<snip>
However, it is good practice to never use an Identifier that
refers to a property of the global object without first
declaring that Identifier as a global variable.

<snip>

That is not well worded as it suggests declaring Identifiers such as -
document - or - Array - prior to using them. The above only applies to
Identifiers of properties that are added to the global object by the
programmer. Native and Host properties of the global objects should not
be declared.

Richard.
Feb 21 '06 #5
yb
In rereading responses here (thanks Richard as well), it looks like the
variable declared with 'var' does become part of the scope chain but is
useful since we don't need to reference a call object in the scope
chain explicitly?

Feb 21 '06 #6
yb wrote:
In rereading responses here (thanks Richard as well), it looks like the
variable declared with 'var' does become part of the scope chain but is
useful since we don't need to reference a call object in the scope
chain explicitly?


Declared variables are properties of the Variable Object of the execution
context. So they are part of the scope chain of this context. However,
for their declaration the scope chain is not used: it does not matter if
you have declared the same variable before, especially not if it was
declared before in an outer execution context. A VariableDeclara tion
always creates a new property of the Variable Object of the context and
recreates it if such a property existed already.

var x = 0;
this.y = 23;
window.alert([x, y]); // 0,23

function foo()
{
// despite x is a global variable (and you would expect it to yield 0),
// x refers to the local variable in this context that was declared
// (see below) but not yet defined at this line
window.alert([x, y]); // [undefined],23
(function() { window.alert([x, y]); })(); // [undefined],23

var x = 42;
window.alert([x, y]); // 42,23
(function() { window.alert([x, y]); })(); // 42,23

// only a VariableStateme nt;
// variable instantiation comes before execution
var x;
window.alert([x, y]); // 42,23

// The local y variable is accessed instead of the global property;
// x refers to the local variable of the outer context instead of
// the global variable
(function() { var y = 11; window.alert([x, y]); })(); // 42,11

// a VariableDeclara tion replaces the previous value,
// `this' refers to the caller which is the Global Object;
// since either it has no property named `undefined' or it has
// a property named `undefined' with the `undefined' value
// (the latter conforms to ECMAScript), x is assigned the
// `undefined' value either way (provided nobody changed the
// value of the property before)
var x = this.undefined;

// modifies (or creates) a global property using the scope chain
y = 0;

// "[undefined],0" because x refers to the local variable and y
// to the modified global property
window.alert([x, y]);

// "[undefined],[undefined]" because y is declared as a local variable
// in the inner context even though there is a global property with
// that identifier already
(function() { var y; window.alert([x, y]); })();

}

foo();

// the global property can be deleted
delete y;

// the global variable cannot be deleted (has the DontDelete attribute)
delete x;

window.alert([x, this.y]); // 0,[undefined]
window.alert([x, y]); // ReferenceError: y is not defined
HTH

PointedEars
Feb 21 '06 #7
VK

Thomas 'PointedEars' Lahn wrote:
yb wrote:
In rereading responses here (thanks Richard as well), it looks like the
variable declared with 'var' does become part of the scope chain but is
useful since we don't need to reference a call object in the scope
chain explicitly?


Declared variables are properties of the Variable Object of the execution
context. So they are part of the scope chain of this context. However,
for their declaration the scope chain is not used: it does not matter if
you have declared the same variable before, especially not if it was
declared before in an outer execution context. A VariableDeclara tion
always creates a new property of the Variable Object of the context and
recreates it if such a property existed already.

var x = 0;
this.y = 23;
window.alert([x, y]); // 0,23


Anyone will finally pronounce the right word or not? I'm tired to wait.
:-)

var x = 0;
// and
this.y = 23;

if taken outside of function declaration (like in the samples)
addressing completely different namespaces.

var x = 0; creates new variable in the namespace of Global Object
(script execution context).

this.y = 23; adds new property to the Host Object (which is in the most
common case window object).

Most people used to look at this as one object, and most of the time it
doesn't produce big problems. Still one should remember that Global
Object and Host Object are very different. In the particular (OP's
case) an attempt to address undefined identifier in Global Objects
leads to runtime error
5009, "Undefined identifier" (JScript notation)
and
undefined (? keep forgetting to report), "... is not defined" (Firefox
notation)

Nevertheless an attempt to address undefined identifier in Host Object
simply returns undefined value.

Feb 21 '06 #8
VK wrote:
Thomas 'PointedEars' Lahn wrote:
yb wrote:
> In rereading responses here (thanks Richard as well), it looks like the
> variable declared with 'var' does become part of the scope chain but is
> useful since we don't need to reference a call object in the scope
> chain explicitly? Declared variables are properties of the Variable Object of the execution
context. So they are part of the scope chain of this context. However,
for their declaration the scope chain is not used: it does not matter if
you have declared the same variable before, especially not if it was
declared before in an outer execution context. A VariableDeclara tion
always creates a new property of the Variable Object of the context and
recreates it if such a property existed already.

var x = 0;
this.y = 23;
window.alert([x, y]); // 0,23


Anyone will finally pronounce the right word or not? [...]


The right word has been pronounced already but your judgment is probably
too clouded with notions of (inexistent) "dark secrets" to recognize that.
var x = 0;
// and
this.y = 23;

if taken outside of function declaration (like in the samples)
addressing completely different namespaces.
There are no namespaces in the discussed implementation (namespaces are
going to be introduced with ECMAScript Edition 4). There are execution
contexts (ECMAScript Edition 3 Final[1], section 10).
var x = 0; creates new variable in the namespace of Global Object
(script execution context).
When control enters the execution context (10.2), a variable x is created
as a property of the Variable Object of the execution context, with the
DontDelete attribute, before execution, through variable instantiation
(10.1.3).

Since the execution context is the global context here, it creates a
property of the Variable Object of the global context, which is is the
Global Object (10.2.1). When this VariableDeclara tion is eventually
executed, the AssignmentExpre ssion `0' initializes the variable (12.2).
this.y = 23; adds new property to the Host Object (which is in the most
common case window object).


Nonsense. It adds a new property to the object referred to with `this'.
In the global execution context, `this' is the Global Object (10.2.1).

The Global Object is _not_ a host object (4.3.8), it is a native object, and
a built-in object (4.3.6/7 and 15). It may have host-defined properties
that refer to itself. Its `window' property refers to the Global Object
itself in many HTML document object models (10.1.5). That a reference to
`window' cannot be identified per se with a reference to the Global Object
has been demonstrated already in the SVG DOM and in the Internet Explorer
HTML DOM.
PointedEars
___________
[1] <URL:http://www.mozilla.org/js/language/>
Feb 21 '06 #9
VK

Thomas 'PointedEars' Lahn wrote:
The right word has been pronounced already but your judgment is probably
too clouded with notions of (inexistent) "dark secrets" to recognize that.


Search results for "Host Object" /i : zero entries (besides mine)
this.y = 23; adds new property to the Host Object (which is in the most
common case window object).


Nonsense. It adds a new property to the object referred to with `this'.
In the global execution context, `this' is the Global Object (10.2.1).


Nonsense.

<script type="text/javascript">
alert(this.navi gator); // [Navigator object]
</script>

Outside of function "this" always refers to the Host Object which is in
the most common case is window object. If Books of ECMA indeed say
something else, it is plain wrong in that part.

Feb 21 '06 #10

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

Similar topics

6
3869
by: Will | last post by:
I downloaded a webcounter from http://www.math.sunysb.edu/~shafikov/computing/webcounter. It seems to be working but I have the following being printed to the page: Notice: Undefined variable: counter in g:\program files\apache group\apache\htdocs\dev\webcounter.php on line 73 Notice: Undefined variable: prefix in g:\program files\apache group\apache\htdocs\dev\dbclass.php on line 33
3
6123
by: Jason | last post by:
hello, i am new to PHP, so go easy. I am using the examples in the book: PHP: Your Visual Blueprint For Creating Open Source, Server Side Content In the section where they talk about getting values from a form submission, the book says:
0
1863
by: Dave | last post by:
Hi everyone, (I already posted this to the VS.NET IDE news group without any responses, so I'm attempting one more time in this group) The issue I'm having is occuring in the IDE of VS.NET 2003, although I'm not sure what is actually causing the problem. I can't summarize the issue, so please read on to find out more. I've created a BaseDialogEditor class that allows a developer (namely me) to create Modal editors for controls at...
10
5501
by: PCHOME | last post by:
Hi! Would someone please help me thess C error(in gcc on Linux)? The compiler continues to give me: readLP.o: In function `Input_Problem': readLP.o(.text+0x0): multiple definition of `Input_Problem' main.o(.text+0x2f2): first defined here /usr/bin/ld: Warning: size of symbol `Input_Problem' changed from 172 to 185 in
49
14522
by: matty | last post by:
Hi, I recently got very confused (well that's my life) about the "undefined" value. I looked in the FAQ and didn't see anything about it. On http://www.webreference.com/programming/javascript/gr/column9/ they say: <snip> The undefined property A relatively recent addition to JavaScript is the undefined property.
4
7191
by: John Oliver | last post by:
PHP Notice: Undefined index: name in /home/www/reformcagunlaws.com/new.php on line 6 PHP Notice: Undefined index: address in /home/www/reformcagunlaws.com/new.php on line 7 PHP Notice: Undefined index: city in /home/www/reformcagunlaws.com/new.php on line 8 PHP Notice: Undefined index: county in /home/www/reformcagunlaws.com/new.php on line 9 PHP Notice: Undefined index: zip in /home/www/reformcagunlaws.com/new.php on line...
6
6080
by: tshad | last post by:
I have a structure (which happens to be a Java DataBean that contains some string arrays) that is giving me an error. The error at the "for" statement is: Object reference not set to an instance of an object. Here is the code where chDataBean is the structure. chDataBean.voucherNumber is a string array of voucher numbers. But if there are no numbers the debugger shows it as <undefined value>. But other fields
45
4858
by: VK | last post by:
(see the post by ASM in the original thread; can be seen at <http://groups.google.com/group/comp.lang.javascript/browse_frm/thread/3716384d8bfa1b0b> as an option) As that is not in relevance to "new Array() vs " question or to the array performance, I dared to move it to a new thread. Gecko takes undefined value strictly as per Book 4, Chapter 3, Song 9 of Books of ECMA :-)
1
5548
by: yamitmehta | last post by:
When I compile to code using g++arm of VxWorks 5.5 and put it on my board i get the follwing undefined symbols:- Cpool and Csingleton are template classes. CPool has the static member variables:-ms_uCapacity ,ms_uAllocatedCount , ms_uLockCapacity ,ms_pmutex -ld < yamit/apps1.out Undefined symbol: _Q23m5tt5CPool1ZQ23m5t10CMarshaler$ms_uCapacity (binding 1 type 0) Undefined symbol: _Q23m5tt5CPool1ZQ23m5t10CMarshaler$ms_uAllocatedCount
0
9586
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
9423
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
10210
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
9861
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
8869
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6672
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
5446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2814
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.