confuse about number compare in javascript - javascript

The code is simple:
var i = 0.5;
if (i < 0) {
console.log('small');
} else {
console.log('big');
}
but the result is big!, what's wrong about my code?

The else part of your if-statement evaluates i >= 0. And 0.5 >= 0.
Perhaps you wanted to write:
if (i >= 0 and i < 1) {
console.log('small');
}
But I don't know what you would consider small ;-)

there is nothing wrong in your code, lets take a deep look on your 'if' condition, you will get the answer that 0.5 > 0
you may be want to write this
var i = 0.5;
if (i > 0) {
console.log('big');
} else {
console.log('small');
}

Your code logic is completely right...
0.5 is greater than 0

Related

How do i check if a variable is a specific number in JS

Im trying to make a simple clicker game (im pretty new to coding in javascript) but the player can buy things even if they dont have enough, so i tried to do this
function clickpowup() {
if(click += 50) {
clickpower += 5;
click += -50;
}
if(click !== 50) {
alert("Not enough cookies")
}
This is how my variables are laid out above the text
var click = 0;
var clickpower=1;
function clickpowup() {
if(click += 50) { ///here the code is wrong? if(click <= 50) you want?
clickpower += 5;
click += -50;
}
if(click !== 50) {
alert("Not enough cookies")
}
The if the condition seems wrong. if(click <= 50) are you looking for something like this?
If I'm reading your code right and understanding it... did you mean += to be "greater than or equal to?" If so, that's >= not +=. Also if (click !== 50) would mean "if click is not 50." 51 is not 50, but is "enough cookies" so that should be if (click <= 50), right?
The if condition you have coded is not correct(if(click += 50)).The if condition should return either true or false. It cannot interpret the output of this addition operation.
END NOTE:
Please try to explain your code in a better way

Functions and else ifs

I'm still pretty new to JavaScript and need to be pointed in the right direction on a tiny project that is just for practice.
Very sorry if I'm not posting incorrectly, this is my first post on Stack Overflow and any help is appreciated.
I've tried accomplishing my goal a few different ways and haven't gotten there.
attack.addEventListener("click", function(){
hit();
});
function hit(){
if (bossHealth.textContent > 0 && playerFocus.textContent >=2) {
playerFocus.textContent -= 2;
bossHealth.textContent -= 3;
console.log("attack");
}
else if (bossHealth.textContent >= 0 && playerFocus.textContent < 2){
alert("Attack costs 2 focus, try regenerating this turn to gain focus and health!");
}
};
strong.addEventListener("click", function(){
bigHit();
});
function bigHit(){
if(bossHealth.textContent > 0 && playerFocus.textContent >= 5){
playerFocus.textContent -= 6;
bossHealth.textContent -= 6;
console.log("strong attack");
}
else if (playerFocus <5){
alert("Strong attack costs 5 focus, if you do not have enough focus try regenerating for a turn");
}
else (bossHealth.textContent <= 0){
bossHealth.textContent = "Dead";
alert("You've killed the bad guy and saved the world!!!");
}
};
easy.addEventListener("click", function(){
reset();
});
function reset(){
playerHealth.textContent = 10;
playerFocus.textContent = 10;
bossHealth.textContent = 10;
};
hard.addEventListener("click", function(){
hardMode();
});
function hardMode(){
playerHealth.textContent = 10;
playerFocus.textContent = 10;
bossHealth.textContent = 15;
};
With function hit I don't get the alert in my else if statement
with function bigHit I also don't get my alert for the else if statement and neither part of the else statement works.
also subtraction works in my functions, but when trying to add another function that uses addition in the same way it adds the number to the end of the string instead of performing math
You really shouldn't depend on what is in the DOM for logic. You should try with local variables then update the DOM based on those variables.
var boss = {}
var player = {}
function reset(){
player.health = 10;
player.focus = 10;
boss.health = 10;
update()
};
function hit(){
if (boss.health > 0 && player.focus >=2) {
player.focus -= 2;
boss.health -= 3;
console.log("attack");
} else if (boss.health > 0 && player.focus < 2){
alert("Attack costs 2 focus, try regenerating this turn to gain focus and health!");
}
update()
}
function update() {
playerFocus.textContent = player.focus
playerHealth.textContent = player.health
bossHealth.textContent = boss.health
}
Your issue is caused by textContent automatically turning your numbers into strings, by managing the data using your own variables this doesn't affect your code's logic.
Alternatively you could parse the strings as numbers using new Number(playerFocus.textContent), parseFloat(playerFocus.textContent), or +playerFocus.textContent but your code will become very hard to read very quickly.
Hope this enough to help you to make more edits to your code.
It looks like your playerFocus variable is a DOM node? Based on that assumption, your condition is missing a check for its textContent:
if (bossHealth.textContent > 0 && playerFocus.textContent >= 5){
// ...
}
else if (playerFocus.textContent <5){
// ...
In JavaScript, else blocks cannot have conditions, so if you want to conditionally check whether bossHealth.textContent <= 0 at the end of your bigHit function, you will need to change it to an else if (bossHealth.textContent <= 0) { ... } block instead.
I'm adding on to #LoganMurphy's comment and my own. In order to use the value of bossHealth it needs to be an integer. Change your code to look something like this:
function hit(){
if (parseInt(bossHealth.textContent) > 0 && parseInt(playerFocus.textContent) >=2) {
playerFocus.textContent -= 2;
bossHealth.textContent -= 3;
console.log("attack");
}
else if (parseInt(bossHealth.textContent) >= 0 && parseInt(playerFocus.textContent) < 2){
alert("Attack costs 2 focus, try regenerating this turn to gain focus and health!");
}
};
https://www.w3schools.com/jsref/jsref_parseint.asp

new to JavaScript, simple if function

I just made the jump from IDE to Node-RED where JavaScript comes into play. I am eager to learn but my knowledge is limited knowledge.
What I am trying to do, is simple to check the msg.payload, if the value is larger than 25 then I want to return 1 else I want to return 0.
I have tried different codes, but it does not work.
m = msg.payload;
if (m < 25)
{
return 1;
}
else if (m > 25)
{
return 0;
}
and
m = msg.payload;
if (m < 25)
{
return 1;
}
else ()
{
return 0;
}
For Node-RED function nodes you must return a msg object not just a value.
So the correct form for this test is as follows.
if (msg.payload > 25) {
msg.payload = 1
} else {
msg.payload = 0;
}
return msg;
You can do it in one line:
return msg.payload > 25 ? 1 : 0;
or if you just need booleans (true/false):
return msg.payload > 25;
Try this:
if (Number(m) > 25){
return 1;
}
else{
return 0;
}
You can simplify this a good bit, the else isn't even needed in this case:
if (m > 25) {
return 1;
}
return 0;
When the return inside the if statement is executed, the code that follows won't be run... making the else statement unnecessary.
The else is redundant when you're just returning like that, and you've got your comparison operators backwards. Right now it'll return 1 if it's less than 25, not greater than.
if (msg.payload > 25) {
return 1;
}
return 0;
You should learn comparision operator where > denotes greater than and < denotes lesser than , you can simplify using ternary operator as
return msg.payload > 25 ? 1 : 0;
DEMO WITH IF ELSE
function check(m){
if (m > 25){
return 1;
}
else
{
return 0;
}
};
console.log(check(50));
DEMO WITH TERNARY
function check(m){
return m > 25 ? 1 : 0;
};
console.log(check(50));
As you have mentioned that you want to return 1 if value is greater than 25. Please check that you have written wrong condition.
Your condition must be this:
if ( m > 25 ){
return 1;
} else {
return 0;
}
You are making a very silly mistake of less than and greater than sign. Hope it helps you.
m = msg.payload;
if (m > 25)
{
msg.payload=1;
}
else if (m < 25)
{
msg.payload=0;
}
return msg;

Change div class based on positive or negative value - issue with values between 1/0/-1

I'm using this snippet for changing class of div based on positive or negative values
<script type="text/javascript">$('.price-change').each(function() {
if (parseInt($(this).text()) < 0) {
$(this).addClass('negative');
}
else if (parseInt($(this).text()) >= 0) {
$(this).addClass('positive');
}
});</script>
I'm having issues with values that are in between 0 and 1 and 0 and -1. So if the value is -0.15 it will show green, although it needs to show red since there is - before value.
Why is that happening? What is the best way to fix it?
Thanks in advance
Try parseFloat instead of parseInt. parseInt will convert the -0.15 to 0 while parseFloat will compare it to the actual -0.15.
<script type="text/javascript">
$('.price-change').each(function() {
if (parseFloat($(this).text()) < 0) {
$(this).addClass('negative');
} else if (parseFloat($(this).text()) >= 0) {
$(this).addClass('positive');
}
});
</script>
Small example: http://jsfiddle.net/6mymcn4c/1/
Try with .parseFloat():
$('.price-change').each(function() {
if (parseFloat($(this).text()) < 0) {
$(this).addClass('negative');
} else if (parseFloat($(this).text()) >= 0) {
$(this).addClass('positive');
}
});
Demo
$('.price-change').each(function() {
if (parseFloat($(this).text()) < 0) {
$(this).addClass('negative');
} else if (parseFloat($(this).text()) >= 0) {
$(this).addClass('positive');
}
});
.negative{
color: blue;}
.positive{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price-change">1</div>
<div class="price-change">0</div>
<div class="price-change">-0.15</div>
<div class="price-change">-10</div>
why is that happening
Add console.log(parseInt($(this).text(),10)) and you'll see what is happening.
parseInt converts to the nearest whole number (an integer). -0.15 is not an integer so will round to zero, which in your case is positive.
What is a way to fix it?
You can use parseFloat() instead:
$('.price-change').each(function() {
var val = parseFloat($(this).text());
$(this).addClass(val < 0 ? 'negative' : 'positive');
]);
or you can use other functions, such as floor which returns the largest integer less than or equal to a given number (ie always rounds down).
$('.price-change').each(function() {
var val = Math.floor($(this).text());
$(this).addClass(val < 0 ? 'negative' : 'positive');
]);
You can use try and catch to handle these errors
http://www.javascriptkit.com/javatutors/trycatch.shtml
Or
you can use If condition and manually handle the output in these known conditions the result in the code
Finally you can use this :
$('.price-change').each(function() {var x = parseFloat($(this).text();If(x>0){x.addClass('negative');}
else{ x.addClass('positive');}});

Prime factor in javascript, why is this case not working?

I'm writing a primality checker in in j/s and I was wondering why I'm getting true as a return for when I test 55... It seems to work fine for all the other cases I checked just not 55, can someone tell me where I went wrong?
var isPrime = function(num){
if (num === 2){
return true;
}
else if(num%2 === 0){
return false;
}
else{
var i = 2;
while(i<num){
if((num/i) % i === 0 ){
return false;
}
i++
}
return true;
}
};
Thanks in advance and apologies for the noobness!
if((num/i) % i === 0 ){
return false;
}
What is this case?
Shouldn't it be
if(num % i === 0 ){
return false;
}
Just as #Andrey pointed out, your if statement inside the while loop is not correct. For 55 at i=5 you should get false for 55 being prime, but 55/5 % 5 == 1 Also you could use just == instead of === for logical equals, since === checks if both values and type are equal, which is not necessary here.
Try this.
var isPrime = function isPrime(value) {
var i = 2;
for(i; i < value; i++) {
if(value % i === 0) {
return false;
}
}
return value > 1;
};
Even if your bug may be solved, I'd recommend to think about some other aspects to optimize your code:
Clarify your corner cases: In the beginning, check for n<2 -> return false. At least to math theory primes are defined as natural number larger then 1, so 1 is by definition not a prime like all the negative numbers. Your code won't handle negative numbers correctly.
You don't have to check all divisors up to n-1. You can obviously stop checking at n/2, but there are even proofs for tighter bounds which means you can stop checking already at √n if I'm right. To further optimize, you don't have to check even divisors >2.
else {
var i = 3;
while ( i < num/2 ) {
if( num % i == 0 ) {
return false;
}
i+=2;
}
return true;
}
See https://en.wikipedia.org/wiki/Primality_test for details about testing of primes.
P.S: I just wrote the code here in the text box, but it looks like it might work.

Categories