Why is this logging my variable?


#1


https://www.codecademy.com/courses/javascript-beginner-en-qDwp0/0/3?curriculum_id=506324b3a7dffd00020bf661#


There is no error I'm just curious why it's printing out my variable when I'm not telling it too...mostly this is for me to understand better.


// Write your loop below!
var count = 0;
var end = true;

while (end) {
    count ++;
    if (count <= 5) {
        console.log(count);
    } else {
        console.log("loop is complete, total is 5.");
        end = false;
    }
    
}

Replace this line with your code.

Now if I rewrite it like this, it works fine:

// Write your loop below!
var count = 0;
var end = true;

while (end) {
    count ++;
    if (count <= 5) {
        console.log(count);
    } else {
        end = false;
        console.log("loop is complete, total is 5.");
    }
    
}

Why is having my variable end after my console log gonna log it? When I run the first it says false on the last line of my output. However if I have it first it does not...I don't understand that part.

Also side note my count would not work when I put

count + 1;

it only worked with the ++


#2

When the last executed statement is an assignment, the value resulting will be echoed by the console as a final response. When the last command given is console.log(), it is the last response.

count ++ (or more commonly, count++) is a compound operation that modifies a variable, much like a statement.

count + 1 is an expression that does not actually do anything. We would write it as,

count = count + 1

to perform the equivalent action to the above.


#3

Awesome, thank you for explaining that.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.