473,396 Members | 2,020 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

var declarations

Hi ALL!
I'm a bit new in a javascript and thus have some simple questions which
IMHO are obvious for most members of this group.
It is not clear for me what is difference between two declarations of
variables on level of *.js file.
For example:
// *** BEGIN JS FILE ***

myObj; // this is a global var

var myObj2; // is this a global var too?

// *** END JS FILE ***

Are there differences in declaration of variables above?
AFAIK myObj is a global variable. But what about myObj2. Is myObj2 a
global variable too? In other words is semantic of this two
declarations the same?
Thanks.

Dmitry

Jul 30 '06 #1
3 1420
trunikov wrote on 30 jul 2006 in comp.lang.javascript:
Hi ALL!
I'm a bit new in a javascript and thus have some simple questions which
IMHO are obvious for most members of this group.
It is not clear for me what is difference between two declarations of
variables on level of *.js file.
For example:
// *** BEGIN JS FILE ***

myObj; // this is a global var
this is illegal!

myObj = 7;

would be short for

var myObj = 7;

and that would be short for

var myObj;
myObj = 7;
>
var myObj2; // is this a global var too?

// *** END JS FILE ***

Are there differences in declaration of variables above?
AFAIK myObj is a global variable. But what about myObj2. Is myObj2 a
global variable too? In other words is semantic of this two
declarations the same?
Example, try this as a html file in IE or other browser:

<script type='text/javascript'>

myObj = 20; // shorthand for "var myObj = 20;"

var myObj2;
myObj2 = 10;

function test() {
myObj2 = 5; // modifies the global variable value
var myObj; // makes a local variable
myObj = 3; // sets the local variable value

alert( myObj ); // shows 3, local variable

alert( self.myObj ); // shows 20, global variable
}

test();

alert( myObj ); // shows 20, global scope

alert( myObj2 ); // shows 5, global scope

</script>
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jul 30 '06 #2
trunikov wrote:
<snip>
It is not clear for me what is difference between two
declarations of variables on level of *.js file.
For example:
// *** BEGIN JS FILE ***

myObj; // this is a global var
This is not a variable declaration. It is an Expression statement,
consisting of nothing but an Identifier. The statement is executed by
first resolving the Identifier against the scope chain to yield an
instance of the internal Reference type. In the global execution context
the only object on the scope chain will be the global object itself, and
as the global object has no properties named 'myObj' the Identifier will
not correspond with any property of any object on the scope chain and
the resulting Reference type will have a null 'base' object. The final
act in resolving the Expression statement is to call the internal
GetValue function, using the Reference type that was the result of
evaluating the Identifier as its argument.

Whenever the internal GetValue function is called with a Reference type
argument that has a null 'base' object an exception is thrown. Thus this
expression statement results in an error.

It is much more likely that you intended something along the lines of:-

myObj = 'something';

- which is another Expression statement, but this time the expression is
an assignment expression. An assignment expression evaluates the right
hand side of assignment operator (- = -) to a value and then resolves
the left hand side to a reference type, which it then used as an
argument to the internal PutValue function (along with the value, which
will be 'Put'). The Identifier - myObj - still resolves into a Reference
type with a null 'base' object, but when such a Reference type is used
with the internal PutValue function instead of an exception being thrown
a new property is created on the global object and the value is assigned
to that new property.

Following this dynamic creation of a new property of the global object
an subsequent attempts to resolve the identifier - myObj - will no
longer result in a reference type with a null 'base' object as the
global object is alwasy at the end of all scope chains and it now has a
'myObj' property (the Reference type will have the global object
assigned to its 'base' property).

That is unless:-

delete myObj;

- is executed, as - delete - would remove the property of the global
object and so it would not be found in subsequent Identifier resolution.
var myObj2; // is this a global var too?
During Variable Instantiation for any execution context (that is, prior
to the execution of any code for that execution context), for each
Identifier in a Variable Statement (- var VariableDeclaration List; -) a
property is created on the 'Variable' object for that execution context.
In the global execution context the global object is used as the
'Variable' object, so a global variable declaration results in the
creation of a property of the global object.
// *** END JS FILE ***

