JavaScript if statement to check for either one, but not both

Hey there, fellow developers. I'm currently encountering a mental block and struggling to find a solution for my issue.

Here is the code snippet in question:

if ((n % 3 === 0 || n % 5 === 0) &&( n % 3 !== 0 && n % 5 !== 0))
    {
        return true;
}
else {
    return false;
}

In essence, I need to determine if a number is a multiple of either 3 or 5 but not both.

Unfortunately, regardless of the input number (whether it's a multiple of 3, 5, or both), the test consistently fails. Initially, I believed this could be achieved within a single statement.

The following alteration of the code does yield correct results:

if (n % 3 === 0 || n % 5 === 0)
{
    if( n % 3 === 0 && n % 5 === 0)
    {
        return false;
    }
    else {
       return true;
    }
}
else {
    return false;
}

Nevertheless, I am puzzled about what exactly is lacking in the initial test. My aim is to consolidate all conditions into one line, yet due to this mental lapse, I am unable to pinpoint the missing piece to solve this puzzle.

Answer №1

An alternative method is to utilize the XOR operator

result =  (num % 4 === 0 ^ num % 6 === 0);

Answer №2

Whenever a number is divisible by both 3 and 5, it will automatically be divisible by 15.

Kindly test the condition below:

if ((num % 3 === 0 || num % 5 === 0) && (num % 15 !== 0))

Answer №3

adjust

if ((n % 3 === 0 || n % 5 === 0) &&( n % 3 !== 0 && n % 5 !== 0))

transform to

if ((n % 3 === 0 || n % 5 === 0) && !(n % 3 === 0 && n % 5 === 0))

The primary part of the logic is to ascertain if the number in inquiry is divisible by either 3 or 5, while the subsequent should be about determining if only one of them is present. Consequently, I modified the second section to check for both matching and then negated it.

Answer №4

To abide by the conditions:

if ((n % 3 === 0 || n % 5 === 0) &&( n % 3 !== 0 || n % 5 !== 0))

Answer №5

if ((num % 3 === 0 && num % 5 !== 0) || (num % 5 === 0 && num % 3 !== 0)) {
    return true;
} else {
    return false;
}

(not yet verified)

Answer №6

Your second check is incorrect:

if ((n % 3 === 0 || n % 5 === 0) &&**( n % 3 !== 0 && n % 5 !== 0)**)

Please amend the condition to:

(! (n%3 === 0 && n % 5 === 0 ) )

Answer №7

Here's a concise implementation of the XOR operation using conditional statements in JavaScript.

if((num % 3 === 0)? (num % 5 !== 0) : (num % 5 === 0)) {
  ...
}

You can also simplify it by directly comparing the results of the conditions as boolean values:

if( (num % 3 === 0) !==  (num % 5 === 0)) {
  ...
}

This makes the code more compact and easier to understand at a glance.

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

Guide on setting a value in $(document).ready using code behind

I am currently working on a .NET application with the use of Twitter Bootstrap. My main challenge right now is retrieving data from a .aspx.cs page to a .aspx page. Here's a look at my code: strObject.cs public class strObject { public string Nam ...

Instructions for loading static HTML content in the browser from a specific directory

Exploring my file hierarchy: public---| |-index.html |-static-| |-static.html After launching the project at localhost:4000, it directs to the public folder and displays index.html. However, I am looking to load static ...

How can we determine if a Node.js application will remain operational?

How is the longevity of a Node.js app determined? For example, consider this code snippet: console.log('Hello World'); In this case, the phrase will be printed and the app will exit immediately. However, with a web server that is actively lis ...

A guide on receiving object input within AngularJS

I am working on a form that looks like this: <input type="text" ng-model="gen.name" ng-repeat="gen in movie.genres"> The gen in the movie.genre is an object with two key-value pairs: Object{ id: 24, name : insidious } However, when I submit the ...

Utilizing Google Maps in React to display numerous markers sourced from marker.js components

My goal is to implement multiple markers using Google Maps React, similar to the example provided in this link. However, my file structure differs significantly from the given example. How can I adjust it to work with my application? /* global Google*/ i ...

A guide on incorporating unique font weights into Material UI

Looking to customize the Material theme by incorporating my own font and adjusting the font weights/sizes for the Typography components. I am attempting to set 100/200/300/400/500/600/700 as options for each specific typography variant, but it seems that o ...

Showing Angular 2 Data in JSON Format

When I retrieve an object with a Promise, it is structured as follows: export class ShoppingCart { Cart_Items: [ { Id: number, SKU: string, Link: string, ImageURL: string, Title: string, Description: str ...

Function Errors, How to Fix Them?

I've recently developed a tool for character creation within a new video game. However, I'm currently facing an issue: When it comes to assigning points in Magic Power or Weapon Power for the Warrior and Wizard characters, there seems to be a p ...

Is it possible to run my JavaScript script immediately following the execution of npm run build?

Hey everyone! I am trying to run my JavaScript file right after receiving the successful message from npm run build. Currently, I am working on a Vue.js codebase. Is there a way for me to log and create a file in my code repository containing the 'run ...

Retrieving the initial data from a JSON array

After declaring an array called myclinicsID using var myclinicsID = new Array();, I added some data to it. When I use alert(JSON.stringify(myclinicsID)), the output is ["1","2","3","4"] However, when I try to access this array in my function and check the ...

What is the best way to implement a custom layout with nuxt-property-decorator?

Summary of Different Header Components in Nuxt In order to set a different header component for a specific page in Nuxt, you can create separate layout files. layout ├ default.vue // <- common header └ custom.vue // <- special header for s ...

I am looking for a string with this particular format in JavaScript

I am working with a JSON string array that looks like this: var dataMaster = [ {"id":1,"name":"John Doe","age":30}, {"id":2,"name":"Jane Smith","age":28} ] If you want to see how I would like to transform this data, please visit the following lin ...

Retrieve data from MongoDB that is within the past week in ISO string format

My goal is to retrieve data from MongoDB that is exactly a week old. The specific field I am focusing on is - { _id:821398723913, closed_at:"2020-06-10T01:43:59-04:00" } I am looking to fetch all objects where the 'closed_at' field falls wit ...

Reviewing file information prior to submission

Is there a way or method we can utilize to validate file details (extension and size) before the form is submitted by the user? I have limited knowledge of jQuery or JavaScript, so please provide detailed assistance if that is the solution. I envision tha ...

Using setInterval in JavaScript to automatically update a TextField

As someone who is relatively new to Javascript and jQuery, I am trying to make a simple code that updates a text field with random values every 5 seconds. However, my implementation does not seem to be working. I apologize if this question seems too basic ...

Jquery function for determining height across multiple browsers

I am currently facing an issue with setting the height of table cells in my project. While everything works smoothly on most browsers, Firefox seems to add borders to the overall height which is causing inconsistency across different browsers. If anyone k ...

Is it possible to generate a post automatically every second using an AJAX call, with no user input required?

Want to find the answer? Check out this link: Render a view in rails via AJAX and controller In my Rails application, I have a Post model that automatically creates and saves new posts while deleting old ones every 10 seconds using an AJAX call set withi ...

Javascript textbox and submit button

Is there a way to generate a text box with a submit button and save the input into a JavaScript variable? ...

Adjusting the placement in Draw2D

I'm a newcomer to this library and I'm struggling to figure out how to properly size and position the canvas. If anyone could provide guidance on the best way to do this, I would greatly appreciate it. $(window).load(function () { // se ...

The onLayoutChange function keeps overwriting the data stored in my local storage

When my layout changes, the new changes are saved into local storage and the layout state is updated. onLayoutChange(layouts) { saveToLS("layouts", layouts); } However, an issue arises when the page is refreshed. The layout g ...