I'm currently learning JavaScript on Code Academy and I am at the end of the while loops section.
The following code:
j = 0;
while (j < 3) {
j++;
}
produces a 2 on the console and I have no clue why. I tried running this on Eclipse JaveEE only to realize that using a HTML file with this code as a script gives me a different result: a blank page.
That makes sense to me, because I've only incremented j to 3, but not printed it. Not sure why the CodeAcademy console gives me a 2.
This is a screenshot of the console output:
The behaviour you're observing is because that's how a browser console works.
For every code you evaluate it tries to return some value. For trivial expressions it's easy - 2 + 2 would presumably return 4.
For code that consists of multiple statements it's much more complicated and console tries to be smart. What adds more complexity into this is the fact that console's behaviour is not standardised, so what we observe at this very moment for a given browser is not guaranteed to hold true for another browser or for another release of the same one.
Let's try to find out what is happening though:
j = 0;
while (j < 3) {
j++;
}
for this code browser tries to be smart and outputs the value of the latest found expression, which is in this case is j++;. It returns 2 because that was the value of j on the last iteration before loop termination. And since the postfix increment returns the current value before modifying it - it returns 2.
If we change it to
j = 0;
while (j < 3) {
++j;
}
the output would be 3, for the very same reason.
Now let's try something different:
j = 0;
while (j < 3) {
j++;
a = 42;
}
this would output 42. Since the a = 42 is the latest expression in this code.
j = 0;
while (j < 3) {
j++;
var a = 42;
}
For this sample it would again return 2, since console decides to ignore the assignment statement and reverts back to the latest expression.
To summarise: this behaviour is not standardised, and browsers just try to be useful and to output something, even if it's not what you expect to be. So my advice would be to not rely on the implicit console output and use the console.log() explicitly in case when you want to get a result.
Related
I'm a very beginner learning Javascript, alongside other code languages, and while looking at information here and in other sites, I've pieced together a simple code loop:
function returnMe() {
for (let i = 1; i <= 10; i++) {
if (i == 10) return i;
console.log(i)
}
}
console.log(returnMe());
I understand what everything does except the function I've created. The function is to stop the loop from continuing endlessly, but I'm not sure how exactly I've enabled that, nor why it should be logged (though I figured out that both pieces must be there for it to work or else it will either not work or come back as undefined.)
I was hoping someone here could help quickly define the simple issue for me, since search engines and other sites believe I'm asking what the return function is instead (which makes sense why), and I just need to understand how that bit works.
the output of the function is
1
2
3
4
5
6
7
8
9
10
it will console log every number from 1 to 9 in the for loop and then it will return 10 which will be printed outside
The For Loop Consists Of for (let i = 1; i <= 10; i++) the parameters: Initiatlisation, Condition, Incrementation. So When You Use i<=10 you are allowing the function to run until the value is less than 10.
Going further It will console log all the numbers from 1 to 10 because of the console.log(i) afterwards. Then at i=10 it will return the value which will be then displayed by console.log(returnMe());
I am learning JavaScript on Codecademy. I am finding so many outputs like below when I use while loop.
for (var i=0; i<5; i++){
console.log("Dhanu identify problems and solve them");
}
var loop = 0;
while(loop<5){
console.log("Do some more");
loop++;
}
I am getting an unwanted output in the last line as 4.
The output you get is simply console.log which logs the last known value of the 'loop' variable: (here in firefox):
It's absolutely not related to your code and you don't have to worry about that.
As stated in another answer, debug console use to log the result of the last line (probably because they are meant to debug).
For example the statement "i = 1" evaluates to "1":
while the statement "var i = 1;" evaluates to "undefined", hence logging "undefined"
you can observe the same behavior by invoking eval on those statements:
You're seeing that because the last statement in your while loop is loop++, which "returns" the current value of loop. This is just a side effect of running code in a console like this. Consoles are basically read-execute-print-loops (REPL), and so they need something to print. If you ran this as a script in a webpage you would not see 4
when you write any statement in developer console then last returned value will be printed...
for example
var a;
it prints undefined on console.
a = 10;
it prints 10 on console.
a = 10; a = a + 5;
it prints 15 on console.
simply when we assign any values or increment or decrement numbers then it returns value after performing that operation...
so, in the above or below code
var loop = 0;
while(loop<5){
console.log("Do some more");
loop++;
}
finally loop++ is 4.
I am currently building a small web application with similar functionality across all modules. I want to code small generic functions so that all programmers next to me, call these functions and these functions return necessary but important data for them to implement their functionality. In this example, I am trying to deal with the typical "choose true or false" exercise. So from the template.php they call this function:
function checkAnswers(){
var radiobuttons = document.form1.exer1;
var correctAnswers = answers(); //this is an array of string
var checkedAnswers = checkExerciseRB(radiobuttons, 2, correctAnswers);
for(i=0; i<checkedAnswers.length; i++){
alert(checkedAnswers[i]);
}
}
Function checkExerciseRB is my generic function, it is called from checkAnswers.
function checkExerciseRB(rbuttons, opciones, correct){
var answers = new Array();
var control = 0;
for(i=0; i<rbuttons.length; i++){
var noPick="true";
for(j=0; j<opciones; j++){
if(rbuttons[control+j].checked){
if(rbuttons[control+j].value==correct[i]){
answers[i]= 1;
noPick="false";
break;
}
else{
answers[i]=2;
noPick="false";
break;
}
}
}
if(noPick=="true")
answers[i]=0;
control=control+opciones;
}
return answers;
}
It works great but while looking at my favorite browsers (FireFox, Chrome) error log it says:
TypeError: rbuttons[control + j] is undefined
Any clue on how to deal with this matter?
This probably means that control + j is greater than or equal to the length of the array rbuttons. There's no such array element as rbuttons[control + j].
You should learn how to use the JavaScript debugger in your favorite browsers! Debuggers are great. They let you watch this code run, line by line, as fast or as slow as you want, and watch how the value of control changes as you go.
You’ll watch it, and you’ll think “Oh! That line of code is wrong!”
You're looping through rbuttons.length times, but in each loop you're adding 2 to control. Using control to index your array, you're going to run past the end.
Does the index specified by control + j exist in the array? i.e: If that evaluates to 4, is there at least 5 items in the array?
Also, you should be using var i, var j, etc inside your for loop. Without it your variables are leaking into the scope this code is executed in (most likely the global scope, and that's not good) :)
My background is in java and right now Im getting into learning Javascript. (I'm porting this java code that I made into javascript but it behaves a bit different than I expected?? If I use "console.log()" instead of "document.write" I'm NOT getting the same result..why?
thanks 4 yr time! Some insight will be very appreciated!
var counter = 1;
function println(str) {
console.log(str);//
}
for (var i = 1; i <= 5; i++) {
for (var j = i; j < 5; j++) {
document.write("#");
// println("#");
}
for (var k = 1; k <= counter; k++) {
document.write("*");
// println("*");
}
document.write("<br/>");
//println(" "); <--- "\n" ?
counter+= 2; //
} // ends application
document.write() is for printing content to the page of your document, while console.log() is used predominantly for diagnostic/debug information to be emitted in the console of your web browser. Specifically, document.write() is intended to be consumed by the viewer of your page, while console.log() is generally not.
Console.log logs stuff into browser console. Install Firebug (getfirebug.com) and you will see your logs.
Also there is nice description about how it works http://getfirebug.com/logging.
Also, using document.write is not really elegant, you can use it only on page load, and it's blocking whole page. You basically should not use it at all. If you try to use document.write after page is loaded, it will replace whole content of your document with your last "log".
In this question,I'm asking how the following snippets work, as it involves weird use of variable:
while (+(+i--)!=0)
{
i-=i++;
}
console.log(i);
Interesting problem... you've tagged it Java, JavaScript and C -- note that while these languages have the same syntax, this question involves very subtle semantics that may (I'm not sure) differ across languages.
Let's break it down:
+(+i--)
The -- postfix decrement operator is most tightly bound. So this is equivalent to +(+(i--)). That is therefore equivalent to the value of +(+i) (that is, i), but it also decrements i after taking the value. It compares the value with 0 to see if the loop should continue. Thus, while (+(+i--)!=0) is equivalent to the following:
while (i-- != 0)
Note that it also performs i-- at the end of the loop.
Inside the loop, I believe you have some undefined behaviour, at least in C, because you are referencing i on the right, and also updating i on the left -- I believe that C doesn't define which order to do that in. So your results will probably vary from compiler to compiler. Java, at least, is consistent, so I'll give the Java answer. i-=i++ is equivalent i = i - i++, which is equivalent to to reading all the values out of the expression, computing the result of the expression, applying the post-increment, and then assigning the result back. That is:
int t = i - i; // Calculate the result of the expression "i - i++"
i++; // Post-increment i
i = t; // Store the result back
Clearly, this is the same as writing i = 0. So the body of the loop sets i to 0.
Thus, the loop executes just one time, setting i to 0. Then, it decrements i one more time on the next while loop, but fails the check because i (before decrementing) == 0.
Hence, the final answer is -1, no matter what the initial value for i is.
To put this all together and write an equivalent program:
while (i-- != 0)
{
int t = i - i;
i++;
i = t;
}
console.log(i);
When I tried it in Java and JavaScript, that's what I got. For GCC (C compiler), it gives -1 only when i starts out as 0. If i starts out as anything else, it goes into an infinite loop.
That's because in GCC (not necessarily all C compilers), i-=i++ has a different meaning: it does the store back to i first, then does the post-increment. Therefore, it is equivalent to this:
int t = i - i; // Calculate the result of the expression "i - i++"
i = t; // Store the result back
i++; // Post-increment i
That's equivalent to writing i = 1. Therefore, on the first iteration, it sets i to 1, and then on the loop, it checks whether i == 0, and it isn't, so it goes around again, always setting i to 1. This will never terminate, but for the special case where i starts out as 0; then it will always terminate the loop and decrement i (so you get -1).
Another C compiler may choose to act like Java instead. This shows that you should never write code which both assigns and postincrements the same variable: you never know what will happen!
Edit: I tried to be too clever using that for loop; that wasn't equivalent. Turned back into a while loop.
That's soooo wierd! (I love it)
first, you can forget about the +(+...) part, it's just like saying 1 + (+1) = 2.
i-- means i = i - 1. In your while condition, you test if i-- is different from 0. Note: the test is made on i != 0 and then i's value is changed. If you wanted to change its value before the test, you should have used --i instead.
As for the i -= i++, it's a very dumb way to say i = 0. You must read it from right to left: i = i + 1 and then i = i - i1 (whatever value of i you have, you'll end up with 0.
Simplier quivalent snippet:
while (i-- != 0) {
i = 0;
}
console.log(i);
1 a -= b means a = a - b.
i -= i++ would mean a similar thing to i = i-i; i++ (if you make the -= explicit).
In a similar fashion, you can pull the side effect of i-- out of the loop condition by
transforming while (foo(i--)) { ... } to while (foo(i)) { i--; ...} i--; (you need to put it both in the loop body and after the loop because, at the end, the condition will be false and the loop body will not be executed but execution continues after the while loop).
The while condition evaluation happens based on operator precedence. I have used explicit braces to help understand the evaluation:
(+(+(i--)) != 0) which is equivalent to using (i-- != 0) as the '+' are just unary operators.
The expression i -=i++; is equivalent to i = i - i++; where the LHS expression gets evaluated from left to right.
i = 4;
while (+(+i--)!=0) //here i would be decremented once to 3.
{
i-=i++; // here i = 3 - 3 = 0; even though i has been incremented by 1 its value is set to 0 with this assignment
}
This is very simple. And I think the only reason to code like this is a concept called "code obfucasion" or "code confusing". This way makes the code harder to read and debug, so that can prevent from reverse engineer your code :-)