Why won't my While Loop work? - javascript

I am doing the video tutorials from The New Boston and I'm on video 20. Everything has been fine until now but I can't get this one to run. I've checked against the code in the tut and I just can't see what I'm missing. I'm sure it's right in front of my face.
Sorry this is so basic, but I'm a total newbie.
This is the video tutorial: http://www.youtube.com/watch?v=QPFW_0blw9w
This is my code:
var x = 1;
while(x<10){
document.write(x + "how do you like </br>");
x++;
}
Thanks for any help!

Your syntax is correct, as verified by running the JavaScript code (exactly as you wrote it) inside Codecademy Labs. If your while loop isn't working, I suspect it has to do with your environment or the state of the document being written, but it is not the code itself. As a fellow newbie, I try running code in two IDE's (codecademy labs being one) to test a lot of code and confirm against this sort of issue, though codecademy can't do file operations.
In addition, if you're interested in knowing why a for loop is superior to while for this situation, continue reading.
A for loop is a loop that comes in handy when you have a fixed index; When you know how many iterations you need, or know how to find out and can work that into the code.
A while loop is better at handling situations when an unknown (and unpredictable) number of iterations is required, as it will loop through until the conditions are eventually met.
Keep in mind that what makes it strong also makes it weak; for loops are harder to create infinite loops for. Because of the arguments in a for loop (IE: for (index,index<=value,value++)), most for loops self-terminate neatly, or at least it's hard to forget to put the "closing" condition in. while loops, however, don't innately ask for a closing statement and thus you must explicitly state them inside the loop.
I hope this answers your question, and more.
EDIT: Oh yeah, and </br> doesn't work inside the quotes. You can remove it, and it should still do a new line without it; But leaving </br> inside the code just has it literally print </br> in the line.

I don't see anything wrong with your code the way you wrote it, so there must be an error in some of the code that surrounds this. Alternatively, for the same outcome as this, I would suggest using a for loop as such:
for (var x = 1; x < 10; x++){
document.write(x + "how do you like </br>");
}

Related

What is the main difference between these two loops as a solution to this exercise? (learning javascript)

I am learning JS and came across this exercise:
Write a loop which prompts for a number greater than 100.
If the visitor enters another number – ask them to input again.
The loop must ask for a number until either the visitor enters a number greater than 100 or
cancels the input/enters an empty line.
Here we can assume that the visitor only inputs numbers.
There’s no need to implement a special handling for a non-numeric input in this task.
My solution works and was as follows:
let value;
while (true) {
value = prompt('Enter a number greater than 100', 0);
if (value > 100 || value === '');
console.log(value);
break;
}
The MDN solution was this, and though it is shorter and more simple, it seems to accomplish the same task.
let num;
do {
num = prompt("Enter a number greater than 100?", 0);
} while (num <= 100 && num);
Is my solution still valid? Is the MDN one more proper?
I just want to make sure I am understanding things correctly as I go.
If your solution worked before, I think you probably typed in your solution incorrectly here. I am going to assume you meant to write:
if (value > 100 || value === '') {
console.log(value);
break;
}
Since you're just starting out with JS, you will eventually learn that there will be multiple ways you can handle any given coding problem. It will not always be a good answer/wrong answer type of scenario. Sometimes there are multiple ways to accomplish the same thing.
In this example, the MSN solution is better in terms of readability and possibly safety.
The MSN solution creates a while loop with the exit condition identified in the while statement. This loop will exit when that condition is met.
In your solution, the loop will never exit on it's own, the while() statement will always evaluate to 'true'. This loop needs an explicit exit statement, which you provide with the if() condition.
Your method, although it works, is a little bit less safe in terms of code readability and overall maintenance profile. For example, a future developer could by mistake change the if() condition and inadvertently create a never ending loop.
Or, if the loop contained several dozen lines of code, a developer may miss the if condition, and may add some important code after the if condition (such code would not execute when the exit condition is met.)
Yes, this specific sample exercise is trivial, so the code complexity and readability may not matter. But in large enterprise applications with hundreds of lines of code, such code choices carry serious risks with costly implications.
That said, I'll reiterate - as you learn more about JS, you will often find that there are multiple ways of solving any given problem. Sometimes you do want to create an explicit exit condition through an if() statement, on rare occasions you will want to create a never ending loop.
As you explore more complex problems, you will find needs for such solutiosn. So keep learning, keep trying different solutions, and keep asking questions.

