Parameter comparing won't work - javascript

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)

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

Comparing date to NaN and undefined

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)) {

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

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"

determining var type from prompt command and if else statement

I'm trying to write this exercise from a book:
Write a program to ask yourself, using prompt, what the value of 2 + 2
is. If the answer is "4", use alert to say something praising. If it
is "3" or "5", say "Almost!". In other cases, say something mean.
I made this attempt:
var input = "" || 'number'
prompt ("How many is 2+2 ?", input)
if (input = 4)
print ("Awesome !");
else if (input = 3 || input = 5)
print ("Close !");
else if (input = 'number'
print ("wrong number");
else if (input = 'random text')
print ("use numbers only!")
I know it is wrong. This is I intended to do:
I need to determine the type of var, not just the value. I need to make var either number or string (according to typeof). Why ? For prompt imput, because below else if condition, will be based on which type was inputted.
I know that exercise didn't asked it, but I want make it superior.
= is assignment. == is comparison.
To convert the string that prompt gives you to a number, use parseInt(input,10) - that said, JavaScript will typecast for you, so there's no real need here. You can even tell if the user entered something that isn't a number by testing isNaN(input) for your "use numbers only" result.
So something like this:
var input = parseInt(prompt("How much is 2 + 2?",""),10);
if( input == 4) alert("Awesome!");
else if( input == 3 || input == 5) alert("Almost!");
else if( input == 10) alert("No GLaDOS, we're working in Base 10 here.");
else if( input == 42) alert("That may be the answer to Life, the Universe and Everything, but it's still wrong.");
else if( isNaN(input)) alert("Use numbers only please!");
else alert("You are wrong!");
I'd personally suggest:
var guess = parseInt(prompt('What is 2 + 2?'), 10);
switch (guess) {
case 4:
console.log('Well done!');
break;
case 3:
case 5:
console.log('Almost!');
break;
default:
console.log('Seriously? No.');
break;
}
JS Fiddle demo.
Or, to be more functional about it:
function answerMath (sum) {
var actual = eval(sum),
guess = parseInt(prompt('What is ' + sum + '?'),10);
if (guess === actual) {
console.log('Well done!');
}
else if (guess + 1 === actual || guess - 1 === actual) {
console.log('Almost!');
}
else {
console.log('Seriously? No.');
}
}
answerMath ('2*3');
JS Fiddle demo.
Note that while eval() is the only means I could think of in this situation to evaluate the sum passed to the function as a string, I'm not entirely sure it's a good recommendation (albeit eval() has more bad press than it perhaps deserves, though it does present risks).
In most programming languages, = is assignment, and == tests for equality. So
a = 4 assigns the number 4 to the variable a. But a == 4 checks to see if a is equal to 4.
So for your code, you'd need:
var input = "" || 'number'
prompt ("How many is 2+2 ?", input)
if (input == 4)
print ("Awesome !");
else if (input == 3 || input == 5)
print ("Close !");
else if (input == 'number')
print ("wrong number");
else if (input == 'random text')
print ("use numbers only!")
I'm going to build on David Thomas's answer a little, because if you wanted to make it better, you could easily turn it into a little game.
var numa = Math.round(Math.random() * (100 - 1) + 1);
var numb = Math.round(Math.random() * (100 - 1) + 1);
var answer = numa + numb;
var guess = parseInt(prompt('What is ' + numa + ' + ' + numb + '?'), 10);
switch (guess) {
case answer:
alert('Well done!');
break;
case (answer - 1):
case (answer + 1):
alert('Almost!');
break;
default:
alert('Seriously? No.');
break;
}
Further things you could do would be to include a timer to see how long the user took to answer the question, and ask them if they way to play again when they get it right.
Here is a Fiddle: http://jsfiddle.net/6U6eN/

Categories