Are there differences in declaration of variables above?
As both assignment to an undeclared Identifier and a global variable
declaration both result in the creation of a property of the global
object these two actions seem similar. However, they are not identical;
In the two cases the properties of the global object are created at
different times, the first happens with the assignment (whenever that
happens) and second happens prior to the execution of any code in the
global execution context. In addition, in the case of a variable
declaration the property created on the 'Variable' object is internally
marked as - DontDelete -, which means that it cannot subsequently be
removed from that object with the - delete operator.
AFAIK myObj is a global variable. But what about myObj2.
Is myObj2 a global variable too?
Only - myObj2 - is a global variable, but the distinction between a
global variable that is effectively a property of the global object and
a runtime created property of the global object is minimal (only the use
of the - DontDelete - attribute and when the properties are created on
the global object).
In other words is semantic of this two
declarations the same?
No, and there are 'bast practice' and practical reasons for declaring
all variables that are intended to be global in the global execution
context. The practical reason being that browsers like IE create
properties of the global object for any DOM element with an ID
attribute, and many with NAME attributes. Subsequent attempts to assign
to these properties throw exceptions, but these properties are not
created when a javascript global variable has already been created with
the same name. Thus naming collisions that may only apply to some
browsers are avoided by the explicit declarations of global variables.

The 'best practice' reason for declaring all global variables is that it
makes identifying errors in the code easier, as omitting a function
local variable declaration will have any subsequent assignments to what
was intended to be a function local variable creating a property of the
global object. If all variables that are intended to be global are
rigorously declared in the global execution context such errors can
easily be distinguished from code that represent deliberate assignments
to global variables as no global declaration could be fount for the
Identifier that as intended to be local.

Richard.
Jul 30 '06 #3
People, thank you very much for your comprehensive answers. They are
very helpful.

Jul 31 '06 #4

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

Similar topics

9
by: Michael Tobis | last post by:
Summary of my understanding of a recent interesting thread: General usage has "declaration" meaning "statement which does not generate executable bytecode but merely affects the compiler". My...
0
by: Rikard Land | last post by:
I try to model a data definition language in XML. It can be seen as C without any executable statements other than variable assignments. I want to allow for: (1) type declarations ("structs" in...
2
by: Chris Gordon-Smith | last post by:
I am currently in India and have treated myself to the Indian reprint of O'Reilly's "C++ In A Nutshell". (Books in India come in at 1/3 to 1/2 of the price in Britain.) I thought that I would...
134
by: James A. Donald | last post by:
I am contemplating getting into Python, which is used by engineers I admire - google and Bram Cohen, but was horrified to read "no variable or argument declarations are necessary." Surely that...
9
by: MLH | last post by:
Would the following work if placed in a form module rather than a global module? Declare Sub InternetCloseHandle Lib "wininet.dll" (ByVal hInet As Long)
14
by: Arthur J. O'Dwyer | last post by:
Well, I'm trying to write that program that was requested a few weeks back, the one that could take struct definitions and create portable functions to read and write those structs. Hence the...
28
by: Michael B. | last post by:
I tend to use rather descriptive names for parameters, so the old style of declaration appeals to me, as I can keep a declaration within 80 chars: void * newKlElem...
1
by: Chris | last post by:
This may be more of a Visual Studio question but those groups seem to be full of unrelated stuff so hopefully this might be the right place. I have a class (no associated aspx file) which handles...
10
by: Andy Fish | last post by:
hi, I have an XSLT which is producing XML output. many of the nodes in the output tree contain namespace declarations for namespaces that are used in the source document even though they are...
7
by: aspineux | last post by:
Hi I read the PEP 3117 about the new "Postfix type declarations" in Python3000. THIS PEP as been REJECTED ! But ... The notation in the PEP is very ugly ! This make python code more...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...

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.