Comparing date to NaN and undefined - javascript

I have a pretty simple if statement but I don't use javascript too much so I think I have made an error somewhere. If you go to my page you can see the value gets alerted as undefined, but a block of code still gets skipped even though the if parameters are == undefined. Does it matter that this is an AngularJS app?
web page: http://alainwebdesign.ca/pl2/#/petType
javascript:
$scope.setDate = function (dateSelected) {
alert(dateSelected);
var now = new Date();
$scope.latest = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes());
$scope.hoursAgo = Math.round((($scope.latest - dateSelected) / 3600000) * 100) / 100;
if ($scope.hoursAgo === undefined || $scope.hoursAgo == NaN) {
alert("Please choose a date/time");
}
else {
alert('You lost your pet ' + $scope.hoursAgo + ' hour(s) ago');
$scope.checkDateSet = true;
}
}

Your problem is not with your if statement. NaN in Javascript is somewhat special.
For example:
NaN === NaN // false
You can read about it more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN
Change your check to:
if ($scope.hoursAgo === undefined || isNaN($scope.hoursAgo)) {
...
} else {..}

To check if ($scope.hoursAgo === undefined || $scope.hoursAgo == NaN)
write like this
if ($scope.hoursAgo === 'undefined' || isNaN($scope.hoursAgo)) {

Related

Why is this if statement not affected by my input?

I want to build an algorithm who convert AM/PM to the 24hours format. It's not finished, but the code I have so far is behaving strangely.
When I give the input "25:05:45PM", it should enter the first branch of the first if statement, but should not enter the second if statement. I've checked the condition, and it's definitely false. My brain is melting.
Here is the code :
function conversionTime(s) {
if (s.includes('PM')) {
let temp = s.slice(0, 8).split(':');
if (temp[0] >= 01 && temp[0] <= 12); {
temp[0] = Number(temp[0]) + 12;
return temp.join(':')
}
} else if (s.includes('AM')) {
let temp2 = s.slice(0, 8).split(':');
return temp2
}
}
console.log(conversionTime("25:05:45PM"))
Gotcha.
if (temp[0] >= 01 && temp[0] <= 12);
This semicolon is the culprit! It's saying "the if statement is over, no need to do anything", so your code is being interpreted like:
if (temp[0] >= 01 && temp[0] <= 12);
{
temp[0] = Number(temp[0]) + 12;
return temp.join(':');
}
The code in the block will always run. This feature exists so you can make full use of let's scoping:
let x = "outside";
console.log(x);
{
let x = "inside";
console.log(x);
}
console.log(x);
Well, really it exists because that's how C works – it predates the let statement – but that's what it's useful for these days.
I Will do that this way..
function conversionTime(timeAPM)
{
let [h,m,s,apm] = timeAPM.match(/(\d+)|(\w+)/g);
if (timeAPM !== `${h}:${m}:${s}${apm}`
|| isNaN(h) || isNaN(m) || isNaN(s)
|| (apm !== 'AM' && apm !== 'PM')
) return undefined;
if (apm === 'PM' && h <= 12 ) h = +h +12;
return `${h}:${m}:${s}`;
}
console.log(conversionTime("25:05:45PM"))
I don't know if it's intentional or not on his part, but the PO's code also returns undefined. Apart from his attachment to the AM/PM labels, the OP gives no explanation on the validity of the entry.
So this second version is content to check that there are indeed 3 numerical values, separate by :, and directly followed by AM or PM.
the number of digits of these numbers is unknown : His test uses an hour = 25 while it is an AM/PM presentation. So why not seconds or minutes expressed with 40 digits...
I'm not claiming my regex is the best in the universe.
I could also have added in my code:
console.log(conversionTime("10:31:25BAM")) // -> undefined
console.log(conversionTime("1:3:5abc")) // -> undefined
console.log(conversionTime("1:3zzzz")) // -> undefined
console.log(conversionTime("a:10:15PM")) // -> undefined
console.log(conversionTime("285::4875PM")) // -> undefined
// or more absurd:
console.log(conversionTime("285:1505:4875PM")) // -> 285:1505:4875

How to write this JavaScript code for finding if a tree is a Binary Search Tree in fewer lines?

In a quiz for my Javascript class, we were told to make a simple tree and write a function that returns true or false whether it is a BST or not.
I got a decent grade, but i got 10 points off because the instructor said "It can be done in 6 less lines".
This is what I had:
function node(value, left, right){
this.Value = value;
this.Left = left;
this.Right = right;
}
//this IS a BST, returns true
var head = new node(8, new node(9, null, null), new node(10, new node(9, null, null), new node(14, new node(13, null, null), null)));
function isBST(currNode){
if(currNode.Left === null && currNode.Right === null){
return true;
}
else if(currNode.Left.Value > currNode.Value || currNode.Right.Value < currNode.Value){
return false;
}
else{
if(currNode.Left === null){
return isBST(currNode.Right);
}
else if(currNode.Right === null){
return isBST(currNode.Left);
}
else{
return (isBST(currNode.Left) && isBST(currNode.Right));
}
}
}
console.log(isBST(head));
Anything I'm overlooking here? Maybe it shouldn't have been recursive?
The problem with your current function is that it does not work. It returns true for:
4
/ \
3 5
/ \
2 100
It seems that all the other answers at this time have the same problem. Here's one that works and is a lot shorter
function isBST(curNode, minval, maxval){
if (curNode == null) {
return true;
}
return (
(minval == null || minval <= curNode.Value) &&
(maxval == null || maxval >= curNode.Value) &&
isBST(curNode.Left, minval, curNode.Value) &&
isBST(curNode.Right, curNode.Value, maxval)
);
}
If all your teacher is worried about is line count... I would consider them to be a bad teacher...
That being said... I'm not saying your code is correct, but here is your code minus the extraneous return statement, with more than 6 less lines.
function node(value, left, right){
this.Value = value;
this.Left = left;
this.Right = right;
}
//this IS a BST, returns true
var head = new node(8, new node(9, null, null), new node(10, new node(9, null, null), new node(14, new node(13, null, null), null)));
function isBST(currNode){
if(currNode.Left === null && currNode.Right === null) return true;
if(currNode.Left.Value > currNode.Value || currNode.Right.Value < currNode.Value) return false;
if(currNode.Left === null) return isBST(currNode.Right);
if(currNode.Right === null) return isBST(currNode.Left);
return (isBST(currNode.Left) && isBST(currNode.Right));
}
console.log(isBST(head));
As an aside: verbose readable code trumps less lines and hard to read 99.99% of the time. 0.01% is when you're in a bad teacher's class who cares more about line count than actually looking at your assignment.
Aside #2: A line more than ~80 characters in length should normally be split into multiple lines for readability. No one likes to read one long line of code.
EDIT: For a real BST modeled after the example # stanford.edu
var head = new node(5,
new node(3,
new node(1, null, null),
new node(4, null, null)
),
new node(9,
new node(6, null, null),
null
)
);

Parameter comparing won't work

Everything works just fine - everything except this one if-else-statement:
else if ((day = 0 || day = 6) && (hour <= 19)) {
greeting = "We wish you a nice weekend and a nice " +
Weekdays[day] + ".";
}
Firefox's Error Message: 'ReferenceError: invalid assignment left-hand side'
..it should be really easy but till now I coudn't find the problem.
Thanks for helping and have a nice day!
Use == for comparison(by value) and = for assigning values.
So in your case, it should be:
...
else if ((day == 0 || day == 6) && (hour <= 19)) {
greeting = "We wish you a nice weekend and a nice " +
Weekdays[day] + ".";
}
...
If you need to compare by both type and value, you should use ===
In short:
var a = 10; // assigns value 10 to variable `a`
"1"==1 // true => Since == compares by value
"1"===1 // false => Since === compares by both type and value. In this case although value is 1, both are of different types (string and integer)

JavaScript if else statement ignored

I have a simple if statement below:
function calculateTotal() {
if (tanksize != 1 || tanksize != 2) {
var setupPrice = basicPrice + StatPrice() + DigiStatPrice() + IRPrice() + UVPrice() + cagePrice();
var setupPrice2 = toFixed(setupPrice, 2);
} else {
var setupPrice = basicPrice;
var setupPrice2 = toFixed(setupPrice, 2);
}
//display the result at the top of page
var divobj = document.getElementById('totalPrice');
divobj.innerHTML = "£" + setupPrice2;
//display the result at the bottom of page
var divobj = document.getElementById('totalPrice2');
divobj.innerHTML = "£" + setupPrice2;
}
But when the tanksize variable is set to 1 or 2, the setupPrice variable is still calculated by adding the basicPrice + StatPrice...etc.
You need to use:
if (tanksize !== 1 && tanksize !== 2) {
with the && operator, or
if (!(tanksize ===1 || tanksize === 2)) {
In your code, you have the first block executing any time the value is not 1 or is not 2, which equates to it always executing.
If the value is 1, then tanksize != 2 is true so tanksize!=1 || tanksize!=2 is true.
If the value is 2, then tanksize != 1 is true so tanksize!=1 || tanksize!=2 is true.
In other words, tanksize!=1 || tanksize!=2 is always true, no matter what the value of tanksize is.
This statement is always true:
if(tanksize!=1 || tanksize!=2){
because, when tanksize = 1, tanksize is different of 2
and when tanksize = 2, tanksize is different of 1.
It is not a javascript error, you just need to change your logic to make the right test in the if...
Try if(tanksize!=1 && tanksize!=2){ instead of if(tanksize!=1 || tanksize!=2){
Your Logic is wrong..
As a matter of fact, OR Operator for two NOT EQUALS is always TRUE ( check boolean table for this) and the conditional statement "if" checks for TRUE or FALSE, hence your code will always return TRUE
Use something like
if(tanksize!=1 && tanksize!=2){
# Your code
}
(tanksize!=1 || tanksize!=2) always will be true by this statement. Change operator || to &&
your first condition is always true, cuz for example if some x = 1, is different of 2 and vice versa.
so this condition is kind of equal to.
if(true) {
// ...
}

Javascript switch

I am working on a zodiac calendar that requires a switch 0-11 for the signs. I have written HTML code that drops down for the month and a text input for the year. The sign should use id 'output' and should also show up in text. I am not sure if I am using my switch correctly, of if my math is causing the problem or why it is not sending to output.
HTML CODE:
<div><label for="sign">Sign</label><input type="text"
name ="sign" id="sign"></div>
Javascript Code
if (year && year.value && (year.length == 4)){
year = parseInt(years.value);
month = parseInt(month.value);
if (month < 2) {
year = (year - 1);
}
year = ((year - 1924) % 12);
} else { // Show Error:
document.getElementById('year').value =
'Please enter valid values.';
}
switch (year){
case 0 :
block code;
break;
etc..
} // End Switch
if (output.textContent != undefined) {
output.textContent = sign;
} else {
output.innerText = sign;
}
return false;
}
Your regular expression could be failing to match your lowercased url. When that happens, the result would be null.
You should be checking the match() result before using it. Something like this:
var matches = url.toLowerCase().match(/https?:\/\/(.+?)[?#\/$]/);
if (!matches || matches.length < 2) {
// Handle error
...
} else {
// Keep going
var domain = matches[1];
...
}
Also, verify that your regular expression is actually doing what you intend.
Because of my javascript code innerText
if (output.textContent != undefined) {
output.textContent = sign;
} else {
output.innerText = sign;
}
I had to delete
<div><label for="sign">Sign</label><input type="text"
name ="sign" id="sign"></div>
and replace it with
<p>Sign: <span id="output"></span></p>
I could have easily changed the javascript code and document.getElementID('output') = sign.value;
The problem should be caused by domain checking instead of calculate function.
Remove domain checking and try again (see if it works).
Errors:
1) if (year && year.value && (year.value.length == 4)){
year = parseInt(year.value);
2) main html didn't declare element "output"

Categories