JavaScript Conditional Statement Not Working - javascript

What's wrong with this JavaScript?
var numPackages == 0;
if (coffeeProducts <= 12) {
numPackages == 1;
} else if (coffeeProducts % 12 == 0) {
numPackages == coffeeProducts/12;
} else {
numPackages == (coffeeProducts/12) + 1;
}
Basically, it needs to calculate the number of boxes/packages necessary to ship an amount of items (12 per box). Is there a better way to do this, perhaps using round()?

== is condition.
= is assignment.
The better way is to use Math.ceil() to round to next integer.
So:
var numPackages = Math.ceil(coffeeProducts/12);

All the others explained your mistake with the comparing operator == and the assigning operator =.
The shortest way to solve it would be
var numPackages = Math.ceil( coffeeProducts / 12 );

Make each statement look like this:
if (coffeeProducts <= 12) {
numPackages = 1; // just "=", not "=="
}

Single equals (=) for assignment: x = 10
Double equals (==) for comparison: if (x == 10)
Triple equals for special cases where type is important as well as the value.
Change your two numPackages lines to a single equals and you're good to go :)

Related

javascript two conditions in if statement

I'm trying to write code that checks two conditions in an if statement but no luck.
for(var num = 1; num<=100;num +=1)
{if (num % 3==0) and (num % 5==0) console.log("fizzbuzz");
else if (num % 3==0) console.log("fizz");
else if(num % 5==0) console.log("buzz");
else console.log(num);}
First, change and to &&,
Also, your if statement does not have parenthesis like that:
for(var num = 1; num<=100;num +=1){
if ((num % 3==0) && (num % 5==0)) console.log("fizzbuzz");
else if (num % 3==0) console.log("fizz");
else if(num % 5==0) console.log("buzz");
else console.log(num);
}
Then it should work like a charm!
You need to work your indentation too.
Use && instead of and.
for (var num = 1; num <= 50; num += 1) {
if (num % 3 == 0 && num % 5 == 0) console.log("fizzbuzz");
else if (num % 3 == 0) console.log("fizz");
else if (num % 5 == 0) console.log("buzz");
else console.log(num);
}
Indentation. If you use IDE (like webstorm), there should be an option to auto format the code. FYI: indentation plays a very big role in understanding your own code in some time (for example, right after you write it:))
I wouldn't call it js becase there's logical AND operator: &&, not and. At first glance it can be even treated as a portion of pseudocode, bad pseudocode
if statement has structure like if (condition) operator, so when you want to check multiple conditions, you should wrap them with parenthesis: if (condition1 && condition2 && ... && conditionN). All the conditions are finally equvalent to a single condition that's checked after evaluation.
Of course, if statement allows you not to wrap operators with curly brases: if (condition) some operator;. But it's more readable and understandable if you write if (condition) {operator}. For example, when you change your code and want to add some more operators, it will be more secured from some confusing mistakes. Let's say you want to write smth like this:
if(everythingIsOk)informUser;
Let's say you'd like to add a message if everything is ok. You could write this:
if (everythingIsOk)
informUser;
writeMessage;
In the example above you make the program to write the message anyway because it's a separate instruction. If you wrote initially if (everythingIsOk){informUser} it would be easier to just add one more instruction that must be executed in this particular case. More than that, it's more readable.
You would probably be surprised, but the following is valid too:
if (everythingIsOk);
The following is more readable because at least it makes people think that you haven't forgotten about your construction somewhere in the middle:
if (everythingIsOk){}
And finally, if you want to emphasize that nothing should be done in some cases, that's the approach (just fyi):
if (everythingIsOk){/* Do nothing, no code here is not a mistake! */}
So your code would be more readable if you wrote it like this:
for (var num = 1; num <= 100; num += 1) {
if ((num % 3 == 0) && (num % 5 == 0)) {
console.log("fizzbuzz");
} else if (num % 3 == 0) {
console.log("fizz");
} else if (num % 5 == 0) {
console.log("buzz");
} else {
console.log(num);
}
}
I'd recommend you read at least examples you learn more accurately.

Please help to find out why the code works in such manner (JavaScript)

