Boolean object is not working properly in condition [duplicate] - javascript

This question already has answers here:
Why does !new Boolean(false) equals false in JavaScript?
(2 answers)
Closed 5 years ago.
I´m really confused. Maybe anyone can help me?
The problem is the following:
var isSignInside = new Boolean(someCondition);
if (!isSignInside) {
//doStuff
}
else {
//doOtherStuff
}
Now, if isSignInside is false (the debugger told me), the script still jumps to //doOtherStuff. How can this be?
The rest of the snippet isn´t of relevance, but I can share it if asked.
Surely there is an easy explanation i don´t see. Thanks in advance.
Edit:
The someCondition really is a custom method "forced" to return a bool instead of (otherwise) a string.
Edit: Just used the function directly in the if. Needed some tricky paranthesis, but works now. Thanks for the hint that a (boolean) object can never be === to a static boolean primitive. Hell this forum is fast.

When you create a Boolean object, it's an object. A reference to it, regardless of the boolean primitive value it represents, will always test as truthy just like any other non-null object reference.
There's generally no point in constructing a Boolean instance like that:
var isSignInside = !!someCondition;
That'll give you a boolean primitive that reflects the truthy/falsy state of your condition.

if(new Boolean(false)) alert("hehe");
Actually, isSignedInside is not a boolean, but a boolean object (thanks to the new). You may want to get its primitive value for comparison:
if( (new Boolean(false)).valueOf() ) alert("hehe");
Or even easier, take the value directly.

Well that's not how that's done. You want to use a boolean primitive. What you're trying to do is done this way:
var isSignInside = (someCondition);
if (isSignInside === false) {
//doStuff
}
else {
//doOtherStuff
}
https://jsfiddle.net/catbadger/pxrteq59/

Related

Is it necessary to use double exclamation points (!!) in order to make sure that an object is not null? [duplicate]

