Jump to content

Six More Beginner Questions


violagirl
 Share

Recommended Posts

1. In switches, do variables declared in a case only exist in that case or from every case after that one? What I thought was that if you used break; at the end of a case, all variables declared in that case would not continue on to the next case, but if you didn't put in the break; for whatever reason, they would bleed over into the next case and so on until a break; was written. Am I right on this or is it a little different?2. This next question is just a question of whether this is good code or not. I KNOW it works, but is there a better way to do this, or is this way good?

<script type = "text/javascript"><!--do  {  var name = prompt ("What is your name?","");   };while (name != "Megan");//--></script>

3. Is there a way to make a box like a confirm box, except you choose what the buttons say rather than them having OK and Cancel?4. Are there cases where you would use the continue; out of an if statement? Like I know you usually see it as if (...) {continue;};, but I have seen the break used out of if statements, like for the end of cases on switches. Are there any cases where continue; is not used as an if statement, then? Just wondering.5. Is it best to declare or NOT declare the variable used in the perimeters in a for statement beforehand? And if you DO declare it beforehand, is it a bad thing to leave it out in the perimeters? (I noticed you can so long as you don't omit that semicolon)6. This too is just a question of style. Is this a good way to use a break? Or would it be better to just have the while statement be while (name != null && name != "Megan");??

<html><body><script type = "text/javascript"><!--do  {  var name = prompt ("What is your name?","");  if (name == null) {break;};  };while (name != "Megan"); //--></script></body></html>

Thanks in advance!Megan

Link to comment
Share on other sites

1. im not sure just try it, variables created in a case will probable only exist in that case, having them exist for the others isnt logical (if u wanted to just use a global variable). break will get u out of the loop and continue with the code after that if any, for instance if u had case 1: case 2: and case 3:, and the variable = 1 {statment, break} it would skip case 2 and 32. depends on what you want to get done, seems like ur only letting some one in if they know the correct value, 3. not to my knowledge4. hmm, cant think of any atm, 5. u have to declare the parameters when u create a function other wise that function has no parameters, it just has to use global variables, if u do use them you have to put something in when u make a call to that function otherwise ur function variales wouldnt have any value and would do the same stuff, it might just make the variables null or 0, im not sure6.again not usre

Link to comment
Share on other sites

For number five, I meant... for example....

<script type = "text/javascript">var i = 0;for (i = 0, i < 5, i++){...};</script>

Here's another, with txt being defined beforehand as "" for "seemingly" no reason (or is it just to make it global?):

<script type="text/javascript">var txt=""function message(){try   {   adddlert("Welcome guest!")   }catch(err)   {   txt="There was an error on this page.\n\n"    txt+="Error description: " + err.description + "\n\n"   txt+="Click OK to continue.\n\n"   alert(txt)   }}</script>

Seems kind of pointless to me, but I have already this and a few other similar situations done already, so I couldn't help wondering if there was a good reason to do so.And as for number three, does anyone else know more about this? Even if it was more like radio buttons in an alert box, where you choose one or the other. I just want to know if there is a way to do this or not.Otherwise, thanks for the help! :)

Link to comment
Share on other sites

2: The only thing I'd add here is that there is no indication to the user that s/he is doing anything wrong and s/he may feel that your code is "broken" because it keeps asking for a name. :)3: No. I believe there was a way to do it in VBScript, but that only works in IE so there's really no point unless you are developing for an IE-only audience. You might look into using something like ThickBox (do a Google search for that) which can emulate modal windows (like javascript confirm). If you used those, you can make the window look like anything you want. :)4: The keywords continue and break are used in loops. There's really no point in using a continue in an if statement unless that if statement is in a loop. It's used to skip the rest of the loop, but to still continue to iterate through the loop.

var i, item;var count = myArray.length;for(i = 0; i < count; i++){	item = myArray[i];	if(item == true)	{		continue;	}	alert("It's false!");  }

5: For an example, look at the code above. The variable "i" doesn't necessarily need to be declared outside of the for loop, however, because it is, it can then be used after the for loop ends. Imagine if instead of using the continue, we used break. Then, if we check "i" after the loop ends, we can tell which element of the array caused the loop to end. "item" is declared outside of the loop because it is never a good idea to declare variables inside of a loop. If you declare it once outside, then you simple overwrite the values each time through the loop. If you declare it inside the loop, the computer has to set aside memory, use the value, then get rid of the memory, then, next time through the loop it has to set aside memore, use the value, then get rid of the memory. It's more effecient to do it that way. Also, with the count variable there. If we hadn't used count to get the length of the array before iterating through the loop, then each time through the loop we'd have to check the size of the array to see if we need to continue. This isn't much of a big deal in this case, but imagine a page with 100 links and you wanted to iterate through each of them:

for(var i = 0; i < document.getElementsByTagName("a").length; i++){}

vs.

var theAs = document.getElementsByTagName("a");var count = theAs.length;for(var i = 0; i < theAs.length; i++){}

In the first example, each time through the loop you'd have to get the document object. Then you'd have to traverse through the document object to get all the a tags. Then you'd have to traverse through that array to get the length of the array. This would all need to be done 101 times. That would be MUCH slower than the second method. 6. I believe that is just a matter of style. The only thing I can add here is that when you use && to check more than one item in an if statement, only the first item needs to be false for the whole thing to be false. For example:

var test = false;if(test == true && NonExistentVar == false){}else{	alert("Howdy!");}

That snippet won't throw any errors because "NonExistentVar == false" is never evaluated because test == false. So, using && in an if statement can sometimes be more efficient than using multiple if statements.Same thing goes with ||. If the first item is true, the rest of the test doesn't need to happen.

Link to comment
Share on other sites

2: The only thing I'd add here is that there is no indication to the user that s/he is doing anything wrong and s/he may feel that your code is "broken" because it keeps asking for a name. :)
So how would you DO that? If I wanted to have the first time have that prompt box pop up, and then if they still didn't do it correctly, to have another prompt box pop up with something like "Can't you guess?" until they get it right. Well, this is what I TRIED, but it doesn't work, so how would I do it? I tried a number of things and none of them worked. This actually applies to another situation with a similar thing, which I couldn't figure out how to do, so if someone could tell me how to do this, it will help me out with the other thing too, so it would be MUCH appreciated!
script type = "text/javascript"><!--var name = prompt ("What is your name?","");  while (name.toLowerCase() != "megan");  {  name = prompt("What, can't you guess?","");  };//--></script>

Oh, wait, wait, I think I figured it out. Is this a good way to do it?

<script type = "text/javascript"><!--var whee, name;name = prompt ("What is your name?","");do  {  if (name.toLowerCase() != "megan")	{	whee = prompt("What, can't you guess?","");	if (whee.toLowerCase() == "megan") {break;};	};  };while (name.toLowerCase() != "megan");  //--></script>

I guess sometimes you DO figure things out if you think hard enough! Is that the usual way of doing such things? My only problem with it is I am trying to make it so the user can't press cancel. :-p I had assumed that so long as I wrote if (name.toLowerCase() != "megan"); it wouldn't break out of it unless this is true, but it allowed the user to press cancel unless I explictitly typed if (name.toLowerCase() != "megan" || name == null) and if I typed the order reversed, as if (name.toLowerCase() != "megan" || name == null), it would still let the user press cancel!!! Can someone tell me why this is! I remember you saying that for ||, so long as the first part of the test is true, the rest of it needn't be tested. So does Javascript just automatically have something built in where so long as you press cancel, it automatically lets them cancel, even if your loop doesn't explicitly say so? Also, the prevention of cancel only works for the first prompt, they can still press cancel on the whee prompt. How can I fix that? I tried if (whee.toLowerCase() == "megan" && whee != null) and if (whee != null && whee.toLowerCase() == "megan"), but neither of them worked. So now I'm wondering what would be the best way to do this. Thanks for the help!Megan

Link to comment
Share on other sites

Hmm, rather than:

if(name == null)

You might try

if(!name)

This code works as you describe:

var name = prompt("What is your name?");while(!name || name.toLowerCase() != "megan"){	name = prompt("Come on, say 'Megan'.");}alert("Hello, " + name);

The !name is sort of like an "is set" test. If a variable is set, it will return true. If it is not set, it will return false. So ! (which is the "not" operator) in front of the variable name will be true if it is not set and false if it is.

Link to comment
Share on other sites

The !name is sort of like an "is set" test. If a variable is set, it will return true. If it is not set, it will return false. So ! (which is the "not" operator) in front of the variable name will be true if it is not set and false if it is.
Oh! I had thought that it was exactly the same as != true! So there is a difference, then? Well, obviously so, because I took your code and replaced the !name with name != true and just got myself stuck into a loop. :grumbles: So now I can't close the gosh darn box because it won't quit the loop even if I type in "Megan"!!!
Link to comment
Share on other sites

I don't know the exact terminology for the ! operator (unary?) but it basically does what you said:

var isSomething = false;if(!isSomething){	alert("This will alert!");}

However, javascript treats pretty much any value as true other than null (and false).

if(1004 && -1 && true && !null){	alert("Hi!");}if(){	alert("This won't alert.");}

Because of this quirky behavior, you can use this to see if a variable has been set or not.

var test;if(test){	alert("Not going to alert.");}test = 42;if(test){	alert("This will alert.");}

Link to comment
Share on other sites

Hm.... so why do !name and name == false not seem to work the same way, then?Like I said, if I type

var name = prompt("What is your name?","");while(name == false || name.toLowerCase() != "megan"){	name = prompt("Come on, say 'Megan'.","");}alert("Hello, " + name);

it will not work, allowing the user to cancel.However, if I type

var name = prompt("What is your name?","");while(name != true || name.toLowerCase() != "megan"){	name = prompt("Come on, say 'Megan'.","");}alert("Hello, " + name);

it will, as I mentioned, put me into a loop which I can't break! It only works if I put name != null or !name. So does !name equal either name != null OR name != true, while tying out true or false explicitly doesn't work since this variable doesn't have a true or false attribute?

Link to comment
Share on other sites

It is because name will never explicitly equal true or false unless you explicitly set it to true or false.

var name = false;if(name == false && name != true){	// this code will execute.}

Just because if(name) and if(!name) pass the true/false check for an if statement, doesn't mean that name's value is true or false.

var name = "Megan";if(name != true){	// this code will execute because name != true	// it equals "Megan".}if(!name){	// this code will not execute because we've	// set the value of name to "Megan".}

I hope that helps.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...