i've been working on a primitive code and got the unexpected result.
var one = prompt("Enter the number", "4");
var age = parseInt(one);
if (age >= 14 || age <= 90) {
console.log("Correct");
} else {
console.log("Wrong")
}
When I put 100, for example, it says "Correct" instead of "Wrong".
Would you be so kind to answer why it works in such manner.
You are using an or operation, so when age is 100 the first part of the OR operation is true which means that the entire OR condition is true because true OR false is true.
You need to use and AND operator
var one = prompt("Enter the number", "4");
var age = parseInt(one);
if (age >= 14 && age <= 90) {
console.log("Correct");
} else {
console.log("Wrong")
}
Any number will return true, because any number is > 14 OR < 90.
If you need the age to be between 14 and 90, do it this way:
if ( age >=14 && age <= 90 )
I got ur Requirement instead of Using OR Operator i.e "||" you should use AND Operator i.e "&&" then u will get the desired result its a logical error

Check if value is multiple of 10

I want to check if a value is a multiple of a certain number, for example, multiples of 10, but I also want to be able to change it to whatever I want.
if (directWinner == 10){
}
You'd use the modulus operator for that :
if (directWinner % 10 === 0){
directWinner = 20;
}
Added a small dose of jQuery for no good reason at all ?
$.modu = function(check, against) {
return check % against === 0;
}
if ( $.modu(directWinner, 10) ) {
directWinner = 20;
}
You'd use the modulo operator % for that:
var certainNumber = 10;
if (directWinner % certainNumber === 0) {
// directWinner is a multiple of certainNumber
}
Use the modulo operator (assuming positive integers) :
if (directWinner % 10 === 0) {
...
}

Change color depending on value

I don't why this is not working. Can somebody tell me what is the problem with this?
var x = $('#clicked_info').val();
if(x == 1) {
$('#companyname_ph').css({'color':'yellow'});
}
else if(x == 2) {
$('#companyname_ph').css({'color':'red'});
}
You need to use parseInt to convert a string to an integer.
var x = $('#clicked_info').val();
if(parseInt(x) == 1){
$('#companyname_ph').css({'color':'yellow'});
} else if(parseInt(x) == 2){
$('#companyname_ph').css({'color':'red'});
}
OR use string comparison
if(x == '1'){
val returns a string
x == 1 shoulb be x == '1'
x == 2 should be x == '2'
Or you can convert x to int using the following.
var x = $('#clicked_info').val();
x = parseInt(x);
like the other folks here have noted, you should use parseInt when you want to convert a string representation of an integer to a number type. I would add that you should provide a radix to parseInt because if you don't, you may get unexpected results if your string starts unexpectedly with "0x" :)
try doing:
var x = parseInt($('#clicked_info').val(), 10)

Javascript Finding Prime Numbers

I am writing a little script to find and print out all the prime numbers from X thru Y. Here is what I have written:
var numX = prompt('Enter a number greater than 0:','');
var numY = prompt('Enter a number greater than ' + numX + ':','');
while (numX <= numY) {
if (numX == 1 || numX == 2 || numX == 3) {
document.write(numX + '</br>');
} else if (numX % 2 === 0 || numX % 3 === 0 || numX % 5 === 0 || numX % 7 === 0){
document.write();
} else {
document.write(numX + '</br>');
}
numX++;
};
Now, this works just fine so long as the first number is 1. If, however, the first number is anything greater than 1 it does not print out anything. I am not sure if this is the right forum for this question (perhaps a math forum?), but I thought I would ask here on the off chance someone could help me out. I also know that a sieve is the better way to go about this, but I wanted to try and figure this out as a while loop first. Any and all help is appreciated!
While I understand what you are trying to do, I highly recommend taking a look at the Sieve of Eratosthenes. You really want to get the hang of knowing different algorithms to compute these things in case you decide to deal with really large numbers. While the way you go about it now might work in smaller ranges, bigger ranges are going to go crazy.
Also I believe this Stackoverflow question is very similar to this one and the answer for it is very well made:
finding sum of prime numbers under 250
You can try any of the options here : http://www.javascripter.net/faq/numberisprime.htm
Hi i have added bit change to ur code (added condition for 5 and 7 prime numbers) and its working...
var numX = prompt('Enter a number greater than 0:','');
var numY = prompt('Enter a number greater than ' + numX + ':','');
while (numX <= numY) {
if (numX == 1 || numX == 2 || numX == 3 || numX == 5 || numX == 7) {
document.write(numX + '</br>');
} else if (numX % 2 === 0 || numX % 3 === 0 || numX % 5 === 0 || numX % 7 === 0){
document.write();
} else {
document.write(numX + '</br>');
}
numX++;
};
Check the demo here
OK, turns out that I jumped the gun on asking this question. I was more concerned with getting the else if statement working that I failed to even note that my formula was seriously flawed!
The issue possibly could be with the second variable. If the first variable is 1 then the second variable can be any number. However, if the first variable is greater than 1 then the second variable has to be less than 100 or it will not work.

Categories