I am trying to disable a button depending on a couple of conditions.
<Button disabled={((myobject && myobject.name === "bob") || user.registered) ? true : false} >my button</Button>
Essentially, I want to disable the button if myobject.name is "bob" or if the user is registered (eg. user.registered is not nil). As it stands now, the button seems to get disabled if myobject.name is "bob" but it seems to ignore user.registered. What am I doing wrong?
many thanks!
You can simplify your code with optional chaining and by omitting the ternary, as it is redundant here:
<Button disabled={myobject?.name === "bob" || user.registered}>my button</Button>
Inside the button tag you could try to use just the two constraints you want to impose (I didn't understand why the myobject at the beginning though). It could be something like the following:
(myobject.name === "bob" || user.registered) ? true : false
It looks like you're probably pretty close, the code you have should work fine. I would make sure to check two things. Make sure that user.registered has a "truthy" value.
If it's a string or a number it could be evaluating to false where you don't expect it. In Javascript 0 undefined null "" (empty string) and NaN are all evaluated as false
You should also make sure that myobject is defined somewhere. You'll still get a reference error if myobject never gets declared. if myobject is any of those values that evaluate to false though and user.registered == true then your code should do what I think you're trying to accomplish. If not you might need to give a little more detail as to what you expect to happen and some sample values to look at.
Related
I have some weird inconsistent bug in my code that's very hard to reproduce. It shows up but if I run the same sequence again, it goes away. If I try to debug it, it goes away.
Anyways, I'm wondering if the following could be the culprit
Suppose I have the following code
var myBoolean; // undefined
if( !myBoolean ) {
doX();
} else {
doY();
}
Question is, in the above code, will it run doX() or doY()?
When I test it, it seems to run doX(), but I know that there's a more proper way of checking for undefined.
if( typeof myBoolean == 'undefined' || !myBoolean ) { ...
So my question is, could the improper way of checking myBoolean be causing indeterminism in my code? It's just that I would have to make this code change in a lot of places and I just want to know if this is the issue before doing anything.
The expression !myBoolean will always be true when myBoolean is undefined. However, it will also be true when it's 0, "", false, NaN, or null.
Whether that's OK or not depends on the situation in your program. The sample code you wrote is clearly pointless; since myBoolean will definitely be undefined in that if statement, the if can be eliminated completely. In a real situation, you may know that a variable or object property will be either undefined or an object reference.
A lot of people code defensively as a practice, so such a programmer would be likely to include a more explicit test. Most of the time, it's true that the values null and undefined have the same essential meaning in typical coding situations, so if that's the case then it's safe to write
if (myBoolean == null)
The == comparison will be true only when myBoolean is either undefined or null, and not in any other situations. In other words,
if (myBoolean == null)
is effectively the same as
if (myBoolean === undefined || myBoolean === null)
You may use whichever you prefer of course :)
I wrote a function that works great for mobile, based on something I found on SO a while ago.
jQuery(document).on('touchstart', function(event) {
if ( !jQuery(event.target).closest("#peopleMenu").length) {
jQuery("#peopleMenu").fadeOut();
}
});
the part that I found was in the "if" statement that took me a bit to wrap my head around.
It is saying that if the target touch event is on #peopleMenu , it will stay open, or close if touched off. The if statement boils down to :
if (!1) {
//false - understand this.
}
if (!0) {
//true - hmmm.
}
My question is basically is this a common programming paradigm, a strange js feature, or is it just trickier than it needs to be? Thanks.
This is common in many languages. Everything in JavaScript has an inherent Boolean value, generally known as either truthy or falsy.(e.g. 0 or an empty string). So in this case, if the length comes back as 0, the if statement is false. Here is a great writeup on this topic as it relates to Javascript if you care to know more: Truthy/Falsy
It is common, it mean if you touch something else than #peopleMenu or its childrens, do something.
0 is a falsy value while every other integer are truthy.
Using bang (!) reverse the value, !true == false and !false == true.
The .length property of jQuery is the way to know how many element are selected. 0 mean none.
After reading both :
difference between "void 0 " and "undefined" , https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/void
I still have some questions.
I've read that
window.undefined can be overwritten vwhere void operator will return the undefined value always
But the example which caught my eyes was the one in MDN :
Click here to do nothing
In order to do nothing , I always thought I should write :
href="javascript:return false;"
And this leads me to another question : (at Href context !) :
javascript:void(0); vs javascript:return false;
What is the differences ?
Also - Does
function doWork() {
return void( 0 );
}
is exactly
function doWork() {
return undefined;
}
Thanks.
This will not work properly:
href="javascript:return false;"
because you are not in a function. You are thinking of this:
onclick="return false;"
which is correct since return false; is placed in a function. The false value tells the onclick to prevent the default behavior of the element.
For the return statement to work in an href attribute, you'd need a full function.
href="javascript:(function() { return false; })();"
but that's just long and ugly, and as the comments note, JavaScript in an href is generally discouraged.
EDIT: I just learned something. Having a non undefined expression as above seems to replace the elements with the return value (at least in Firefox). I'm not entirely familiar with the full ramifications of using JavaScript in an href, because I never do it.
Yes, this:
return undefined;
returns exactly the same thing this:
return void 0;
as long as the undefined variable has not been redefined or shadowed by some other value.
But while they may return the same thing, it's not entirely accurate to say they are the same thing, because:
undefined is a global variable whose default value is the undefined primitive
void is an unary operator that will replace the return value of its operand with the undefined primitive
So they both result in the undefined primitive, but they do so in a very different way.
If you specify javascript: something as a value of href attribute, this something will be evaluated when someone activates that link.
The result of this evaluation will be checked: if its typeof evaluates to 'undefined' string, nothing will happen; if not, the page will be reloaded with the evaluation's result as its content:
Nothing to see here, move along...
No, still nothing...
Check this out!
The first two links here will do basically nothing. But the third one is quite more interesting: whatever you enter in prompt will be shown to you - even an empty string! But that's not all: if you click Cancel, you would still see a new page - with null printed (as cancelled prompt returns null, and, as you probably know, typeof null is in fact object; and null converted to String is, well 'null').
It could get more interesting:
What happens here?
And here?
Well, here we still get nothing at the first link. But second link will show you 333 in IE8. :)
And that's, I suppose, answers your second question as well: typeof void(0) will always be undefined. typeof undefined could give you dragons if someone decided it's a good idea to reassign them to window.undefined. )
... And yes, javascript: return false; is just wrong: you cannot return from non-function environment. You probably confused it with onclick: return false, but that's completely another story. )
I opened a js file that I wrote a while back and although it's working, I thought I spotted an error. (JS is not my primary language)
I had this:
if( myvar = fieldval.match(mypattern))
{
//Do Stuff
}
So I think I get it. Is this a correct statement?:
A javascript assignment operation evaluates to the value being assigned.
I tested on w3schools
<script type="text/javascript">
var str="The rain in SPAIN stays mainly in the plain";
var patt1=/ain/gi;
var test
document.write(test=str.match(patt1));
</script>
and it writes "ain,AIN,ain,ain" where I might have expected it to write "true" or not to write at all because boolean true is not a string. Is my line of thought and then ultimate conclusion correct. (I ask about my line of thought on this because I do not have a lot of formal CS training.)
It is a correct statement. The new value of myvar is tested:
if ( myvar = fieldval.match(mypattern) )
When the String.match method cannot find a match, it returns null. !!null === false, so the if-block is not evaluated. When any non-empty match is found, the condition is true, and the block is evaluated.
In this case, it is very likely that the if-statement is correct, and that the following is intended:
if ( (myvar = fieldval.match(mypattern)) !== null )
Rob W is correct, however it's extremely poor practice to put an assignment in an if statement like that. In the future, anyone coming along (including yourself) will scratch their head at that statement to determine if that's what you really meant.
I highly recommend Douglas Crockford's talk: http://www.youtube.com/watch?v=taaEzHI9xyY It'll make anyone (Js dev or not) a better developer for watching it because you'll consider the implications of your coding style and what future maintainers might assume.
match returns an array of matching values, not boolean. Use test instead.
The function string.match() returns an array of matches, or null if no matches are found. The code works because null evaluates to false in an if statement, while an array evaluates to true.
So indeed, the result of str.match is stored in myvar and then myvar is evaluated as boolean. It works as expected.
I've just been looking at the _.isEqual function of Underscore.js and a section of the code goes something like this:
if (a === b) return true;
if (typeof a !== typeof b) return false;
if (a == b) return true;
I'm just wondering if there's any case where the third statement could be reached and evaluate to true?
Edit: Just to be clear, this isn't my own code I'm talking about, I'm reading the source of Underscore, in particular, this line and I was curious about why they're doing that.
I've just been browsing through the Underscore repo and came across a short discussion where someone asked the exact same thing, and it looks like it is actually unnecessary.
Following the algorithm defined by the ECMAScript Language Specification in section 11.9.6 and section 11.9.3 seems to show that no pair of values should return true in the above case.
So, in short, no, that situation is not possible.
The only situation where == and === react unexpectedly is when comparing a literal string ("123") to a constructed string (new String("123")), which would fail the first test.
However, on the second test it gets caught because the constructed string has the type object, but the literal has the type string.
Based on that, I'd say no, the third statement can never be reached, and evaluate to true.
When you use the == operator and the expressions are of different types, JavaScript will generally convert the two into the same type before comparing.
For example, this can happen with null and undefined. null == undefined is true, even though null === undefined is false. However typeof null is "object", while typeof undefined is "undefined". So, in this case you should return false on the second statement.
You can read all the details in the spec (section 11.9.3), it is very involved:
http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
My initial guess was that it was to work around a broken browser implementation.
However after digging into the git logs for that file it looks like the corresponding line was in the very first underscore.js checkin. (I'm not gonna hunt in the parent documentcloud core.js repo...) You can see it at line 334 of https://github.com/documentcloud/underscore/commit/02ede85b539a89a44a71ce098f09a9553a3a6890 .
So now my guess is that its just cruft that got left in, never completely tested and never cleaned out.