new to JavaScript, simple if function - javascript

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;

Related

How to return NaN

I'm working on a codewars problem-here's the question:
-Write a function that accepts two integers and returns the remainder of dividing the larger value by the smaller value.
-Division by zero should return NaN.
I have the first part figured out, but how do I return NaN if I divide by 0? I don't know a lot about NaN and I'm pretty new to JavaScript.
function remainder(n, m){
if (n > m) {
let answer = n % m;
if (m === 0) {
return undefined;
}
else {
return answer;
}
}
else if (m > n) {
let answer = m % n;
if (n === 0) {
return undefined;
}
else {
return answer;
}
}
else {
let answer = n % m;
return answer;
}
}
Edit: solved, answer is below
Welcome to our community!
NaN stands for Not-a-Number and it is a property of the global object(in order to understand more about the global object, I would recommend reading about Scopes).
You could access NaN like this:
window.NaN => from a browser
Number.NaN
NaN
If you want to check if a number is NaN you could use: isNaN.
If you want to use it in a function you can just do
function test(x){
if(isNaN(x)){
return NaN;
}
return x;
}
To come back to your problem, you could do something like this:
function calculateRemainder(a,b){
return a>b ? a % b : b % a
}
Where % is known as the remainder operator about which you can read more here. This operator returns NaN if you try to divide by 0 or to operate with Infinity.
The following operations return NaN:
NaN % 2
Infinity % 0
10 % 0
Infinity % Infinity
The problem is that % is not the divider syntax, but this is /.
I created a basic example for you:
In this example, the console logs "divider is 0"
function divider(up, down) {
if (down == 0) {
console.log("divider is 0");
return NaN
} else {
console.log(up / down);
}
}
divider(5, 0);
But here, it will log 2.5
function divider(up, down) {
if (down == 0) {
console.log("divider is 0");
return NaN
} else {
console.log(up / down);
}
}
divider(5, 2);
This is my answer (with help from the comments on my question), and it worked. Thank you for your help!
function remainder(n, m){
if (n > m) {
let answer = n % m;
if (m === 0) {
return NaN;
}
else {
return answer;
}
}
else if (m > n) {
let answer = m % n;
if (n === 0) {
return NaN;
}
else {
return answer;
}
}
else {
let answer = n % m;
return answer;
}
}

Beginner Javascript function problem I'm trying to solve