Javascript: Array not shifting, multiple setTimeout functions (JSON)

I'm really stuck on this javascript question!
So I'm making a web page that will be completely animated (so it can be used for display for example in a television). That animation will be configurable by the user (stored in a database).
Right now, I've already made the code to store the configuration and to get the configuration (I do an AJAX call and save the configuration in an array of json objects) and everything is as it should be.
The problem is in the animation in which I go through the array and use setTimeout function to create animations. To iterate through the array I rotate it
(I use array.push(array.shift()) according to the answer here).
The first time the intervalmaster function is used, everything goes according to plan, but when the function is called again I need to rotate the array once more (because of the last animation) and the array just doesn't rotate!
Bellow I've left a portion of the code that I'm using that reproduces the problem I'm getting. I've also added the array jsonanima with some possible values (In reality the array is probably much bigger and with higher values).
I really don't understand what is happening, I've also considered that this could be a problem of the multiple setTimeout functions because I've read somewhere (couldn't find the link, sorry!) that is not really advised to use multiple setTimeout.
If that's the case is there any other way to do this?
Thank you in advance!
EDIT: Thanks to the comment from mplungjan I've realized that if change the console.log(jsonanimate) to console.log(JSON.stringfy(jsonanima)) it outputs the correct values (the json array rotated). This got me even more confused! Why do I need to JSON.stringfy to get the array in the correct order?!
Anyway, can't test this with the full code now as I'm not in the office, tomorrow I'll give more feedback. Thank you mplungjan.
EDIT2: Finally solved my problem! So the thing was the call to the function recursivegroup (recursivegroup(0);), this call was made before I rotated the array, so when restarting the animation the array would still have the incorrect values and every sub-sequential value was wrong.
A special thanks to mplungjan and trincot for the comments that helped me debug this problem.
Bellow I leave the code corrected so anybody with the same problem can check it out.
jsonanima=[{"VD":5,"A":10,"diff":0.25},{"L":7,"IE":8,"diff":0.25}];
function intervalmaster(flag){
function recursivegroup(index)
{
if(index==0)
{
//animateeach(jsonanima,0);
}
setTimeout(function(){
//HERE IT WORKS
jsonanima.push(jsonanima.shift());
console.log(JSON.stringify(jsonanima));
//animateeach(jsonanima,0);
//removed the if statement, since it was irrelevant as mplungjan noted
recursivegroup(index+1);
},(jsonanima[0]['diff'])*60*1000);
}
//Changed this
//recursivegroup(0);
var mastertime=0;
for(var key in jsonanima)
{
mastertime+=(jsonanima[key]['diff']);
}
console.log(mastertime,flag);
console.log(JSON.stringify(jsonanima));
if(flag==true)
{
jsonanima.push(jsonanima.shift());
console.log(JSON.stringify(jsonanima));
}
//changed to here
recursivegroup(0);
masterinterval=setTimeout(function(){intervalmaster(true)},mastertime*60*1000);
}
intervalmaster(false);

