Why doesn't this JavaScript code work?
function updateScore() { scoreElement.textContent = score; } function increaseScore() { if (foodCollected = true) { score++; updateScore(); foodCollected = false; } }
The score increases every half second and not just when she has eaten something!
The code does not work because in the condition
an assignment is used instead of a equality operator. As a result, the condition is always evaluated as true, regardless of whether food has been collected or not. Use the equality operator instead
or even better, just use
for the condition to ensure that the score is increased only when actual food has been collected.
there are still a few smaller mistakes hidden.
In the row
there is apparently an additional text “MCStarschlange” outside the meta tag. You should remove it so that only the meta tag line remains.
In function
the “food” variable is not declared before it is assigned. You need to define the “food” variable outside the function so that it can be used throughout the code. You could add it at the beginning of the script:
In function
is a semicolon according to the “if” condition, which leads to the block located therein being executed independently of the condition. You should remove the semicolon so that the condition works correctly.
The function
with
at the end, however, this function is in turn called by itself without an exit condition. As a result, the browser will get into an endless loop. You could instead
use to call the function at regular intervals.
The function
uses the
-I command, but she tries to
– Function within
– Call function. This will
-function in a loop repeatedly called and leads to undesirable behavior. Instead, you should
-command directly in the
– Use function.
I use VSCode and execute it in Chrome
Javascript allowed, unfortunately, assignments in if conditions.
That is, “foodCollected = true” puts foodCollected to true(and has the value of true as most of Javascript).
Many other programming languages would give you at least one warning if not even a mistake.
Strictly speaking, this is not the problem. In JavaScript, assignments are expressions and therefore have a value. Like in C, but not in various other languages.
A reasonable JS editor should warn here.
= is an assignment.
== is a comparison.
Think about what you need.