This question already has answers here:
When to use the double not (!!) operator in JavaScript
(2 answers)
Closed 6 years ago.
I've recently started using double exclamation points !! before an object to make sure that it's not null and that it's not undefined and not an empty string, to make sure that I encompass all the different ways that a variable can be empty.
Is this necessary? It's hard to read, for instance:
if(!!name) vs if(name)
Any opinions on this? I want my code to be safe and not get into conditions where a null pointer exception and other things can occur, but I also want my code to be readable.
What you're doing is already done by JavaScript natively.
if( value ) {
}
will evaluate to true as long as value is not:
null
undefined
NaN
empty string ("")
0
false
Check out the toboolean conversions in the specification.
No, there's no need at all for the double-bang if you're using the variable as the condition in an if. Simply if (name) is sufficient to ensure that name is not a falsy value. All object references are truthy; null is falsy.
This is completely unnecessary unless you need a strict comparison to boolean true, for example:
switch (true) {
case foo:
Should be
switch (true) {
case !!foo:
Or alternatively, the verbose but more readable Boolean(foo) (don't use new with the primitive constructors). Note that opposite is not true, if you are testing for falsey values then it becomes a problem because 0, NaN and the empty string, which may be valid values, are falsey:
if (!foo) { // foo had better not be empty string or zero
However, JavaScript offers you an out here (that some frown on) involving loose equality, null and undefined are loosely equivalent to each other but not to any other falsey values:
null == undefined //true
null == NaN // false
undefined == '' // false
Totally and completely ... pointless, to use a small pun.
The if() autmotically converts the conditional value to a boolean.
The !! converts it a boolean as well.
Where !! is sometimes used is to force something to a boolean value..
Such as:
var hasElement == !!document.getElementById("zz");

Why would you use !! in an expression in this case? angularjs api [duplicate]

This question already has answers here:
What is the !! (not not) operator in JavaScript?
(42 answers)
Closed 8 years ago.
Recently - learning and working with angularjs api. Looked at the source code for angular.isElement(). I understand foundationally what "!!" does to the return value of the expression when using it, but not understanding why use it - is it not redundant? Searched for !! not much info. Link to api page.
function isElement(node) {
return !!(node &&
(node.nodeName // we are a direct element
|| (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
}
Update: regarding being marked as a duplicate — Thx. Weird that i did not see that question on original search.
Though many long answers- reading them - they don't really answer where I am confused. Is it not redundant in this case? Wouldn't it return true without !!. thx
!! is used to convert a "truthy" or "falsey" value into true or false, and is equivalent to Boolean(). For example
!!0 // false
!!1 // true
function Obj() {}
o = new Obj()
!!o // true
!!'' // false
!!'hi' // true
(1 && 3 && 4) // 4
!!(1 && 3 && 4) // true
!!x can be read out loud as 'not not x'. The first ! turns a truthy value to false and a falsey value to true. Then the second ! reverses this so that the truthy value becomes true and the falsey value becomes false.
As to why people use that rather than Boolean, this appears to be just a convention. It is concise and easily understood by most programmers, and there is possibly some resemblance to how people do things in C or C++. It is not particularly faster.
EDIT. You want to know why it is not redundant in this particular case. We may have no idea what type of object is being passed to the function as node. && in javascript works from left to right and if all of the operands are truthy, returns the right-most operand, rather than true or false. Try redefining isElement without the !!. We get the following responses:
isElement('hi') // undefined
isElement(0) // 0
isElement(3) // undefined
isElement({nodeName: 'something'}) // 'something'
isElement({prop: 100, attr: this, find: Infinity}) // Infinity
These results will in fact be handled well most of the time -- in any if statement the truthy values ('something', Infinity) will be treated as true and the falsey values (undefined, 0) treated as false. But still, the user of the API will expect it to return only true or false and there will occasionally be unexpected behaviours if it is allowed to return any of these things.
!!var === Boolean(var). This was not always true, but it is for modern interpreters. In the old interpreters, Boolean(var) always returned true, because it is an object, so people used !! to get the equivalent value.
...and of course it is shorter
It converts the value to a boolean. !! isn't an operator itself. It is just the negation operator ! twice.
The && operator does not always return a Boolean. It actually returns either false or the second value.
That's why !! is used to force it to be a Boolean, because the APIA is apparently supposed to return one.

Augmenting the Object class

I was fooling around with the idea of adding a method onto the Object class like so:
Object.prototype.is = function(operand) {
return this === operand;
};
10.is(10); // returns false
I'm a little vexed by the outcome, can anyone offer some insight?
In JavaScript, numeric primitives are not instances of Number. When the compiler sees 10.is it wraps 10 in a Number object (since only objects can have properties). That object is not equal to the argument 10 because === suppresses automatic type conversion.
P.S. You need something like (10).is(10) for your code to be legal syntax.

Why is it good practice to use if (myBoolean === true) in JavaScript? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
As a follow-up to this question: Is there ever a reason to write "if (myBoolean == true)" in a JavaScript conditional? -
Why is it good practice to use if (myBoolean === true) in JavaScript? As a relatively inexperienced JavaScript user, I'm trying to work out in what specific, real-world scenarios you'd end up with a value that might be a Boolean true or might be a "truthy" value, so that you would need to check if (myBoolean === true) rather than if (myBoolean)
I'll challenge the premise of the question: I don't think it's good practice, nor do I think there's a general consensus that it is. :-)
The only reason for using === true would be if you weren't sure that myBoolean was actually a boolean and you wanted the result to be false if it weren't. There are use cases for that, but they're quite limited. 99.9% of the time, simply if (myBoolean) suffices, even though it will be true for 1, "foo", and other truthy values.
There are times when using strict equality for other reasons is quite a good idea, because JavaScript's rules for loose equality if the operands are of different types are quite complex. But if you're using something as a flag, there's little if any point to using === on it.
One particular place where I've seen === used with boolean values is in code inspired by jQuery, where a callback function can cancel an action by returning false, but doesn't have to return anything. When a function has no explicit return value, the result of calling that function is undefined, which is, of course, falsey. So code that wants to check whether the function returned false, not just undefined, would do this:
if (callback(args) === false) {
// The callback explicitly returned false (not just a falsey value), cancel
// ...
}
But that's a relatively infrequent use case, and of course it involves === false as opposed to === true...
Some random example:
function CreateSomeObject(param)
{
if (param == "1")
{
return new Stuff();
}
return null;
}
var myBoolean = CreateSomeObject("1") || true;
if (myBoolean === true)
{
//doesn't execute
}
if (myBoolean)
{
//executes just fine
}
In case of null only , you want to do that , although I never used this because it feels like more verbose and long string. No problem using it or avoiding it.It is more of style you want to write the code.
I constructed a slightly convoluted answer and then realised that the main reason is in the falsy values rather than the truthy ones. Usually, a function returns one kind of thing, and there is only one falsy value (the empty string for a string function, or 0 for a numeric one, or whatever).
However, when you aren't sure if something is defined or not, it can be instructive:
waitForResponse(request, 5000);
if(!request.ResponseValue) {
alert('Server failed to respond');
}
vs
waitForResponse(request, 5000);
if(request.ResponseValue === 'false') {
alert('Server says no');
}
Although I'd argue that you should check for undefined rather than boolyness:
if(typeof request.ResponseValue === 'undefined') {
//...
}
Incidentally, typeof is fast, at least it was in Chrome last time I checked.
Personally, I don't like statements like it's good practice to x. IMO, it all depends on the context: if you want to check some object exists, if(objectX) will do just as if (objectX === undefined) or if (typeof objectX === 'undefined') and even if (typeof objectX == 'undefined').
The reason why some people, like Douglas Crockford, strongly advocate the use of value and type checking (===) is that falsy and truthy values can, in rare cases, produce unexpected results:
var falsy = '';
if (falsy)
{//only when falsy is truthy, but an empty string is falsy
console.log('could be seen as counter-intuitive: var was declared and assigned an empty string, but is falsy');
}
var obj = {falsy:''}
if (!obj.falsy)
{
console.log('I might assume falsy is not set, although it was:');
console.log(obj.hasOwnProperty('falsy'));//true
}
Again, this might just be my opinion, but in the vast majority of cases this won't break your code. I'd even go one step further: Douglas Crockford might claim that using checking for falsy values isn't a good idea, but he does like the logical OR (||) operator:
var falsy ='';
var someVar = falsy || 'default value';//this relies heavily on falsy values
The only "solid" arguments for strict comparison are:
if you need the variable to be a boolean, but then again falsy = !!falsy; coerces to a boolean all the same
strict comparisons are marginally faster, but you'll have to do a whole lot of comparisons before you'll be able to notice the difference
Having said that, I do tend to use strict comparisons an awful lot, again, it might be a personal thing, but I like to know what the actual type of a variable is:Given that '1' == 1 evaluates to true, but '1' === 1 is false, it at least allows you to coerce a var to the type you need:
var foo = '00001';
var elements = [foo = ('00000' + (+(foo)+1)).substr(-5)];
while(elements[+(foo)-1])
{
foo = ('00000' + (+(foo)+1)).substr(-5);
elements.push(foo = ('00000' + (+(foo)+1)).substr(-5));
}
Now this isn't what you'd call good code, but there's a lot of type-juggling going on. At the end of the ride, you might want to know what value was assigned to foo. That's not an issue in this snippet, but suppose you want to use the numeric value of foo inside the while loop, if it's an odd number:
var foo = '00001';
var elements = [foo = ('00000' + (+(foo)+1)).substr(-5)];
while(elements[+(foo)-1])
{
foo = ('00000' + (+(foo)+1)).substr(-5);
elements.push(foo = ('00000' + (+(foo)+1)).substr(-5));
if (+(foo)%2 === 1)
{
foo = +(foo);
//do stuff with foo
}
}
The easiest way to check weather or not foo is a string after the loop is completed is to check foo directly: if (foo === +(foo))
I am well aware that this example is a little far-fetched, but I have encountered a case quite similar to this one. It's at times like this where the advantages of strong-typed languages really show. speaking of which: new Date() >= someDateObject vs Date() >= someDateObject... try it in your console and you'll soon see what I'm on about.

Difference between if (var.length >0){} and if (var){}

In javascript is there a difference between using
if (foo.length > 0) {
//run code involving foo
}
and
if (foo) {
//run code involving foo
}
If so, could someone please explain the difference and an example where they would not be the same?
Here's an example where they are not the same:
var x = [];
alert(x? 'yes' : 'no'); // displays "yes"
alert((x.length > 0)? 'yes' : 'no'); // displays "no"
The two are completely different. I'm assuming by the use of .length that var is a jquery object, in which case if(var) will always be true. jQuery will always return an object, but it may be empty. if(var.length>0) checks that the jquery object actually contains an element.
The former tests if var.length returns more than 0. The latter tests if the value of var is true.
You cannot necessarily use either one for all variables. For a boolean, if(var) makes more sense. For a string or array, if(var.length) makes more sense.
they're obviously different, the question is really just why are they different.
your first example is explictly checking that the length property of an object is greater than 0. if that is true it evaluates the content of the if statement.
the second example can only tell you if the variable is 'truthy', or 'falsy' (or as the great stephen colbert coined it, 'truthiness'). check out the wikipedia article on javascript booleans for detail.

Categories

Resources