When to use variables? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I've started to learn HTML/CSS/JS after several years of no coding at all, previously some simple C++/Python/Pascal stuff.
In one of the tutorials, there is a very simple game to do, comparing a user input with a generated random number and displaying a message if both match.
The question is what is a general practice in web-development:
<p>How many fingers am i holding up?</p>
<input id=userInput type=text>
<input id=guessButton type="button" value=Guess!>
<script type="text/javascript">
document.getElementById("guessButton").onclick=function(){
if (document.getElementById("userInput").value == Math.floor(Math.random()*5)+1)
alert ("You've won");
}
</script>
vs
<script type="text/javascript">
document.getElementById("guessButton").onclick=function(){
var numberGuessed=document.getElementById("userInput").value;
var randomNumber=(Math.random()*5);
randomNumber=Math.floor(randomNumber)+1;
if (numberGuessed==randomNumber)
alert ("You've won");
}
</script>
I get that this example is VERY simple, but when it comes to more complicated logic or nested functions is it better to strive for step-by-step clarity or to avoid the creation of unnecessary variables?
Which is faster?
The answer to this one is it doesn't really matter a whole lot. If it's extremely necessary, for the best speed (both downloading off of the internet and running), if you're only using the values once, you'll want no variables. If you're using the values more than once, you'll probably want to define them in a variable. When downloading, the less data, the better. If you're only using it once, defining it as a variable would technically require more data to be downloaded (i.e. an extra var, an extra semicolon maybe), but it's so insignificant it should not be taken into account most of the time. Your Javascript took less than 1/10th of a millisecond to execute, so this should not be a concern most of the time, either.
Which is preferred?
This is more of an opinion-based question, and therefore, not exactly allowed on Stack Overflow, but I think I can safely say that most developers would say what is important is readability. If this means defining the variables, then so be it. If code cannot be read easily, then it's going to be extremely difficult to expand and modify it, even for yourself, down the road. Readability is especially important when working in a team. Ultimately, though, you should do whatever you prefer.
For speed, as people have stated, the difference is negligible. As for best practice, the second is, in my opinion, demonstrably better.
If someone else is using your code, proper variable naming removes the question of "What are they trying to do?" from the list of problems another developer (or you in a few months) has to solve. Expressive variable names make it so that, If I'm trying to debug a function, I can focus my energy on what's "going wrong", not on what's "going on".
In your second code example, without even looking at how your variables are declared, I can instantly understand what you're trying to do, whether it's working as intended or not. I can then put a debugger before the conditional and check that all the values of the variables you've declared make sense based on what you've named them. For example, I can pretty quickly narrow down what might be wrong if one them is a string, null, NaN, or undefined.
The second example, however, forces me to evaluate what you're doing before I can analyze how you're doing it.
It's a similar philosophy to code comments, really, the smaller the ratio of time spent understanding vs debugging, the more maintainable the code will be.
This is one of those style questions for which you'll likely get a gazillion answers. I would prefer the in-line version unless I was going to use the values more than once. There is probably a tiny difference in performance, since you're having to add names to the local namespace and then (eventually) gc them, but I doubt that difference could be measured in any reasonable use-case.
Yes, you can break down a computation into intermediate variables, and this has the advantage not only of readability, but also of debuggability, since that lets you set breakpoints on each line where something is calculated, and examine the values of the variables.
However, you can also pre-calculate variables. In your case, the DOM element will never change, and so it can be pre-calculated outside the event handler:
const userInputElement = document.getElementById("userInput");
document.getElementById("guessButton").onclick=function() {
var numberGuessed = userInputElement.value;
var randomNumber=(Math.random()*5);
randomNumber=Math.floor(randomNumber)+1;
if (numberGuessed==randomNumber)
alert ("You've won");
};
userInputElement needs to not be executed until the DOM is loaded. So this JS should be either at the end of your body, or wrapped in an event handler such as DOMContentLoaded.
Breaking the calculation of the random number down into two steps is probably going overboard. Most programmers would write this in one line:
var randomNumber = Math.floor(Math.random() * 5) + 1;
In this case, another option is to write this as a little separate function. This has several advantages. First, you would be able to re-use that function in other places in your code. Second, you could test it more easily in isolation. Third, the code where you are using it is simplified.
function getRandomNumber(n) {
return Math.floor(Math.random() * n) + 1;
}
Now you can simplify your event handler to
document.getElementById("guessButton").onclick=function() {
var numberGuessed = userInputElement.value;
var randomNumber = getRandomNumber(5);
if (numberGuessed == randomNumber)
alert ("You've won");
};
However, now that you have both pre-calculated the DOM element, and moved the random number calculation into a function, there is less need to calculate variables one-by-one in your event handler, and you can simplify it to:
document.getElementById("guessButton").onclick = function() {
if (userInputElement.value == getRandomNumber(5))
alert ("You've won");
};
Now you have a very simple, readable event handler, which anyone can look at and easily see what is happening. You also have a separate, re-usable random number generator.
Although not directly related to your question, I would strongly recommend that you indent your code properly, and also adhere to style guidelines for things like the use of spaces.
It is also recommended to use addEventListener instead of assigning to the element's onlick attribute:
document.getElementById("guessButton").addEventListener('click', function() {
if (userInputElement.value == getRandomNumber(5))
alert ("You've won");
});

What does this syntax mean which likes `functionName: {}`?

