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!

(1 votes)
Loading...

Similar Posts

Subscribe
Notify of
8 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
butterkipfel
1 year ago

The code does not work because in the condition

if (foodCollected = true)

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

if (foodCollected)

for the condition to ensure that the score is increased only when actual food has been collected.

butterkipfel
1 year ago
Reply to  MCStar975

there are still a few smaller mistakes hidden.

In the row

 MCStarschlange

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

placeFood()

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:

let food;

In function

increaseScore()

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

draw()

with

requestAnimationFrame(draw);

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

setInterval(draw, 200);

use to call the function at regular intervals.

The function

add()

uses the

ctx.fillRect()

-I command, but she tries to

add()

– Function within

draw()

– Call function. This will

add()

-function in a loop repeatedly called and leads to undesirable behavior. Instead, you should

ctx.fillRect()

-command directly in the

draw()

– Use function.

jort93
1 year ago

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.

jo135
1 year ago
Reply to  jort93

Javascript allowed, unfortunately, assignments in if conditions.

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.

jo135
1 year ago

= is an assignment.

== is a comparison.

Think about what you need.