...

View Full Version : Problem with Code



NeoPuma
10-28-2004, 07:57 PM
hey there,
The code i'm about to give you, isn't for some reason, doing what its ment. Its not outputing anything.


function bold(form, txtbox) {
if(a == '1') {
txt = document.forms[form][txtbox].value
text = txt + '[/B]'
document.forms[form][txtbox].value = text
a = 0
}
else
{ txt = document.forms[form][txtbox].value
text = txt + '[B]'
a = 1
}
}

If you have any ideas please help...

kansel
10-28-2004, 08:10 PM
If you're not getting anything at all, please post more of your code (the form at least). If you're getting [/B] but not [B], you're missing a line from the else block.

Duplicate this line from the if block into the else block
document.forms[form][txtbox].value = text

NeoPuma
10-28-2004, 08:13 PM
Ok, I now have (fully):

<script type="text/javascript">

function bold(form, txtbox) {
if(a == 1) {
txt = document.forms[form][txtbox].value
text = txt + '[/B]'
document.forms[form][txtbox].value = text
a = 0
}
else
{
txt = document.forms[form][txtbox].value
text = txt + '[B]'
document.forms[form][txtbox].value = text
a = 1
}
}

</script>

<form action="index.php?p=members/cpanel&a=addreview2" method="post" name="addreview">
Game: <br>
<input type="text" name="Game"><br><br>
<u>Ratings</u><br>
Graphics: (1-10)<br>
<input type="text" name="Graphics"><br>
Sound: (1-10)<br>
<input type="text" name="Sound"><br>
Multiplayer: (1-10 [Enter 0 if no multiplayer])<br>
<input type="text" name="Multiplayer"><br>
Overall: (1-100)<br>
<input type="text" name="Overall"><br><br>
<u>Console And Review</u><br>
Consoles: <br>
<input name="XBox" type="checkbox" id="XBox" value="XBox">X-Box<br>
<input name="PS2" type="checkbox" id="PS2" value="PS2">PS2<br>
<input name="GC" type="checkbox" id="GC" value="GC">Game Cube<br>
<input name="GBA" type="checkbox" id="GBA" value="GBA">Game Boy Advance<br>
<input name="PC" type="checkbox" id="PC" value="PC">PC<br>
<br>
Review (No HTML):
<i>Tags</i><br>
<input type="Button" name="Bold" value="Bold" onclick="bold('addreview', 'Review')"></input>
<br>
<textarea name="Review" cols="40" rows="5"></textarea><br><br>
<input type="submit" name="Submit" value="Submit"><br>

Hope this helps you to help me!

-Neo

