Francesca
Francesca

Reputation: 28108

Adding an integer to a JavaScript variable

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.

Upvotes: 0

Views: 660

Answers (5)

Dissident Rage
Dissident Rage

Reputation: 2716

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

Upvotes: 0

nanobash
nanobash

Reputation: 5500

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
}

Upvotes: 1

Bhavesh Munot
Bhavesh Munot

Reputation: 675

Keep quizscore as global variable. And secondly change the line no.1 of your correctAnswer() function to

quizScore = quizScore + 1;

Upvotes: 1

George Sofianos
George Sofianos

Reputation: 1191

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

Upvotes: 3

user229044
user229044

Reputation: 239220

You're adding one to whatever value is in quizScore, and doing nothing with the result.

You need quizScore = quizScore + 1.

Upvotes: 1

Related Questions