How come my total isn't zero after I get a 1 on the dice roll?

I've been working on a dice game where if either of the dice rolls a 1, the score is set to 1. However, I'm having trouble getting that part of my code to work properly. I'm confident that everything else is functioning correctly.

var die1 = Math.floor(Math.random()*6 + 1);
var die2 = Math.floor(Math.random()*6 + 1);
var score;

if (die1 === 1 || die2 === 1) {
    score = 1;
} 
if (die1 !== 1 && die2 !== 1) {
    score = die1 + die2;
}

console.log("You rolled a " + die1 + " and a " + die2 + " for a score of " + score);

Answer №1

Before anything else, it's important to note that you should not set score to 0. Instead of using score === 0, update it to score = 0.

Additionally, ensure that your second if statement isn't needlessly evaluated. Consider revising it as an else if block:

if (die1 === 1 || die2 === 1){
    score = 0;
   } 
else if ...

Answer №2

Combining all the excellent ideas provided:

if (die1 === 1 || die2 === 1) {
    score = 1;                // "If either dice rolls a 1, the score is 1"
                              // Remember to use = for assignment
} 
else {                        // Just use else instead of checking the inverse
    score = die1 + die2;
}

Answer №3

if (result1 === 1 || result2 === 1) {
    finalScore = 1;                // The score is assigned here, not compared
} 
else if ...               // It is recommended to use else if instead of multiple if statements

For further details :-

else if javascript

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to pass a variable within a jQuery event map?

Consider the below jQuery .on() event map: $('header').on({ mouseenter: function(e) {}, mouseleave: function(e) {}, }, 'li'); Is there a way to share a common var $this = $(this) variable between the mouseenter and mouseleave even ...

The Firefox extension is unable to activate any click events

Currently, I am developing a Firefox add-on with the goal of automatically filling in login form fields and submitting the login. For each website, I have access to various identifiers such as ids, classes or xpath, depending on what is provided by the web ...

Trigger a keyframe animation upon initial click and then reverse playback on the subsequent click

I'm struggling to create a wave animation that fills the screen up to a certain point and stops on the first click of a navigation menu. I've attempted to have it play in reverse when the navigation menu is clicked again, but it's not workin ...

Querying MongoDB to locate an element within an array is a common task

I need help with writing a mongoose query to select a specific object from the "cartItems" array in my mongodb database and update its "qty" and "price" fields. Here is the data: { _id: new ObjectId("634a67e2953469f7249c9a7f"), user: new ObjectId("634 ...

Issue encountered while loading JSON data into DynamoDB's local instance

I have successfully set up DynamoDB local and everything is functioning as expected after going through their documentation. I have also tested their example code, which worked flawlessly. The Users table has been created with the name "Users". Below is ...

Processing one file to submit two forms to the database in Express

I am facing an issue with two forms on one form.hbs page using the same process.js file. Each form is processed by a different submit button for separate occasions. The first submit button works correctly, processing the data in the process.js file and se ...

Getting a variable from an ajax call and using it in a Pug template

Currently, I am experimenting with Express and Pug to learn some new concepts. Upon making a request to a website, I received some dynamic information stored in an array. However, I am facing challenges when trying to iterate over this array using Pug. The ...

Element sticking on scroll down and sticking on scroll up movements

I am currently working on a sticky sidebar that catches and stays fixed at a certain scroll point using JavaScript. However, I am facing an issue where I need the sidebar to catch when scrolling back up and not go further than its initial starting point. ...

Ways to remove all attributes from a JSON data type

In my code, I am working with the following object: [ { "Name": "John Johnsson", "Adress": "Linkoping", "Id": 0, "Age": "43", "Role": "Software Engineer" }, { &qu ...

Understanding the reason why "undefined" is occurring in Javascript

Can anyone help me understand why the alert at the start is showing "undefined"? The alerts are displayed in this order: "success!" "Data" (the correct value) "undefined" I have gone through several threads and found that the issue usually arises du ...

Running the command "npm start" is resulting in an error message stating: "ENOENT: no such file or directory ... package.json"

After successfully creating a React app using NPX, I encountered an issue when trying to run npm start. The error message that appeared is as follows: $ npm start npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Users\Administrateur.TE ...

Consistent column heights within each row

I currently have Bootstrap implemented on my website and have integrated jQuery to adjust the height of each column to match the tallest one. However, the issue I am facing is that the height adjustment applies globally across the entire page, rather than ...

Delete the content on a webpage using an Ajax jQuery request to transfer it elsewhere

Whenever I submit a form using an ajax post request, I receive values from the controller and manipulate the page based on those values. However, my issue is that I need to erase the values from the previous request when the form is submitted again. For in ...

Heroku is showing an Error R10 (Boot timeout) message, indicating that the web process was unable to bind to the designated $PORT within one minute of launching

Encountering an error while trying to deploy my first node project on Heroku. Here is the error message: 2020-09-29T04:24:09.365962+00:00 app[web.1]: production 2020-09-29T04:24:09.415266+00:00 app[web.1]: server is listening at port 40890 2020-09-29T04:24 ...

"Trouble encountered when submitting data to an external system by writing the image source - issues with Firefox and

I've been diving deep into various online resources to find a solution for an issue I'm encountering. My familiarity with Javascript is limited, so please bear with me. Whenever I click on the next button during checkout, a script runs to submit ...

Utilize a recursive function to incorporate data into an array nested within other arrays

I am facing an issue where the data I'm trying to add to an element containing nested arrays is not getting updated in MongoDB, even though it appears correctly in the console. I have developed a function to navigate through the entire structure of th ...

Relationship between multiple Mongoose instances linking to a single entity

Having an issue regarding mongoose and relationships. My "Athletes" collection has the following schema: var athletesSchema = mongoose.Schema({ name : String, regionName : String, age : Number, overallScore : Number, scores : { ordinnal : String, ...

Determine the aspect ratio of the image and incorporate it into the query string

In my current code, I am extracting the dimensions of an image obtained from a cropper tool. I then calculate the aspect ratio of the image by dividing the height by the width. This value is then incorporated into the query string url: urlLocation + imag ...

Plugin for jQuery that smoothly transitions colors between different classes

After searching through numerous jQuery color plugins, I have yet to discover one that allows for animating between CSS class declarations. For instance, creating a seamless transition from .class1 to .class2: .class1 { background-color: #000000 } .class ...

The React hamburger menu triggers a re-render of child elements within the layout

I am currently working with React and Material UI v5. Within my layout, I have a menu component with children. Whenever I click on the menu, it triggers a refresh of the children components. I attempted to resolve this by encapsulating the child components ...