I have found a piece of code in my company's project like the following:
while(condition){
code...
reloop: {
if(somethingIsTrue) {
break reloop;
}
}
code...
}
I don't understand what reloop does, can anyone give a simple explanation?
reloop: is a label. They are rarely used, and serve a very specific purpose: they let you break or continue outer loops from inner loops.
The article on MDN about labels explains this better.
Note that labels are very rarely used, and most of the time needing a label hints that your code is unclear, and should be restructured. I have never, not even once, used a label in javascript.
Avoid them unless they are truly the only clean solution to piece of code that proves difficult to write. Prefer, instead, splitting code into functions that you can return from.
reloop is a label for the block. The break command breaks out of the labelled block.
See eg https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break

Please explain this usage of a colon in javascript

I'm making a library, and I often inspect the result of Closure Compiler's output to see how it's doing things (I do have unit tests, but I still like to see the compiled code for hints of how it could compress better).
So, I found this very weird piece of code, which I never seen before.
variable : {
some();
code()
}
Note: this is not an object literal! Also, there is no ? anywhere that would make it a ?: conditional.
That code is in a regular function block (an IIFE).
variable, in this case, is an undefined variable. There's no code making it true, false, or whatever, and just to make sure, I put a console.log in there and indeed, I get a ReferenceError.
Please do note that I test my code in IE8 too, so this isn't just in modern browsers. It seems to be standard, plain old javascript.
So let's experiment with it. Firing up Chrome's console, I get this:
undeclaredVariable:{console.log('does this get logged?')} // yes it does.
trueValue:{console.log('what about this?')} // same thing.
falseValue:{console.log('and this?')} // same thing.
but then...
(true):{console.log('does this work too?')} // SyntaxError: Unexpected token :
...and...
so?{console.log('is this a conditional?')}:{alert(123)} // Unexpected token .
So what does it do?
thisThing:{console.log('is used to declare a variable?')}
thisThing // ReferenceError: thisThing is not defined
Please, I'd love it if someone could explain to me what this code is meant to do, or at least what it does.
It is a label
Provides a statement with an identifier that you can refer to using a
break or continue statement.
For example, you can use a label to identify a loop, and then use the
break or continue statements to indicate whether a program should
interrupt the loop or continue its execution.
Another common place you see it is when people stick the wonderful and useless javascript: on event handlers.
This is a label (the bit ending with a colon) followed by a block (the code surrounded by the curly brackets).
Blocks usually follow control statements, like if(...) { /*block*/ }, but they can also simply stand on their own, as in your example.
Labels allow jumping up several loops at a time with a continue or break; see the linked MDN page for several examples, such as:
var itemsPassed = 0;
var i, j;
top:
for (i = 0; i < items.length; i++){
for (j = 0; j < tests.length; j++)
if (!tests[j].pass(items[i]))
continue top;
itemsPassed++;
}
Here, top: is a label that code inside the inner loop can jump to, in order to escape to the outer loop.
For the sake of anyone who doesn't know what JSON is, and sees a colon in what might actually be an object, and is trying to figure out what it is, and finds this discussion, a colon is also used in JSON. There is a practice of embedding functions in a JSON object. Which might be confusing (As it was to me) for anyone who happens to see this for the first time. (Everyone isn't born with the knowledge of JSON and JavaScript programmed into their brains.) So if you find yourself at this discussion, and you think that every time you see a colon in JavaScript, that it's a label, it might not be. It might be that it's a colon after a label, OR it might be part of JSON. In fact, a colon in JSON being shown as a string, is a lot more common than a label. JSON in the form of an object, will be displayed as [object Object], with all the content hidden. So, unless the JSON is in the form of a string, and you display an object to the console (console.log(object)) all you will see is [object Object]. It is common practice to write JavaScript code, wrapped in an object. In that case you will see the JSON in the form of code. That's when you'll ask yourself, "What is this? and what is that colon for?" Then you'll find yourself at this discussion, and be told that it's a label, when it's really part of JSON. The topic of this discussion is worded: "Please explain this usage of a colon in javascript", and then the "correct answer" is marked as having to do with a label. The correct answer is that a colon can be used in more than one way. So, if you don't know what JSON is, or think you know (like I did, but didn't really understand) read about it here:
JSON.org
That is just a label.
you can use continue [label name] (or break) in a loop to go to a label.
More explanations of what they are can be seen throughout the interwebs.
it is used for labeling an statement in jsvascript.check more detail here.
the labeled statement can be used with break and continue later.

Categories

Resources