I have a variable declared here:
var quizScore = 0;
And I want to add a number to it each time the correctAnswer() function runs:
function correctAnswer(){
quizScore+1;
console.log ( 'correct answer selected: quizscore = ' + quizScore );
}
I added a console log for debugging. It works, so the function is being called, but it is not adding the score. Do I need to parse this to an integer? I can't work out what the +1 needs to be to work correctly.
You can go here and you will see that clicking "Lightning Bolt" for question 1 shows "correct answer" in the console, but doesn't add to the score variable.
Do it like this:
function correctAnswer(){
console.log ( 'correct answer selected: quizscore = ' + (++quizScore) );
}
You just need to assign the +1 to quizScore variable. This may be the fastest way to add 1 and display it in one line
You're adding one to whatever value is in quizScore, and doing nothing with the result.
You need quizScore = quizScore + 1.
Keep quizscore as global variable.
And secondly change the line no.1 of your correctAnswer() function to
quizScore = quizScore + 1;
You can use self-memorizing function not to pollute global environment with variables like so:
function correctAnswer() {
correctAnswer.quizScore = (correctAnswer.quizScore || 0) + 1;
console.log("QuizScore : " + correctAnswer.quizScore);
}
for (var i = 0; i < 10; i++) {
correctAnswer(); // output 1 2 3 4 5 6 7 8 9 10
}
Right now, when you do this:
quizscore+1;
You add one to it but it doesn't assign the change to the variable. One reason for this is that sometimes you may want to add a number to the variable long enough to perform an operation but you don't want it to change.
// quiz score is left alone
var nextscore = quizscore + 1
Here are the different ways to actually assign it:
// temporarily adds 1 to quizscore, then saves it to quizscore
quizscore = quizscore + 1
// adds one to quizscore after it's used in an expression
quizscore++
// adds one to quizscore before it's used in an expression
++quizscore
So if you did something like this:
var nextscore = ++quizscore + 1;
You would both increment the current score and predict the next score.
Read more: Expressions and Operators
Related
Understanding While Loop
I am trying to understand what exactly happens when I use the 'while loop' to execute a code multiple times.
I was solving a problem on JSHero.net and I found it confusing so I tried explaining the solution to myself in order to get a clear understanding.
Please study the question, the answer and the simple explanation and let me know if I have understood it correctly. I could have done better explaining the counter as using it inside the condition itself confused me a lot.
Thanking all the good people in advance for helping me !!
Stay Safe !!
Question
Write a function spaces that takes a natural number n and returns a string of n spaces.
Example: spaces(1) should return ' '.
Answer
function spaces(num) {
let mySpaces = '';
while (num-- > 0)
mySpaces += ' ';
return mySpaces;
};
Explanation
declare a function spaces
it has 1 parameter 'num'
declare a variable mySpaces
initialize it with an empty string
we use a while loop as we need to repeat an action multiple times
in this case we need to add blank spaces to a string
our '''empty spaces string''' will be stored in the variable mySpaces
blank spaces will be equal to the 'num' parameter, which is fed when the function 'spaces' is called
while loops have: a condition and a code (loop body)
our condition is to ensure that the code should execute as long as the num is greater than 0
our condition is (num-- > 0)
our code is: mySpaces += ''
so if our function is called with the following parameter then how would this while loop work
spaces (3)
first it will check if 3 > 0; which it is and it will execute the code
mySpaces = mySpaces + ' '; the result in variable mySpace will now be ' ' (1 space)
then since we have used the num as a counter (num--), the loop will reduce 1 from 3 = 2
it will check if 2 > 0; which it is and it will execute the code
mySpaces = mySpaces + ' '; the result in variable mySpace will now be ' ' (2 spaces)
then since we have used the num as a counter (num--), the loop will reduce 1 from 2 = 1
it will check if 1 > 0; which it is and it will execute the code
mySpaces = mySpaces + ' '; the result in variable mySpace will now be ' ' (3 spaces)
then since we have used the num as a counter (num--), the loop will reduce 1 from 1 = 0
it will check if 0 > 0; which it is not and it will only execute the code after the while loop
we return the mySpaces variable which will give us the final result
While construction in javascript and most popular programming language consists of these parts:
while keyword
condition inside parentheses (num-- > 0)
body (mySpaces += ' ';)
It it used to repeatedly execute statements inside the body as long as condition is true.
For example this is how would you print Hello world repeatedly 5 times (please note, for this example for loop would have been more appropriate):
i = 5;
while (i > 0) { // as long as i is above zero
console.log("Hello world"); // print 'Hello world'
i--; // decrease value of i by one
}
In this particular example execution of while loop could be described as this:
check if condition is true
if not - skip body and continue with next statement after body
if yes - execute every statement inside body once and repeat this step
It is possible based on the condition that body gets executed zero, one, or multiple times.
In your code you start with some value of num, when you enter while loop, condition is checked, it is determined, whether body should or should not be executed and then num is decreased by one (because of the -- operator). This process repeats as long as num is above zero.
Slight modification in the order:
...
<> spaces (3)
<> a variable mySpaces will be declared and initialized with an empty string literal.
<> first it will check if 3 > 0; which it is and it start the loop. The value of num has already decreased by 1 in the memory, so now num = 2.
<> mySpaces = mySpaces + ' '; the result in variable mySpace will now be ' ' (1 space)
<> it will check if 2 > 0; which it is and it will execute the code. The value of num has again decreased by 1 in the memory, so now num = 1.
<> mySpaces = mySpaces + ' '; the result in variable mySpace will now be ' ' (2 spaces)
<> it will check if 1 > 0; which it is and it will execute the code. The value of num has again decreased by 1 in the memory, so now num = 0.
<> mySpaces = mySpaces + ' '; the result in variable mySpace will now be ' ' (3 spaces)
<> it will check if 0 > 0; which is false and it will not execute the code inside the while loop anymore. The value of num has again decreased by 1 in the memory, so now num = -1.
<> The last value of mySpaces which is ' ' (3 spaces) is returned from the function.
P.S. I've tried to write the answer in a way closest to how you've explained it. Hope this clears everything! Next time if you find the flow of code confusing always remember to put print statements at different places. Putting a console.log("Checkpoint 1") or printing the value of the variables in action greatly helps one to understand the changes as they happen. A more advanced way is to put breakpoints in code and debug. OnlineGDB's IDE makes a table of values for the variables and displays them at each stop.
I am currently learning a bit.
In one script I get a number which lenghts usually is 4. In rare cases it can be a 8 digit number.
If it's 8 digits long I need to save it in a different variable.
So I get my variable, lets call it mynumber.
Now I printed mynumber.length which is mostly 4. If it is greater than 4 I want to store my original variable in mynumber2 and delete it from mynumber.
What's a good way to achive that?
Try this;
myNumber = 1234; // Or whatever is the value
if(myNumber.length > 4) // If length greater than 4
myNumber2 = myNumber;
myNumber = undefined; // If you want to delete it from original number variable
delete myNumber; // If you want to delete the original number variable
var x = 12345;
var mynumber = 0;
var mynumber2 = 0;
(x.toString().length > 4 ? mynumber2 = x : mynumber = x);
console.log(mynumber + ' - '+ mynumber2);
I just have a question about some while loop logic.
So, when you write a loop that displays a string of numbers to a document and say that while the loop is <= (less than or equal to) say, 5, and you tell the loop to add 1 each time this is true, wouldn't that mean that: while the loop is equal to 5 that it would add one to 5 too? It doesn't, but I messed up on some code when I was practicing and noticed that when it is equal to five it does not add one, but I thought it would...
console.log('2nd Loop:');
text = '';
// loop:
i = 1;
while (i <= 5) {
text += i + ' ';
i += 1
}
console.log(text); // Should print `1 2 3 4 5 `.
the reason your text doesn't display a 6 isn't because i isn't incremented. It's because the text gets added onto before it's incremented.
In other words when executing on that 5th loop, the text would add on 5, and then it would increment i, and then it would check the loop again, which would no longer be valid and therefore 6 is never printed.
In memory, it adds one. It doesn't add it to the text though.
Since you're incrementing the value after assigning it and then the loop condition fails, it doesn't get to the part where you concatenate the string.
It does. Just output i and you'll see it's 6. text never gets the 6 because of when you increment i.
console.log('2nd Loop:');
text = '';
// loop:
i = 1;
while (i <= 5) {
text += i + ' ';
i += 1
}
console.log(text,i); // Should print `1 2 3 4 5 `.
b/c you +1 after you add i to text, all you need to do is switch the two line order.
EDIT
if you want it start with one just change your i to 0 to start with.
i = 1
console.log('2nd Loop:');
text = '';
i = 0;
while (i <= 5) {
i += 1
text += i + ' ';
}
console.log(text);
I was going to post this as a question to a problem but i later found a 'solution' (if that is what it is) and now this is more like an attempt to understand the situation.
I have a javascript code that displays the number 0 on the screen and then when a button is clicked, the number is supposed to increase according to the amount of times the button is clicked.
This was the code i used initially:
var number = 0;
$ (document).ready (function() {
document.getElementById("display").innerHTML = "Number of clicks: " + number;
$("#submit").bind ('click', function(event) {
document.getElementById("display").innerHTML = "Number of clicks: " + number++;
});
});
Problem was the button click event only worked AFTER the second click.Meaning i had to click the button twice before the incrementation worked.
So i created a function:
function increment () {
number++;
return number;
}
and then changed the last line of the initial code to:
document.getElementById("display").innerHTML = "Number of clicks: " + increment();
Now the number increases the first time i click on the button.
I just need to know why the first method didn't work.
Use ++number instead of number++
number++ increases the value of number afterwards.
You code is running fine, even in the first time. But the value displayed is1 less than the number of the clicks.
You are using prefix increment operator (++counter). In prefix increment operation first the value is evaluated or returned and then incremented.
But in postfix increment operation (counter++) first the value will be incremented and then returned
Use the existing code and initialize the number as 1 and execute the code.
You will get the expected result.
Should you want to maintain the initialization as 0, use postfix increment operator to get the desired result.
My recommendation would be not to use either of them but the below one
number += 1;
This is pretty common in a lot of languages.
var i = 0;
1 + i++
returns 1
var i = 0;
1 + ++i
returns 2
The difference is whether the variable is incremented before or after being evaluated in the expression.
Use this
$('#target').click(function() {
$('#output').html(function(i, val) { return val*1+1 });
});
HTML is
<button id="target" type="button">Click Me</button>
<div id="output">10</div>
SEE DEMO HERE
The answer is simple, why your first code did not work for you, as expected.
var number = 0;
$ (document).ready (function() {
document.getElementById("display").innerHTML = "Number of clicks: " + number;
$("#submit").bind ('click', function(event) {
document.getElementById("display").innerHTML = "Number of clicks: " + number++;
});
});
>>> This first time when DOM element load, The Value get printed as :
output : Number of clicks: 0 // because you have initialize number as 0.
Now when you click "Click Button", you have POST-INCREMENTED the Value, means
the value get's incremented after the action is completed. So in this case,
when you click first time, the number is still 0 and get printed again as
"Number of clicks": 0 and then the value get's incremented by Post-increment
and become's 1. When you click for second time,
the output :"Number of click": 1 get's printed.
Why this code outputs 3, not 2?
var i = 1;
i = ++i + --i;
console.log(i);
I expected:
++i // i == 2
--i // i == 1
i = 1 + 1 // i == 2
Where I made mistake?
The changes occur in this order:
Increment i (to 2)
Take i for the left hand side of the addition (2)
Decrement i (to 1)
Take i for the right hand side of the addition (1)
Perform the addition and assign to i (3)
… and seeing you attempt to do this gives me some insight in to why JSLint doesn't like ++ and --.
Look at it this way
x = (something)
x = (++i) + (something)
x = (2) + (something)
x = (2) + (--i)
x = (2) + (1)
The terms are evaluated from left to right, once the first ++i is evaluated it won't be re-evaluated when you change its value with --i.
Your second line is adding 2 + 1.
In order, the interpreter would execute:
++i // i == 2
+
--i // i == 1
i = 2 + 1
++i equals 2, `--i' equals 1. 2 + 1 = 3.
You're a little off on your order of operations. Here's how it goes:
i is incremented by 1 (++i) resulting in a value of 2. This is
stored in i.
That value of two is then added to the value of (--i)
which is 1. 2 + 1 = 3
Because when you use ++i the value of i is incremented and then returned. However, if you use i++, the value of i is returned and then incremented. Reference
++$a Increments $a by one, then returns $a.
$a++ Returns $a, then increments $a by one.
--$a Decrements $a by one, then returns $a.
$a-- Returns $a, then decrements $a by one.
Because you're expecting this code to work as if this is a reference object and the values aren't collected until the unary operations are complete. But in most languages an expression is evaluated first, so i returns the value of i, not i itself.
If you had ++(--i) then you'd be right.
In short, don't do this.
The result of that operation isn't defined the same in every language/compiler/interpreter. So while it results in 3 in JavaScript, it may result in 2 elsewhere.