Roy Sinclair
10-28-2004, 08:18 PM
if(a == 1) {


Remove the quote marks, you're setting numeric values but testing alpha.

Also make sure you turn on notifications about javascript errors in IE or open the javascript console in Moz/Firefox so you can see when errors occur.

NeoPuma
10-28-2004, 09:36 PM
Ok, Thanks for that, And It's giving me the error:

Error: a is not defined
Source File: http://home.prcentral.co.uk/neo/gs/index.php?p=members/cpanel&a=editreview&id=5
Line: 51

I understand the error, but how am I ment to set a? I only wish to set it to 2 for example if its not equal to 1...so how would I do this?

-Thanks
-Neo

AaronW
10-28-2004, 09:49 PM
Do this:



a = 0; // Defines the global variable 'a'
function bold(form, txtbox) {
...

NeoPuma
10-28-2004, 10:03 PM
Wouldn't that set a to 0 even if its equal to 1? I only want it set to 0 if its non-existant

kansel
10-28-2004, 10:53 PM
Outside the function it will set a to 0 once, and only once. This is known as initializing the variable.

NeoPuma
10-28-2004, 11:40 PM
Ok, I now have:


<script type="text/javascript">

$a = 0;
$b = 0;
$c = 0;

function bold(form, txtbox) {
if(a == 1) {
txt = document.forms[form][txtbox].value
text = txt + '[/B]'
document.forms[form][txtbox].value = text
a = 0
}
else
{
txt = document.forms[form][txtbox].value
text = txt + '[B]'
document.forms[form][txtbox].value = text
a = 1
}
}

function italic(form, txtbox) {
if(b == 1) {
txt = document.forms[form][txtbox].value
text = txt + '[/I]'
document.forms[form][txtbox].value = text
b = 0
}
else
{
txt = document.forms[form][txtbox].value
text = txt + '[I]'
b = 1
}
}

function underline(form, txtbox) {
if(c == 1) {
txt = document.forms[form][txtbox].value
text = txt + '[/U]'
document.forms[form][txtbox].value = text
c = 0
}
else
{
txt = document.forms[form][txtbox].value
text = txt + '[U]'
c = 1
}
}

</script>And still get:

Error: a is not defined
Source File: http://home.prcentral.co.uk/neo/gs/index.php?p=members/cpanel&a=editreview&id=5
Line: 55

AaronW
10-29-2004, 12:26 AM
Dude... You defined it as $a, not a. You're confusing PHP/PERL with JS ;)

hemebond
10-29-2004, 01:36 AM
Ok, I now have:
$a = 0;
$b = 0;
$c = 0;That' PHP syntax. It should be
var a = 0;
var b = 0;
var c = 0;

AaronW
10-29-2004, 01:42 AM
Hey, that's what I said...

NeoPuma
10-29-2004, 12:33 PM
Dam you php >.<. Thanks guys - Works!
Your the best :P

-Neo

hemebond
10-29-2004, 10:02 PM
Hey, that's what I said...Yeah, that happens when it takes you an hour to get back to a tab.

AaronW
10-29-2004, 10:18 PM
Oh, and by the way, it isn't "var a", it's just "a". The "var" keyword suggests local to the current scope I believe. That's why it's used in object definitions.

I could be wrong though. I'm rather good at that.

hemebond
10-29-2004, 11:36 PM
The var keyword is used to declare a variable. The variables scope is dependant on where the variable is declared.

AaronW
10-30-2004, 01:52 AM
Ah, this is what I mean:


function doCow ()
{
var cow = 'moo';
}
function printCow ()
{
alert ('Cow: ' + cow);
}
doCow ();
printCow ();

Like that, you'll get a 'cow is not defined' error. Without the var, the variable is defined globally, and you'll get an alert with 'Cow: moo'.

SpiritualStorms
10-30-2004, 02:02 AM
What Aaron means is, that the dollar sign "$" is only charactoristic of languages other than JavaScript. JavaScript does not use special symbols to denote differences of variable types. There is to my knowledge, only one way of declaring a variable generally, and that is to use var. " If " that key term does not exist before an actual variable name, then that name will not really be understood as a variable. For this reason, you will need to do something like this,



// declaring, or creating, variables:
var a;
var b;
var c;


Do you see now how the key term var is used before anything else? And not like i am an expert, or anything, but you should realise that whenever you create a variable, you are simply reserving a certain amount of storage space in the programming language that you are working with. Think of a variable as a box, an empty box to be precise, if you dont put anything in it. The name of the variable simply becomes the address by which you essentially refer to a specific storage unit of memory.

What this means is, that if you do something like, var switch = false;, that what you are essentially doing is storing the object known as false in a box called switch. You must realise that this programming language works on what are called objects. An object is something that is generally a thing with certain charactoristics, and methods. All the charactoristics of an object are understood as a property, or an attribute, or an argument, depending on the context. For this reason, in order to deal with the manipulation of data, or content, you will be often required that you store your content, or data, in those storage units they call a variable. These variables are the only things literally that hold content, or data. Thus if i wanted to do a simple math function, i could do something like,



// declare your variables:

var a;
var b;
var c;

// now initialise the variables above:

a = document.myFrom.boxOne;
b = document.myFrom.boxTwo;
c = document.myFrom.boxThree;

// create a function:

function doMathAddition()
{

var tempBox:

if(a != "" && b != "")
{
tempBox = a + b;
}
else
{
alert("Please type numbers into their fields if you want to see me in action!"+ "\n");
tempBox="";
}
return tempBox;
}


The above is a rough idea of how variables work with if-statements, functions, and the what not.

Notice how with-in the function itself, i have created another variable? This was done because i needed a variable that would change content as a result of certain conditions being either true, or false. Since my final goal was to do math, i needed a temperary variable, hence tempBOX. Since tempBox is a play around with variable, i can use it in my final statement, which is a return command. I am saying, return whatever is in tempBOX.

Do you better understand?

hemebond
10-30-2004, 03:11 AM
Without the var, the variable is defined globally, and you'll get an alert with 'Cow: moo'.No, you'll get
Warning: assignment to undeclared variable cowIf you want a global variable, it must be declared outside of all functions.

AaronW
10-30-2004, 03:31 AM
Well I just ran my example and got the undefined error :P And got the alert when I removed 'var'.

SpiritualStorms
10-30-2004, 03:34 AM
from hemebond:

If you want a global variable, it must be declared outside of all functions.

That's not really true. I thought it was too, but i learned from this forum that it isnt really true. I think it depends on the browser, and the version of the standard you are working with. But as has been stated, a var inside a function makes that variable local to the function, but a var outside the function makes the variable global. This however does not mean that you cant make a variable global if it is inside a function. I know, odd, but its true. If you (for example) omit the var key term when you declare a variable inside a function, that variable will then have global status since you did not use the var key term when you created the variable.

In other words, it isnt so much location that determines whether or not a particular variable is global, or local, so much as the syntax, and/or protocal.




// global boxes:

var a;
var b;
var a;


// now a function with some global variables:

function cruncher()
{
a;
b;
c;
}

// Now a function with non-global status variables:

function cruncher()
{
var a;
var b;
var a;
}



Subtle differences, eh? Yet, all of the above examples demonstrate the difference of global status between all the above variables.

AaronW
10-30-2004, 03:36 AM
If you for example omit the var key term when you declare a variable inside a function, that variable will then have global status since you did not use the var key term when you created the variable.

As per my code example above :p

hemebond
10-30-2004, 05:06 AM
Subtle differences, eh? Yet, all of the above examples demonstrate the difference of global status between all the above variables.What you've done there is this declare global variables; reference those global variables from within a function; and declared variables local to a function.Nowhere have you declared a global variable from within a function.

SpiritualStorms
10-30-2004, 05:09 AM
Perhaps some of the more experienced coders could comment on this?

Like i said, your inclusion of the key term var will determine whether or not, a local variable is really local, or global.

hemebond
10-30-2004, 06:48 AM
*sigh* How about an example
var a; // global variable a

fuinction my_func()
{
var c = 0; // local variable c

a = 1; // assign the value 1 to the global variable a

b = 0; // ERROR! variable not declared
}Clearer?

Philip M
10-30-2004, 08:10 AM
There is a distinction between an undefined variable and a variable (which exists) whose value is undefined. It is possible (but not very sensible) to have two variables with the same name, one global and one local. In fact, in theory it would be possible to have many variables with the same name, one global and all the others local.

<SCRIPT>
var a; // GLOBAL variable a established
my_func();

function my_func(){
var c = 0; // local variable c established
var a = 10; // assign the value 10 to the LOCAL variable a
b = 90; // assign the value 90 to the global variable b
alert (a); // 10
alert (b); // 90
}

two();
function two() {
alert (a); // value of GLOBAL variable a is undefined (a exists but no value has been assigned to it)
alert (b); // 90
alert (c); // Error - variable undefined (there is no variable c available to this function)
}

</SCRIPT>

In short, my understanding is that if defined using var outside a function a variable is global. If defined within a function it is local.

Now I ask a question - bearing in mind that it is not very sensible to have two (or more!!) variables with the same name, is there any great advantage in choosing to make a variable local rather than global? Faster processing? (can hardly be significant).

SpiritualStorms
10-30-2004, 12:59 PM
from Philip M:

Now I ask a question - bearing in mind that it is not very sensible to have two (or more!!) variables with the same name, is there any great advantage in choosing to make a variable local rather than global? Faster processing? (can hardly be significant).


I will agree, but then again, in terms of computer processing time, even a nano second could be like a decade. I have read somewhere from Liorean that local variables cuts down on processing time, while global variables increase it. To what extent is this true, and to what extent, should one care, are issues that i cant really comment on. But i have read that yes, the global status makes some sort of difference.

With regards to the dispute going on in the previous posts, i still say that the moderators ought to throw in their well-informed commentaries. Hemebond is still doubting that what i say is true.

AaronW
10-30-2004, 03:28 PM
You'd want local variables when you're using multiple instances of an object.



a = new Obj ();
b = new Obj ();
a.setName ('Albert');
b.setName ('Bobby');
alert (a.name + ' and ' + b.name + ' are best friends.');


Edit: So you'd define all variables in your object with 'var ':



function Obj ()
{
var name; // Local to this object only, and to any instance of this object.
this.setName = setName;
}
function setName (str)
{
this.name = str;
}


And hemebond, your example does NOT throw an error (save for the typo in "function") when b is defined 0. It tells the global 'b' to be 0. This is in Firefox & IE6.

SpiritualStorms
10-31-2004, 02:14 AM
As an example of what i have said, here's one:


<script language="JavaScript1.2">
<!--
/*Credit JavaScript Kit www.javascriptkit.com*/

var dragapproved=false
var z,x,y

function move(){
if (event.button==1 && dragapproved){
z.style.pixelLeft=temp1+event.clientX-x
z.style.pixelTop=temp2+event.clientY-y
return false
}
}


function drags(){
if (!document.all)
return
if (event.srcElement.className=="drag"){
dragapproved=true
z=event.srcElement
temp1=z.style.pixelLeft
temp2=z.style.pixelTop
x=event.clientX
y=event.clientY
document.onmousemove=move
}
}
document.onmousedown=drags
document.onmouseup=new Function("dragapproved=false")
//-->
</script>

Tell me where the variable temp1, and temp2, are declared as being only local?

If declaring a variable within a function without using the var key term makes the variable local, then what becomes of the variable when it has the key term? Your whole argument revolves around the whole notion that the mere location of a variable determines whether or not it is global, or local. i am saying that the location itself does not make that determination. I am saying, as i have been told, that the syntax used in your declaration of a variable determins whether or not it is global, or local.

Philip M
10-31-2004, 07:56 AM
SpiritualStorms is quite correct, which can easily be seen by studying
the example that I have already posted.

WITHIN a function:-

var a = 10 // LOCAL
a = 10 // GLOBAL

Someone mentioned browser differences. Can anyone comment on this further with actual examples as if it is true then it sets a gigantic trap for the unwary.

SpiritualStorms
10-31-2004, 08:05 AM
from Philip M:

Someone mentioned browser differences. Can anyone comment on this further with actual examples as if it is true then it sets a gigantic trap for the unwary.


I cant actually provide examples of browser differences, but i think that with non-mozilla browsers, one is forced to declare their local variables with the key term var, otherwise, the variable will be shown as null, or not an object. Somehow, if a particular browser encounters a term in a function that doesnt have the var key term, it will consider it as an undefined term, or a non-object.

I stopped keeping track of browser differences a long time ago. It's a no win situation really. The huge difference in syntax between netscape, and microsoft is too overwhelming for me.

SpiritualStorms
10-31-2004, 08:14 AM
Taking Philip M's example:



function my_func(){
var c = 0; // local variable c established
var a = 10; // assign the value 10 to the LOCAL variable a
b = 90; // assign the value 90 to the global variable b
alert ( a ); // 10
alert ( b ); // 90
}


Do you see how b was assigned a value, even though the function itself did not use the var key term in order to declare b as a variable?

From your way of thinking, b must have been declared outside the function. What i am saying is, that is not always true. I know, it makes no friggin sense, to have this syntacal inconsistancy, but hey, i didnt come up with the rules. At any rate, Philips, and my examples, all demonstrate how the mere location of a variable does not determine its global status. It is location, plus the syntax.

Philip M
10-31-2004, 06:16 PM
Consider:-

function calculate (val) {
val = val * 2;
alert (val);
}

Is the variable val global or local?

In fact it is LOCAL. If val is accessed by another function it returns error val is undefined.

AaronW
10-31-2004, 06:21 PM
It's already local. You make it global with the line val = val * 2.

Philip M
10-31-2004, 06:35 PM
It's already local. You make it global with the line val = val * 2.

Not so! (I edited my post after you had posted but before viewing it).

As I say, val is and remains local. Try it!

<SCRIPT>
function calculate (val) {
val = val * 2;
alert (val);
gofwd();
}

function gofwd() {
alert(val);
}
</SCRIPT>

SpiritualStorms
10-31-2004, 06:40 PM
LOL....clearly, no one is listening.



from Philip M:

Consider:-

function calculate (val) {
val = val * 2;
alert (val);
}

Is the variable val global or local? If global how would you make it local?

And then there's Aaron:


It's already local. You make it global with the line val = val * 2.

Clearly, no one is agreed on what is global, and what is local.

Once more, i am inclined to agree with Philip. The reason being, if var in front of a term makes for a local variable, then a term without the key term in front of it must prevent the term from becoming local. Now, if the term is prevented from becoming local due to the fact that there's an absence of the key term var, then we must conclude that the term will instead gain a global status. If you disagree, then the question is once more raised: "What does the key term var in front of a term do to a term when the term is inside a function?"

This a clear example of "X can only be a C if X has J." X has J, therefore, X must be a C. If X has no J, then X can not be a C, since all Xs must have a C in order for them to be a J. Or as they teach in Philosophy: "All men are mortal. Socrates is a man. Therefore, Socrates is a mortal."

The same is said for the existance of the key term var inside a function. Either the existance of it makes a variable local, or it does not. If it does, then that key term must be different from when its outside the function. If it doesnt, then how do you distinguish between a call to an outside variable, and a local variable?

liorean
10-31-2004, 06:45 PM
Seems like it's time for me to clear things out. First, something for all of you to test
var
a='global',
b,
e=(function test(f){
var
a='local',
c='local';
b='global';
d='global';
alert('Local scope:\n '+['a is '+a,'b is '+b,'c is '+c,'d is '+d,'e is '+e,'f is '+f].join('\n '));
return 'global';
})('local'),
f='global';

alert('Global scope:');
try{
alert('a is '+a);
}catch(err){
alert('a is not defined in the global scope');
}
try{
alert('b is '+b);
}catch(err){
alert('b is not defined in the global scope');
}
try{
alert('c is '+c);
}catch(err){
alert('c is not defined in the global scope');
}
try{
alert('d is '+d);
}catch(err){
alert('d is not defined in the global scope');
}
try{
alert('e is '+e);
}catch(err){
alert('e is not defined in the global scope');
}
try{
alert('f is '+f);
}catch(err){
alert('f is not defined in the global scope');
}

SpiritualStorms
10-31-2004, 06:50 PM
Liorean, you had to give me a piece of code i cant even understand? That's a little unfair, dont you think?

I am glad a moderator is comming in to throw some light.

liorean
10-31-2004, 07:29 PM
So, what is happening here? First, let's see what variabels are declared where:
- The variables 'a', 'b', 'e' and 'f' are explicitly declared in the global scope by using a var statement.
- The variables 'a' and 'c' are explicitly declared in the local scope by using a var statement.
- The variable 'f' is explicitly declared in the local scope by being a formal parameter.

That mean we have the following variables:

globels locals
-- --
a a
b
c

e
f f



That's a beginning - we know what variables exist in each of the scopes from the start. Now, identifier resolution (meaning the way JavaScript finds what variable to store a value in) work in the following way:
01. If the identifier matches the name of a variable that exists in the current scope use that variable.
02. If the current scope is the global scope, go to 04.
03. Go up one scope in the tree and repeat the procedure starting from 01.
04. If the identifier matches a variable in the global scope, use that variable
05. If the the identifier does not match a variable in the global scope, create one and use it.

This mean that the code example above will do the following:
- In the global scope, assign the value 'global' to the variable indicated by the identifier 'a'
- In the global scope, assign the value returned from executing the function literal to the variable indicated by the identifier 'e'
- In the global scope, assign the value 'global' to the identifier 'f'.

- In the local scope, assign the value 'local' to the formal parameter associated with the identifier 'f'
- In the local scope, assign the value 'local' to the to the variable indicated by the identifier 'a'
- In the local scope, assign the value 'local' to the to the variable indicated by the identifier 'c'
- In the local scope, assign the value 'global' to the to the variable indicated by the identifier 'b'
- In the local scope, assign the value 'global' to the to the variable indicated by the identifier 'd'





Now, let's look at the results:
identifier global local
-- -- --
a 'global' 'local'
b 'global' 'global'
c undeclared 'local'
d 'global' 'global'
e 'global' undefined
f 'global' 'local'

What does these results tell us? Well, they just prove the identifier resolution as I explained above. In the local scope the value 'local' is stored in the local variable 'a', not the global variable 'a'. So, in the global scope the variable 'a' still contains the value 'global'. The variable 'b' didn't exist in the local scope, so instead the value got assigned to the global variable 'b'. The variable 'c' didn't exist in the global scope, but it did in the local scope, thus only the local variable 'c' got a value, it still doesn't exist in the global scope. The variable 'd' didn't exist in any scope, so it was created in the global scope, and assigned a value. The variable 'e' didn't exist in the local scope, and existed but didn't contain any value in the global scope, so it was undefined when read out locally. It was later assigned the value returned from the local scope. The local variable 'f' was a formal parameter, and wasn't really here to prove anything, except perhaps the feature of formal parameters to act just like were they local variables. It was in the global scope given the value of 'global'.

Philip M
10-31-2004, 08:02 PM
In short, you can have both a global and a local variable with the same name. This is absolutely guaranteed to cause mayhem. So don't do it!

Just as correct punctuation is important in English and if not used correctly can radically alter the meaning!

Liorean said Philip M is a genius.
Sorry, I'll read that again.
Liorean, said Philip M, is a genius.

hemebond
10-31-2004, 08:49 PM
The image attached to this post shows what fills my Javascript console when people don't declare variables correctly, liorean's post included. SS, what seems to be confusing you is the error correction being done for you. As liorean has shown, if a variable is accessed without being declared, it will be created for you at the global level, because that's the last scope level at which the variable is looked for. In stricter languages, this variable would not be created and you would get an error.

So, just like my code sample showed, by not using the var keyword within a local code block, it is assumed you are accessing a variable in a higher scope. In Javascript, if you have failed to declare this variable it will be created for you at the last scope checked, the global scope.

And to the person wondering about the benefits of local over global scope variables, a local variable is created when the scope is entered and destroyed when the scope is exited. Global variables exist for the life of the program.

liorean
10-31-2004, 09:37 PM
Hemebond: That's not an error at all. It's just a warning. You get them when you have the mozilla strict warnings enabled. They're good for tracking down some logic and intent errors. Of course, if you really want to follow the runtime you are better served by using Venkman.

hemebond
10-31-2004, 11:12 PM
Hemebond: That's not an error at all. It's just a warning. You get them when you have the mozilla strict warnings enabled.I never said it was an error, I did say it was a warning. However that just means the script will carry on and my console will still be filled with the messages.

Yes I do have strict warnings enabled, it helps me debug my scripts.

liorean
10-31-2004, 11:34 PM
Seems you're right about that, it was AaronW that called in an error.

AaronW
11-01-2004, 02:30 AM
*sigh* How about an example
var a; // global variable a

fuinction my_func()
{
var c = 0; // local variable c

a = 1; // assign the value 1 to the global variable a

b = 0; // ERROR! variable not declared
}Clearer?

Seems that's calling it an error...

That's the one I was referring to.

hemebond
11-01-2004, 03:18 AM
Seems that's calling it an error...

That's the one I was referring to.There we go, good catch. Still, while it may only generate a warning it's still an error. Using a variable without declaring it is bad.

Philip M
11-01-2004, 07:39 AM
"And to the person wondering about the benefits of local over global scope variables, a local variable is created when the scope is entered and destroyed when the scope is exited. Global variables exist for the life of the program."

I suspect that I am way out of my depth here, but this suggests that local variables require more computational effort to create/destroy them (especially if the function involved is called more than once), while global variables occupy storage space in RAM throughout the run time of the script. If that matters.

In most practical situations it does not seem that local variables are especially useful as compared with global, which is not to say that it is undesirable to use them. A nanosecond may be relevant in theory but in practice it is hard to see why it matters. To me the most important thing is as I have said - it makes sense to avoid using two or more variables with the same name (or even similar names capable of confusion such as theResult and Theresult).

As someone once said, "In theory, there isn't any difference between the theory and practice. In practice, there is".

SpiritualStorms
11-01-2004, 07:36 PM
From Lirean:

So, what is happening here? First, let's see what variabels are declared where:
- The variables 'a', 'b', 'e' and 'f' are explicitly declared in the global scope by using a var statement.
- The variables 'a' and 'c' are explicitly declared in the local scope by using a var statement.
- The variable 'f' is explicitly declared in the local scope by being a formal parameter.

That mean we have the following variables:



globels locals
-- --
a a
b
c

e
f f



You know, at the risk of looking as if though i am about to put a needle in your ballon, i was thinking about your example, and it dawned on me, that the idea of a parameter is a bit out of the scope of the main issue discussed. The main issue was about whether or not, there was a fundamental distinction between local, and global, variables, and about how either was created. This being the case, i didnt think that the inclusion of a parameter was necessary. I do not feel like a parameter is the same as a local, or a global, variable. A parameter is a variable, certainly, in the technical sense, but a parameter to me is more of a place holder for the passing of data into a function. You dont however declare a parameter in the same way you declare other variables. Well, maybe in Java, you declare a parameter in the same way you would declare other variables, but in JavaScript, a parameter is mainly a gateway by which a function is able to recieve additional data at the time the function is put into use, but other than that, a parameter is a bit different than normal variables.

I just thought i'd point that out.

liorean
11-01-2004, 07:55 PM
Let's show you an example that displays just why you should think of parameters as variables:
var
a='global';
(function test(a){
alert(a);
})();
// Alerts 'undefined', since there is a local identifier 'a'
// that has no defined value.Here, the parameter shadows the globel, acting exactly as a local variable declaration would.

hemebond
11-01-2004, 08:13 PM
A function argument is a local variable.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title></title>
</head>
<body>
</body>
<script type="text/javascript">
var a = 5;
function func1()
{
var a = 10;

func2(a);

alert(a); // 10
}

function func2(a)
{
a++;
alert(a); // 11
}

func1();
alert(a); // 5
</script>
</html>

SpiritualStorms
11-01-2004, 08:25 PM
from hemebound

The image attached to this post shows what fills my Javascript console when people don't declare variables correctly, liorean's post included. SS, what seems to be confusing you is the error correction being done for you. As liorean has shown, if a variable is accessed without being declared, it will be created for you at the global level, because that's the last scope level at which the variable is looked for. In stricter languages, this variable would not be created and you would get an error.


First off, what browser are you using? Your JavaScript console is way different from mine. Is that a distinct client from the built in IE internet warning dialogue boxes?

Actually, it isnt created. When a function tries to run itself, what it does is check for the meaning of its expressions, or commands. In other words, every term must be accounted for. For this reason, when it runs into a term it does not understand, it will automatically fire an error of some type. It isnt that the unofficially declared term is created for you, but rather, that it does not know what a specific term means. Thus, in the process of determining what a specific term stands for, it will generally assume somehow a variable that exists outside of itself.

In a strict programming language, the error report would be like, "I do not know what you mean by theValue. What does that term mean."

It is because of the fact that when it comes to programming you must ultimately tell the computer what anything means, or ought to, that in most programming languages, you are required to first declare the concept with which you will be working on. For this reason, the creation of a function is generally proceeded with the key term function. Once you have this, the computer then checks to see if it is indeed a true function, so it goes on to check the other features associated with the idea of a function, like the rounded brackets, or the spiked brackets, or whether or not, there are parameters. Once this is done, it will then try to actually run the function.

The same then must be applied to the idea of a variable. When the program begins to run, it will first check for the concepts it will be working with. If a term exists, but it doesnt have a key term, the program is programmed to respond in some unspecified manner. However, when a term has its key term, then the program in some ways is disarmed a bit, since the program is designed to understand some things automatically, like what the key terms var, function, new, array, math, event, and the what not stand for. Since a variable must be declared as such, any given term the program encounters, will run the risk of throwing the program out of whack, since it will not be a mind reader, and know, automatically, what is meant by a term it runs into.

I am not really confused about a lot of things. I just dont agree with the rules of a lot of things. In theory, programming is based on logic, but from what i have observed, this is not at all the case. If anything, a lot of the so called rules, are actually quite arbitrary. There is no reason, why you should say var, instead of, variable, or box. Yet, if you learn JavaScript, you are forced to type var. The same thing is true of a function. Why do we say function, instead of func, or f3? Hell, its not hard to imagine a programming language, where functions are distinguished from each other by a mere numerical designation. for example, the protocal, could very easily be, f1:-:, f3:-:, f5:-:. All of these structures could just as easily be understood as rules, if others were forced to accept them as such.

Here's an example:




bx^3: theValue1;
bx^3: theValue2;

theValue=3;
theValue=10;

f1:-: doAdd(){bx^6:=:, bx^6:=:, bx^6:=:};

doAdd()
{
theAnswer=theValue + theValue;
fire*theAbswer;
}


The above, could actually be implemented as an actual programming language, if you understand the idea of programming. It is simply a matter of what symbols you will use, and how you will designate them. All languages are based on association. It is only as a result of practise, and societal norms, that anyone speaks as they do. But in essence, there's no reason why anyone should call a dog, a dog. We just do.

kansel
11-01-2004, 08:42 PM
The console is a part of the Mozilla/Firefox browser. It makes debugging javascript a LOT easier than with IE's faulty error/warning dialogs. Also there's the Venkman console available for both Mozilla and Firefox browsers that allows a lot more control over script execution (start/stop points, etc.).

If you're working in HTML/CSS and Javascript, and you have the rights to do it, there's absolutely no reason you shouldn't go RIGHT NOW to mozilla.org (http://mozilla.org) and download either the Mozilla browser suite or the Firefox standalone browser. It's totally free, more compliant than IE, and will solve a lot of headaches. (and create some more probably)

liorean
11-01-2004, 09:21 PM
SpiritualStorms:

The reason for us using the keywords 'var', 'function' etc. when programming JavaScript are that those are the syntaces for various programming concepts chosen for usage in the JavaScript language. In another language, you might not need to declare them at all, you might need to declare them with a type, you might need to give them a dimension or rank, or declare their memory size. All of these things may be explicit or implicit. They are however consistent for the language.

If you want to discuss these aspects, I suggest you create a thread in the Computer Programming forum instead. It's not on topic for this forum, and this thread is sidetracked enough as it is.

SpiritualStorms
11-01-2004, 09:39 PM
I did not say a parameter was not a variable. I am merely saying that a parameter technically speaking is a bit different than other types of variables. Just as you would argue the difference between a parameter, and an arguement, i will argue that there's a difference between a parameter, and a variable in the strictest sense. Parameter acts like a variable, but the main point of a parameter really is to create a passage way into a function, because without it, you cant generally pass values to a function at the time you activate the function.



var tree="acorn";
var person="Stephen Hawkins";
var planet="Jupitar";

function doAlert(a, b, c)
{
var a=a;
var b=b;
var c=c;

alert("The first variable is a, and it has as a value " + a);
alert("The first variable is b, and it has as a value " + b);
alert("The first variable is c, and it has as a value " + c);
}


If you do the above, you should get an empty result because you have not really passed any data whatsoever into the function. Yes, you have 3 gates by which you will be able to pass data through, but unless you give it that data for that channeling to take effect, the function will not alert any actual values, since all you have done is connected a local variable with a specific door. You say something like var a=a, is not at all the same as,



var box1=20;
var box2=10;

var box3=20;
box3=box3+40;

alert(box3);


These are not the same concepts. There is the tendancy to interpret a=a as being the same as a equaling itself, but this isn't true in the context of a function. Each a is interpreted differently based upon its context. The first a is viewed as a local variable by the mere fact that it has the key term in front of it. The second a will be viewed as the name of the parameter you specified in the parameter section of the function. For this reason, it is nto an issue of a equaling itself as an assignment. We have 2 variables, in the technical sense, with the same name, but they are not the same variable.


function doAlert(a, b, c)
{

a=c;
b=b;
c=a;

alert("The first variable is a, and it has as a value " + a);
alert("The first variable is b, and it has as a value " + b);
alert("The first variable is c, and it has as a value " + c);
}


What do you think will happen with the above? Are the terms equaling themselves? Or are they equaling doors?

How about this:




var a;
var b;
var c;

function doAlert(a, b, c)
{

a=c;
b=b;
c=a;

alert("The first variable is a, and it has as a value " + a);
alert("The first variable is b, and it has as a value " + b);
alert("The first variable is c, and it has as a value " + c);
}


Do any of the above variables now contain any actual values? Or are in some ways, the above, similar to the others in the sence that you are basically connecting variables to doorways, but this time, the variables themselves are global, rather than local.



var a;
var b;
var c;

a="I love Logic!";
b="I love programming";
c="I love being a Geek";

function doAlert(a, b, c)
{

var a=c;
var b=b;
var c=a;

alert("The first variable is a, and it has as a value " + a);
alert("The first variable is b, and it has as a value " + b);
alert("The first variable is c, and it has as a value " + c);
}


Now, which a, b, and c, do you think the alerts will do? Will they do the globals, or the locals?

liorean
11-01-2004, 10:20 PM
You're not quite right there. Declaring a formal parameter is exactly the same as declaring a variable. However, they have the additional property of automatically being assigned the value of the corresponding argument sent to the function when the function is entered. The way you are using var statements in your example, you are just redeclaring already existing variables. JavaScript is constructed to allow this kind of sloppyness by not reinitialising the variable when declaring a variable with the same identifier as an already initialised variable. The reason for this sloppyness is two fold - the first reason is just that variables shouldn't shadow parameters. The second reason is to allow the usage of multiple scripts using the same variables, or multiple statements which redeclare the variable in the same scope.

Here's an example of two functionally equivalent functions:
function t0(a){
return a;
}

function t1(){
var
a=arguments[0];
return a;
}They do, in effect, do EXACTLY the same thing. The difference is that the first one does the assignment at a lower level and thus can be optimised far better by the engine.

If you look at your example function, it is effectively doing the same as the following:
function doAlert(){
var
a=arguments[0],
b=arguments[1],
c=arguments[2];
var a=a;
var b=b;
var c=c;
alert("The first variable is a, and it has as a value " + a);
alert("The first variable is b, and it has as a value " + b);
alert("The first variable is c, and it has as a value " + c);
}However, the JavaScript engine is smart, so it doesn't reinitialise those variables. Which means that the above code is effectively treated as the following:
function doAlert(){
var
a=arguments[0],
b=arguments[1],
c=arguments[2];
a=a;
b=b;
c=c;
alert("The first variable is a, and it has as a value " + a);
alert("The first variable is b, and it has as a value " + b);
alert("The first variable is c, and it has as a value " + c);
}And, in your case, that is not equivalent to but could as well have been done as
function doAlert(){
var
a=arguments[0],
b=arguments[1],
c=arguments[2];
alert("The first variable is a, and it has as a value " + a);
alert("The first variable is b, and it has as a value " + b);
alert("The first variable is c, and it has as a value " + c);
}which in turn is just the same as simply doing
function doAlert(a,b,c){
alert("The first variable is a, and it has as a value " + a);
alert("The first variable is b, and it has as a value " + b);
alert("The first variable is c, and it has as a value " + c);
}



The second case of yours, where you have both globels and locals, is functionally equivalent to
var
a="I love Logic!",
b="I love programming",
c="I love being a Geek";
function doAlert(a, b, c){
a=c;
c=a;
alert("The first variable is a, and it has as a value " + a);
alert("The first variable is b, and it has as a value " + b);
alert("The first variable is c, and it has as a value " + c);
}The var statements you used are superflous since the formal parameters with the same identifier have already initialised them. And of course, since the formal parameters are locals, the alerts will use them.

AaronW
11-01-2004, 10:22 PM
If you pass a global to a function whose parameter shares the same name with the global, are you essentially passing by reference? Or how do you pass by reference in JavaScript, as in PHP you tell the function to handle the variable by reference (its pointer, in a sense) by prefixing it with &:



$var = 1;
function inc (&$arg) {
$arg++;
}
inc ($var);
echo $var; // 2


*Rocks nervously in the corner*

SpiritualStorms
11-01-2004, 10:29 PM
Ok, in some ways, you seem to dodge some specifics. Are you telling me that you can pass values/content/data, to a function, without declaring any actual parameters? This is bordering on a previous thread where i had asked something similar.

liorean
11-01-2004, 10:37 PM
If you pass a global to a function whose parameter shares the same name with the global, are you essentially passing by reference? Or how do you pass by reference in JavaScript, as in PHP you tell the function to handle the variable by reference (its pointer, in a sense) by prefixing it with &:
/ - - - /
*Rocks nervously in the corner*JavaScript is pass-by-value. Always. It doesn't support explicit references. However, there is a quirk to it: Primitive objects (booleans, strings, numbers) are stored directly in the value field of variables. Compound objects (arrays, regular expressions, functions, objects) are stored in a separate object, and in the value field of the variables the reference to that object is stored. Thus, even though the language is pass-by-value, the value itself may be a reference, just like in Java.

SpiritualStorms
11-01-2004, 10:37 PM
I will contend that these are all different:



var a;
var b;
var c;

function doAlert( c, b, a )
{
var a;
var b;
var c;

alert(a);
alert(b);
alert(c);
}


You have 3 places in which variables exist. One outside the function. One in the parameter section. And the last inside the actual function. Which of any of the variables will the alert do? Is it doing the ones outside the function? Or is it doing the ones in the parameter? Or is it doing the one in the functions body? Forget the similarity in names. In purely conceptual scheme, how does it know which set of variables it will alert?

hemebond
11-01-2004, 10:41 PM
I get The first variable is a, and it has as a value I love being a Geek The first variable is b, and it has as a value I love programming The first variable is c, and it has as a value I love being a GeekAlong with the warnings shown in the attached image.

And SS, please start using the correct terms. It's not key term, it's keyword. They're not doors, they're function arguments, and they are variables being passed by value, and a local variable is created with the same name and value.

AaronW, Javascript always passes variables by value apparently http://www.webreference.com/js/tips/010210.html.
You have 3 places in which variables exist. One outside the function. One in the parameter section. And the last inside the actual function. Which of any of the variables will the alert do? Is it doing the ones outside the function? Or is it doing the ones in the parameter? Or is it doing the one in the functions body? Forget the similarity in names. In purely conceptual scheme, how does it know which set of variables it will alert?No! There are two scopes being use in your example. The global scope and the local scope. And it will alert the value assigned to a in the local scope because, while you may be passing the global variable to the function, it is being passed by value, and a local variable with that name and value is created.
var a = "global";
function doAlert(a)
{
a = "local";
alert(a); // "local"
}
doAlert(a);
alert(a); // "global"

liorean
11-01-2004, 10:49 PM
Ok, in some ways, you seem to dodge some specifics. Are you telling me that you can pass values/content/data, to a function, without declaring any actual parameters? This is bordering on a previous thread where i had asked something similar.It's in fact the same question. The answer is the same as then:

All JavaScript functions accept any number of arguments. When the function is called, to each formal parameter specified the corresponding argument will be assigned. All arguments will also be accessible by the argument vector. This is the total set of parameters (i.e. it includes also those that are not formal) allowing for a virtually infinite length of arguments.

The thing is, you're confusing explicit with implicit. No, you don't have to declare formal parameters for all arguments a function is to accept. That doesn't mean the parameters don't exist. They are just implicit.

SpiritualStorms
11-01-2004, 10:52 PM
Oh my god, i cant believe you are serious:


I get
The first variable is a, and it has as a value I love being a Geek
The first variable is b, and it has as a value I love programming
The first variable is c, and it has as a value I love being a Geek
Along with the warnings shown in the attached image.

And SS, please start using the correct terms. It's not key term, it's keyword. They're not doors, they're function arguments, and they are variables being passed by value, and a local variable is created with the same name and value.


Key word, key term...drink some coffee. If you want to get technical, its not an arguement, its a parameter. An arguement is what you give as a value to the parameter. But that is beside the point. I was using an analogy, a metaphor. I will call them door ways if i want.

They are not being passed by value. Its a place holder, for the holding of potential values. When you assign a paramter indentifier to a local variable, you arent assigning any values. You are only connecting variables. Hence, its a doorway.

liorean
11-01-2004, 10:59 PM
I get The first variable is a, and it has as a value I love being a Geek The first variable is b, and it has as a value I love programming The first variable is c, and it has as a value I love being a GeekAlong with the warnings shown in the attached image.
Nothing unexpected about that. The warnings are because the strict warnings warn about ECMAScript/JavaScript features that might obscure what actually happens. They are not entirely correct though, there is no shadowing taking place. What actually happens is that it overwrites the variable with another variable, and they warn because the variable overwritten is named the same as one of the formal parameters. The argument is still accessible using the arguments keyword.

SpiritualStorms
11-01-2004, 11:00 PM
HHmmmm....interesting:



from Liorean:

It's in fact the same question. The answer is the same as then:

All JavaScript functions accept any number of arguments. When the function is called, to each formal parameter specified the corresponding argument will be assigned. All arguments will also be accessible by the argument vector. This is the total set of parameters (i.e. it includes also those that are not formal) allowing for a virtually infinite length of arguments.

The thing is, you're confusing explicit with implicit. No, you don't have to declare formal parameters for all arguments a function is to accept. That doesn't mean the parameters don't exist. They are just implicit.


This is why, i come to these forums. I read, and to be honest, they dont always tell you the ends, and outs, of any given syntax.

Ok, so i can pass anything, to any given function, whether or not, i have declared the function with parameters? But the catch must be what? That i use the arguments property inside the function? I am still having a hard time for why then use parameters at all, if in fact, they arent even needed, since, in actuality they already exist, its just that they arent explicitly, and formally, declared as such.

This is giving me a headache.

liorean
11-02-2004, 12:07 AM
I will contend that these are all different:

var a;
var b;
var c;

function doAlert( c, b, a )
{
var a;
var b;
var c;

alert(a);
alert(b);
alert(c);
}
You have 3 places in which variables exist. One outside the function. One in the parameter section. And the last inside the actual function. Which of any of the variables will the alert do? Is it doing the ones outside the function? Or is it doing the ones in the parameter? Or is it doing the one in the functions body? Forget the similarity in names. In purely conceptual scheme, how does it know which set of variables it will alert?
No, not quite. There are just two scopes here. Variables exist in either the global scope or in the local scope of the function. Let me walk you through exactly what happens in that code, just as it looks:

The engine does one initialisation pass over the global code, initialising a variable for each of the identifiers 'a', 'b', 'c' and 'doAlert'. For the latter, it also compiles the function declaration to a function object which it assigns to the 'doAlert' variable. (Yes, it's a variable.)
The engine starts it's execution pass. Since there is no code to execute it will soon enter a dormant state.

Okay, that was anticlimactic. So what happens if a function call would take place? Add
doAlert(b,c,a);at the end, and we'll see what happens now (simplified, of course, it's quite a complex process to describe in full): See point 1 above
Execute the call expression we just added -->
Get the value of the variable associated with the 'doAlert' identifier
Get the value of the variable associated with the 'c' identifier
Get the value of the variable associated with the 'b' identifier
Get the value of the variable associated with the 'a' identifier
Call the function returned from point 3 with the values returned from point 4,5 and 6.
Enter the new scope (ignore just how the scope chain and context passing is done, it's not important for us right now)
Assign all arguments passed to the function to the Arguments object
For all formal parameters specified, create a new variable associated with their specified identifier. If an argument corresponding to the formal parameter was passed to the function, assign its value to the corresponding variable.
Do a pass through the function looking for variable and function declarations, and initialise them, in the same manner as point 1. If they are already initialised, don't reinitialise. (Meaning that the variable declarations doesn't replace the formal parameters with the same identifier - they instead just equate to the same variable.)
Start the execution pass through the function
Do an identifier lookup for 'alert'. (Can't find in local scope, so go one scope up. There is can be found, so it uses it.)
Do an identifier lookup for 'a' (can be found in local scope, so it uses that one)
Call the function returned from 13 with the argument returned from 14.
Repeat 13-15 with 'b' substituted for 'a'
Repeat 13-15 with 'c' substituted for 'a'

hemebond
11-02-2004, 02:11 AM
Nothing unexpected about that.Exactly. It was posted to show SS.

SS, from the Javascript manual
A function definition consists of the function keyword, followed by The name of the function. A list of arguments to the function, enclosed in parentheses and separated by commas. The JavaScript statements that define the function, enclosed in curly braces, { }. The statements in a function can include calls to other functions defined in the current application.
All parameters are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.

SpiritualStorms
11-02-2004, 02:59 AM
Who are you quoting:



All parameters are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.

SpiritualStorms
11-02-2004, 03:05 AM
What is the site of the JavaScript manual? What manual?



A function definition consists of the function keyword, followed by
The name of the function.
A list of arguments to the function, enclosed in parentheses and separated by commas.
The JavaScript statements that define the function, enclosed in curly braces, { }. The statements in a function can include calls to other functions defined in the current application.


Well, Liorean, looks like you lied to me. You were the one who told me about the differences between arguments, and parameters.

liorean
11-02-2004, 04:16 PM
The "manual" as hemebond calls it, are the Netscape DevEdge JavaScript Guide and Reference. (Since DevEdge is gone in the AOL restructuring of Netscape you'll have to find them elsewhere.)

The Netscape documents are geared towards less technical users, and don't make that distinction because they are close enough to be considered the same. The ECMAScript Specification does not equate them, however. Formal parameters are syntactical elements describing the function object, arguments are runtime values sent to the function when called. Let's quote ECMA-262 3ed.
10.1.3 Variable Instantiation

Every execution context has associated with it a variable object. Variables and functions declared in the source text
are added as properties of the variable object. For function code, parameters are added as properties of the
variable object.

Which object is used as the variable object and what attributes are used for the properties depends on the type of
code, but the remainder of the behaviour is generic. On entering an execution context, the properties are bound to
the variable object in the following order:

For function code: for each formal parameter, as defined in the FormalParameterList, create a property of the
variable object whose name is the Identifier and whose attributes are determined by the type of code. The values
of the parameters are supplied by the caller as arguments to [[Call]]. If the caller supplies fewer parameter values
than there are formal parameters, the extra formal parameters have value undefined. If two or more formal
parameters share the same name, hence the same property, the corresponding property is given the value that
was supplied for the last parameter with this name. If the value of this last parameter was not supplied by the
caller, the value of the corresponding property is undefined.

For each FunctionDeclaration in the code, in source text order, create a property of the variable object whose
name is the Identifier in the FunctionDeclaration, whose value is the result returned by creating a Function object
as described in section 13, and whose attributes are determined by the type of code. If the variable object
already has a property with this name, replace its value and attributes. Semantically, this step must follow the
creation of FormalParameterList properties.

For each VariableDeclaration or VariableDeclarationNoIn in the code, create a property of the variable object
whose name is the Identifier in the VariableDeclaration or VariableDeclarationNoIn, whose value is undefined
and whose attributes are determined by the type of code. If there is already a property of the variable object with
the name of a declared variable, the value of the property and its attributes are not changed. Semantically, this
step must follow the creation of the FormalParameterList and FunctionDeclaration properties. In particular, if a
declared variable has the same name as a declared function or formal parameter, the variable declaration does
not disturb the existing property.However, I was wrong about something. Changing the value of a formal parameter DOES change the corresponding element in the arguments object.
10.1.8 Arguments Object

When control enters an execution context for function code, an arguments object is created and initialised as
follows:

The value of the internal [[Prototype]] property of the arguments object is the original Object prototype object, the
one that is the initial value of Object.prototype (section 15.2.3.1).

A property is created with name callee and property attributes { DontEnum }. The initial value of this property is
the Function object being executed. This allows anonymous functions to be recursive.

A property is created with name length and property attributes { DontEnum }. The initial value of this property is
the number of actual parameter values supplied by the caller.

For each non-negative integer, arg, less than the value of the length property, a property is created with name
ToString(arg) and property attributes { DontEnum }. The initial value of this property is the value of the
corresponding actual parameter supplied by the caller. The first actual parameter value corresponds to arg = 0,
the second to arg = 1, and so on. In the case when arg is less than the number of formal parameters for the
Function object, this property shares its value with the corresponding property of the activation object. This
means that changing this property changes the corresponding property of the activation object and vice versa.



Finally, this is the way a function definition is defined in the ECMA-262 3ed specification, which differs from how Netscape defines them:
13 Function Definition

Syntax

FunctionDeclaration :
function Identifier ( FormalParameterListopt ) { FunctionBody }

FunctionExpression :
function Identifieropt ( FormalParameterListopt ) { FunctionBody }

FormalParameterList :
Identifier
FormalParameterList , Identifier

FunctionBody :
SourceElements



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum