Please confirm my suspicions on variable ordering

F

Fabian

With teh following code, if I put picnames first, it wont work because
the other variables havent yet been defined, correct? That seems to be
the case. What I want to know is whether that is a feature or a bug.




var r1 = new Array(
"Anna",
"Jane",
"Hannah",
"Nayomi"
);
var r2 = new Array(
"My name is ",
"I'm "
);
//
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var d1 = r1[Math.floor(Math.random() * 4)];
var d2 = r2[Math.floor(Math.random() * 2)];
//
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var picnames = new Array(
"Good morning.",
"Good morning.",
"What's your name?",
d2 + d1 + ".",
"Thank you.",
"You're welcome."
);
 
L

Lee

Fabian said:
With teh following code, if I put picnames first, it wont work because
the other variables havent yet been defined, correct? That seems to be
the case. What I want to know is whether that is a feature or a bug.
var picnames = new Array(
"Good morning.",
"Good morning.",
"What's your name?",
d2 + d1 + ".",
"Thank you.",
"You're welcome."
);

It's a very important feature. When picnames is created,
the value of the fourth element is determined by evaluating
the current value of d1 and d2. If the values of d1 and d2
change, the value of the fourth element won't change.
That's the way you'll find that you almost always want it to
work.

If you want the fourth element of picnames to change when
you change d1 and d2, just change it at the same time.
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
With teh following code, if I put picnames first, it wont work because
the other variables havent yet been defined, correct? That seems to be
the case. What I want to know is whether that is a feature or a bug.

It is neither; it is a necessity.

The interpreter reads the code in order, executing what it finds; and
must already know about any variables on the right of an assignment.
After page load, functions may be called, and again all values needed
must be pre-defined, in terms of the chronological sequence of
execution.

Note : function X(Y) { Z } is a definition; the function is not
thereby executed, and the RHS may contain unknowns. In effect, the
function text is just remembered.

That's simplified.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top