Boolean logic interpretation in google chrome console - javascript

I'm having difficulties figuring out why the code below doesn't work as expected:
const userInput = prompt("Enter something");
if (userInput) {
console.log("TRUTHY");
} else {
console.log("FALSY");
}
I keep getting "TRUTHY" no matter what I do. I understand the logic of this code and even when running the source file from the class I'm not getting the expected output.
I should get "FALSY" whenever the input is: 0, null, undefined, an empty string or NaN.
What am I doing wrong?
Thank you.
Edit 1: Turns out I was getting ahead of myself. The code should in fact return "TRUTHY" unless you input an empty string.

Which browser are you using? because when I run this code on ms edge, it returns FALSY when I enter nothing. Also, userInput is set to a string type by default, and the string "0" is true as it contains something. You'll have to use parseInt() to convert the value to an integer, though that doesn't look like what you want to do. Consider looking for syntax errors, and check if your browser is up to date.

Since userInput is a string we have to check its length to find out whether it is empty
const userInput = prompt("Enter something");
if (userInput.length !== 0 && userInput == 0 && userInput == null && userInput == NaN) {
console.log("TRUTHY");
} else {
console.log("FALSY");
}

Change that if() to:
if (userInput == true) {
It's because the if(), as you have it, does a strict equality (===), so object types much match.

Related

Testing to see if entered input is a number (JavaScript)

(inputField was defined earlier as the html inputfield)
No matter what input I enter in the inputField, it will always alert 'good job!'. The code worked perfectly earlier, but I changed like one line and now I can't figure out how to fix it. Triple equality signs === don't work either.
let input = inputField.value;
var amount = parseInt(input);
if(amount == NaN || amount == undefined){
alert('enter a valid number!');
} else{
alert('good job!');
}
Try trpeof to get the type of the amount.
console.log(typeof(amount))
Or to get a boolean value just use isNan.
console.log(isNaN(amount))
To check if amount is a number or not use isNaN(amount)

Having confusion regarding how to pass value in a var through prompt

<script>
var p=prompt("how old are you","");
if(p)
alert(p+" is your age");
else
alert("You dint entered any input or you have entered a non-integervalue");
</script>
This is my javascript code. Suppose i enter my age 0.
Then p=0 this implies the else part of the code will execute. But the code is executing the if part!
Why is it happening?
I'm new to Web-development , Please Help.
Thank You!
parseInt() the result of the prompt, that means, parsing the string result to an integer
Now, if the input is "0", it is parsed to 0, and 0 == false.
Thus the "else" condition would take place, as required.
Also, if a non-integer string is entered, such as alphabets, the result would be a NaN and the else part would occur
var p=parseInt(prompt("how old are you",""));
if(p) {
alert(p+" is your age");
}
else {
alert("You dint entered any input or you have entered a non-integervalue");
}
Just write this code :
var p=prompt("how old are you","");
alert(typeof(p));
You will see that it is a string. "0" is a string, so it will be evaluated to true as it is not empty or null.
So, parse it to a number before doing anything.
If you want to ensure the prompt input is number, you should use isNaN function to check the input.
var p=prompt("how old are you","");
if(!isNaN(p)) alert(p+" is your age");
else alert("You dint entered any input or you have entered a non-integervalue");

Unable to use "test" as value in javascript but can use a number like 1

I am running into an issue where I cannot use a value based on words to trigger a form change with the onchange option. I run into an issue were the browser returns that it cannot find the variable If I assign values that are numeric for the options everything works. The issue being here that I need a value word to be entered into the database and not a value number. I know this is not the clearest description but any help would be great.
function test(){
var selopt = document.getElementById("topic").value;
if (selopt == test) {
document.getElementById("f1").style.display="block";
document.getElementById("f2").style.display="none";
}
if (selopt == 2) {
document.getElementById("f2").style.display="block";
document.getElementById("f1").style.display="none";
}
}
I guess you mean
if (selopt == test)
What is test? It is a variable, not a string. You are checking to see if selopt is equal to a function.
if (selopt == "test")

how to simplify my conditional statement?

I am trying to simplify the following codes. The codes seem to redundant to me. Are there anyone here can help me out? Thanks a lot!
if(area.regionCode=='0' || area.regionCode==null){
var fakecode=area.region.substring(0, area.region.length - 1);
area.region= fakecode +i;
}
Whenever you think some code is not directly revealing, try giving it a new home with a suitable name:
if (!isValidRegionCode(area.regionCode)) {
...
}
...
function isValidRegionCode(regionCode) {
return area.regionCode != null && area.regionCode != '0';
}
It has more code overall, but makes your intentions clear.
if(parseInt(area.regionCode) > 0) {}
I would recommend explicit condition checks. When using:
if (area.regionCode) { }
Style of logic, one is treating varAny as a boolean value. Therefore, JavaScript will perform an implicit conversion to a boolean value of whatever object type varAny is.
or
if(Boolean(area.regionCode)){
codes here;
}
both will work same
returns false for the following,
null
undefined
0
""
false.
beware returns true for string zero "0" and whitespace " ".
you can also first trim the output so " " issue will be solve
here tutorial How do I trim a string in javascript?
in the #mttrb and #nnnnnn described case you can first convert string to either int or float by parseInt() and parseFloat() check this Converting strings to numbers

Check validation for numbers only

following is my piece of code which checks if the input format is EMAIL which comes from the form input or not and validates accordingly i want to know how can i modify the following code that validates if the input was only number
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
}else{
$('#email_error').fadeOut(500);
}
Use jQuery's IsNumeric method.
http://api.jquery.com/jQuery.isNumeric/
$.isNumeric("-10"); // true
if (email.match(/[0-9]+/)) {
//it's all numbers
}
EDIT
As mentioned in the comments, to ensure that the entry is ALL numbers, the regex would have to include the begin and end characters, ^ and $:
if (email.match(/^[0-9]+$/)) {
//it's all numbers
}
Or even more succinctly:
if (email.match(/^\d+$/)) {
//it's all numbers
}
I don't deserve the credit for that fix, but I did want to correct it for anyone who may come find this later.
I would use:
if(isNaN(email*1)){
//evaluated to NaN
}else{
//evaluated to number
}
In this case the (email*1) have the possibility to evaluate to NaN, and thus will fail the check because the list of falsish values are 0,"",false,null,undefined,NaN
Check if converting the email address to a Number object returns a 'Not a Number' value; if not, the input was a number. The code would look like this:
if(!isNaN(Number(email)) {

Categories