The question I'm trying to solve goes as follows:
I often struggle to know whether I should wear shorts or pants on a given day. Please help me decide by writing me a function called isShortsWeather
It should accept a single number argument, which we will call temperature (but you can name it whatever you want).
If temperature is greater than or equal to 75, return true.
Otherwise, return false
This exercise assumes temperature is in Fahrenheit
Expected result:
isShortsWeather(80) //true
isShortsWeather(48) //false
isShortsWeather(75) //true
The code I wrote is:
function isShortsWeather(temperature) {
if (temperature < 75); {
return false;
}
if (temperature >= 75) {
return true;
}
}
As snippet:
function isShortsWeather(temperature) {
if (temperature < 75); {
return false;
}
if (temperature >= 75) {
return true;
}
}
console.log(isShortsWeather(80)) //true
console.log(isShortsWeather(48)) //false
console.log(isShortsWeather(75)) //true
Please help me out by informing me what is wrong with my code and how should I fix this issue. I feel like I am relatively close to solving it. Thanks!
Simply return the boolean:
return temperature >= 75;
the main reason it's not working is because you have a extra ; after the first condition.
you can shorten the function body to one line
function isShortsWeather(temperature) {
return temperature >= 75;
}
you forgot ; at the line 2, if you remove it it will work. Also it would be better if you make the 2nd if statement in else if
function isShortsWeather(temperature) {
if (temperature < 75) {
return false;
} else if (temperature >= 75) {
return true;
}
I would recommend a return on both if statements and not a console log on false. You will use console.log to call the function. I have edited the code a bit as the semicolon on line 2 not needed.
function isShortsWeather(temperature) {
if (temperature < 75) {
return false;
} else {
return true;
}
}
temperature = 74;
console.log(isShortsWeather(temperature));
Below you will find the correct code that is working.
Hope answer your questions.
function isShortsWeather(temperature) {
if (temperature >= 75) {
return true;
}
else {
return false;
}
}
console.log(isShortsWeather(76));
console.log(isShortsWeather(74));
function isShortsWeather(temperature) {
if (temperature < 75); {return 0;}
if (temperature >= 75) {return 1;}
}
I think that will solve your problem
You can return the value instead of console logging it.
It would also be a good idea to refactor the "magic number" 75 into a variable with a default value, allowing you to easily change or override it later.
function isShortsWeather(temperature, cutoffTemp = 75) {
if (temperature < cutoffTemp) {
return false;
}
if (temperature >= cutoffTemp) {
return true;
}
}
console.log(isShortsWeather(81));

Will this compare arrays in JavaScript?

I am trying to compare long string numbers. The number length is between 1 and fifty. Comparing the length of the strings worked well but if they were equal length it was a bit harder. I decided to make the strings into arrays, and compare values until they were different. I think this is a formatting error, but I'm not sure.
function compareIntegers(a, b) {
//coding and coding..
var aSplit = a.split("")
var bSplit = b.split("")
if (a.length > b.length){
return "greater";
}
if (b.length > a.length){
return 'less';
}
if (a.length == b.length){
for (i=0; aSplit.length; i++){
if (bSplit.indexOf(aSplit[i] ===-1) {
if (aSplit[i] > bSplit[i]){
return 'greater';
}
if (aSplit[i] < bSplit[i]){
return 'less';
}
else return 'equal';
}
}
}
}
describe("Basic Tests", function(){
it("It should works for basic tests.", function(){
Test.assertEquals(compareIntegers("12","13"),"less")
Test.assertEquals(compareIntegers("875","799"),"greater")
Test.assertEquals(compareIntegers("1000","1000"),"equal")
Test.assertEquals(compareIntegers("999","1000"),"less")
Test.assertEquals(compareIntegers("123","122"),"greater")
Test.assertEquals(compareIntegers(
"1000000000000000000000000000000000",
"1000000000000000000000000000000001"),
"less"
)
Test.assertEquals(compareIntegers(
"1000000000000000000000000000000002",
"1000000000000000000000000000000001"),
"greater"
)
Test.assertEquals(compareIntegers(
"10000000000000000000000000000000000",
"1000000000000000000000000000000001"),
"greater"
)
})})
There's no reason to split the strings into arrays, you can easily access the single characters using an index property or .charAt(). And there's no reason to do this character-by-character comparison by yourself at all (and making mistakes like bSplit.indexOf(aSplit[i])), when that is just the default behaviour of comparing two strings. So I'd write
function compareIntegerStrings(a, b) {
a = a.replace(/^0*/, ""); // strip leading zeroes
b = b.replace(/^0*/, "");
if (a.length > b.length){
return 1;
} else if (b.length > a.length){
return -1;
} else { // a.length == b.length
if (a > b) {
return 1;
} else if (b > a) {
return -1;
}
}
return 0;
}
function comparisonToString(c) {
return ['less', 'equal', 'greater'][Math.sign(c)];
}
You can also shorten that comparison pyramid in compareIntegerStrings to
return Math.sign(a.length - b.length) || +(a>b) || -(a<b);

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.

Is there a more compact way of checking if a number is within a range?

I want to be able to test whether a value is within a number range. This is my current code:
if ((year < 2099) && (year > 1990)){
return 'good stuff';
}
Is there a simpler way to do this? For example, is there something like this?
if (1990 < year < 2099){
return 'good stuff';
}
In many languages, the second way will be evaluated from left to right incorrectly with regard to what you want.
In C, for instance, 1990 < year will evaluate to 0 or 1, which then becomes 1 < 2099, which is always true, of course.
Javascript is a quite similar to C: 1990 < year returns true or false, and those boolean expressions seem to numerically compare equal to 0 and 1 respectively.
But in C#, it won't even compile, giving you the error:
error CS0019: Operator '<' cannot be applied to operands of type 'bool' and 'int'
You get a similar error from Ruby, while Haskell tells you that you cannot use < twice in the same infix expression.
Off the top of my head, Python is the only language that I'm sure handles the "between" setup that way:
>>> year = 5
>>> 1990 < year < 2099
False
>>> year = 2000
>>> 1990 < year < 2099
True
The bottom line is that the first way (x < y && y < z) is always your safest bet.
You could make your own method:
// jquery
$(function() {
var myNumber = 100;
try {
if (myNumber.isBetween(50, 150))
alert(myNumber + " is between 50 and 100.");
else
alert(myNumber + " is not between 50 and 100.");
} catch (e) {
alert(e.message());
}
});
// js prototype
if (typeof(Number.prototype.isBetween) === "undefined") {
Number.prototype.isBetween = function(min, max, notBoundaries) {
var between = false;
if (notBoundaries) {
if ((this < max) && (this > min)) between = true;
alert('notBoundaries');
} else {
if ((this <= max) && (this >= min)) between = true;
alert('Boundaries');
}
alert('here');
return between;
}
}
hope this helps.
Max
The fast and simple way to make this is to create a function like this:
function inRange(n, nStart, nEnd)
{
if(n>=nStart && n<=nEnd) return true;
else return false;
}
Then use that as follows:
inRange(500, 200, 1000) => this return true;
Or like this:
inRange(199, 200, 1000) => this return false;
If you don't like the boolean operator, you could always use nested if statements:
if (1990 < year)
{
if( year < 2099)
return 'good stuff';
}
From a similar solution here: http://indisnip.wordpress.com/2010/08/26/quicktip-check-if-a-number-is-between-two-numbers/
$.fn.between = function(a,b){
return (a < b ? this[0] >= a && this[0] <= b : this[0] >= b && this[0] <= a);
}

Categories