is there any function like string.isnullorempty() in javascript - javascript

I always (thing != undefined || thing != null)?...:...; check. Is there any method will return bool after this check in javascript or jquery ?
And how would you add this check in jquery as a function?

if (thing)
{
//your code
}
Is that what you are looking for?

In Javascript, the values null, undefined, "", 0, NaN, and false are all "falsy" and will fail a conditional.
All other values are "truthy" and will pass a conditional.
Therefore, you can simply write thing ? ... : ....

Try this
function SringisEmpty(str) {
str=str.trim();
return (!str || 0 === str.length);
}

As the others here have mentioned, several things evaluate as "falsy" that you might not want to (such as empty strings or zero). The simplest way I've found in JavaScript to check for both null and undefined in one statement is:
thing != null
This is using type coercion (double equals instead of triple equals), so undefined values are coerced to null here, while empty strings, zero, etc. do not.

Related

is there a short way to write ? value !== null

I have value !== null
I need to get false in null case but 0 is true.
is there a short way to write?
!!value or Boolean(value) not works for me.
You can use != instead of !== if you also want to return false for the input undefined. And you can omit the spaces around the operator:
value!=null
Short of a helper function isNull(…), it won't get any shorter. There is no special "null test" unary operator, if that is what you were looking for.

How does logical expressions work in JavaScript?

This seems to be a common issue, but I didn't find anything that would help me understand.
I have a bunch of items with introduced member of type bool. Some items have introduced value of true, some of false. So coming from c++ I don't expect this to return 'false' (item.introduced is boolean)
if ((show_introduced == "false") && (item.introduced)) {console.log(item.introduced)};
but I acctually see 'false' an well as 'true'.
For me it is the same as, which, of course, never output anything.
var a = false;
if (true && a) {console.log(a)};
Does && works differently in js, or I should find the problem somewhere in the rest of the code?
EDITED: Because item.introduced was read from JSON, it was actually a string, so that's the reason why it didn't work.
'false' in quotes makes it a string, which is true. So, "false" != false
write it like
(show_introduced === false)
EDIT:
Falsy values in Javascript:
false (boolean)
"" (an empty string)
0 (zero)
null
undefined
NaN
if you get anything from above, they are falsy value, and everything else if truthy.
Don't attempt to compare boolean values with true or false, just use them as booleans
if ( showIntroduced )
or
if ( ! showIntroduced )
Logical operators such as && and || in JavaScript behave as you would expect from C/C++, with the same short-circuit rules.

boolean in an if statement

Today I've gotten a remark about code considering the way I check whether a variable is true or false in a school assignment.
The code which I had written was something like this:
var booleanValue = true;
function someFunction(){
if(booleanValue === true){
return "something";
}
}
They said it was better/neater to write it like this:
var booleanValue = true;
function someFunction(){
if(booleanValue){
return "something";
}
}
The remark which I have gotten about the "=== true" part was that it was not needed and could create confusion.
However my idea is that it is better to check whether the variable is a boolean or not, especially since Javascript is a loosetyped language.
In the second example a string would also return "something";
So my question; Is it neater to loose the "=== true" part in the future, or is it good practise to check the type of the variable as well.
Edit:
In my "real" code the boolean represents whether an image has been deleted or not, so the only values boolValue should ever have is true or false.
0 and 1 for example shouldn't be in that variable.
First off, the facts:
if (booleanValue)
Will satisfy the if statement for any truthy value of booleanValue including true, any non-zero number, any non-empty string value, any object or array reference, etc...
On the other hand:
if (booleanValue === true)
This will only satisfy the if condition if booleanValue is exactly equal to true. No other truthy value will satisfy it.
On the other hand if you do this:
if (someVar == true)
Then, what Javascript will do is type coerce true to match the type of someVar and then compare the two variables. There are lots of situations where this is likely not what one would intend. Because of this, in most cases you want to avoid == because there's a fairly long set of rules on how Javascript will type coerce two things to be the same type and unless you understand all those rules and can anticipate everything that the JS interpreter might do when given two different types (which most JS developers cannot), you probably want to avoid == entirely.
As an example of how confusing it can be:
var x;
x = 0;
console.log(x == true); // false, as expected
console.log(x == false); // true as expected
x = 1;
console.log(x == true); // true, as expected
console.log(x == false); // false as expected
x = 2;
console.log(x == true); // false, ??
console.log(x == false); // false
For the value 2, you would think that 2 is a truthy value so it would compare favorably to true, but that isn't how the type coercion works. It is converting the right hand value to match the type of the left hand value so its converting true to the number 1 so it's comparing 2 == 1 which is certainly not what you likely intended.
So, buyer beware. It's likely best to avoid == in nearly all cases unless you explicitly know the types you will be comparing and know how all the possible types coercion algorithms work.
So, it really depends upon the expected values for booleanValue and how you want the code to work. If you know in advance that it's only ever going to have a true or false value, then comparing it explicitly with
if (booleanValue === true)
is just extra code and unnecessary and
if (booleanValue)
is more compact and arguably cleaner/better.
If, on the other hand, you don't know what booleanValue might be and you want to test if it is truly set to true with no other automatic type conversions allowed, then
if (booleanValue === true)
is not only a good idea, but required.
For example, if you look at the implementation of .on() in jQuery, it has an optional return value. If the callback returns false, then jQuery will automatically stop propagation of the event. In this specific case, since jQuery wants to ONLY stop propagation if false was returned, they check the return value explicity for === false because they don't want undefined or 0 or "" or anything else that will automatically type-convert to false to also satisfy the comparison.
For example, here's the jQuery event handling callback code:
ret = ( specialHandle || handleObj.handler ).apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
You can see that jQuery is explicitly looking for ret === false.
But, there are also many other places in the jQuery code where a simpler check is appropriate given the desire of the code. For example:
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
...
If you write: if(x === true) , It will be true for only x = true
If you write: if(x) , it will be true for any x that is not: '' (empty string), false, null, undefined, 0, NaN.
In general, it is cleaner and simpler to omit the === true.
However, in Javascript, those statements are different.
if (booleanValue) will execute if booleanValue is truthy – anything other than 0, false, '', NaN, null, and undefined.
if (booleanValue === true) will only execute if booleanValue is precisely equal to true.
In the plain "if" the variable will be coerced to a Boolean and it uses toBoolean on the object:-
Argument Type Result
Undefined false
Null false
Boolean The result equals the input argument (no conversion).
Number The result is false if the argument is +0, −0, or NaN;
otherwise the result is true.
String The result is false if the argument is the empty
String (its length is zero); otherwise the result is true.
Object true.
But comparison with === does not have any type coercion, so they must be equal without coercion.
If you are saying that the object may not even be a Boolean then you may have to consider more than just true/false.
if(x===true){
...
} else if(x===false){
....
} else {
....
}
It depends on your usecase. It may make sense to check the type too, but if it's just a flag, it does not.
If the variable can only ever take on boolean values, then it's reasonable to use the shorter syntax.
If it can potentially be assigned other types, and you need to distinguish true from 1 or "foo", then you must use === true.
The identity (===) operator behaves identically to the equality (==) operator except no type conversion is done, and the types must be the same to be considered equal.
Since the checked value is Boolean it's preferred to use it directly for less coding and at all it did same ==true
Since you already initialized clearly as bool, I think === operator is not required.
I think that your reasoning is sound. But in practice I have found that it is far more common to omit the === comparison. I think that there are three reasons for that:
It does not usually add to the meaning of the expression - that's in cases where the value is known to be boolean anyway.
Because there is a great deal of type-uncertainty in JavaScript, forcing a type check tends to bite you when you get an unexpected undefined or null value. Often you just want your test to fail in such cases. (Though I try to balance this view with the "fail fast" motto).
JavaScript programmers like to play fast-and-loose with types - especially in boolean expressions - because we can.
Consider this example:
var someString = getInput();
var normalized = someString && trim(someString);
// trim() removes leading and trailing whitespace
if (normalized) {
submitInput(normalized);
}
I think that this kind of code is not uncommon. It handles cases where getInput() returns undefined, null, or an empty string. Due to the two boolean evaluations submitInput() is only called if the given input is a string that contains non-whitespace characters.
In JavaScript && returns its first argument if it is falsy or its second argument if the first argument is truthy; so normalized will be undefined if someString was undefined and so forth. That means that none of the inputs to the boolean expressions above are actually boolean values.
I know that a lot of programmers who are accustomed to strong type-checking cringe when seeing code like this. But note applying strong typing would likely require explicit checks for null or undefined values, which would clutter up the code. In JavaScript that is not needed.
In Javascript the idea of boolean is fairly ambiguous. Consider this:
var bool = 0
if(bool){..} //evaluates to false
if(//uninitialized var) //evaluates to false
So when you're using an if statement, (or any other control statement), one does not have to use a "boolean" type var. Therefore, in my opinion, the "=== true" part of your statement is unnecessary if you know it is a boolean, but absolutely necessary if your value is an ambiguous "truthy" var. More on booleans in javscript can be found here.
Also can be tested with Boolean object, if you need to test an object
error={Boolean(errors.email)}
This depends. If you are concerned that your variable could end up as something that resolves to TRUE. Then hard checking is a must. Otherwise it is up to you. However, I doubt that the syntax whatever == TRUE would ever confuse anyone who knew what they were doing.
Revisa https://www.w3schools.com/js/js_comparisons.asp
example:
var p=5;
p==5 ? true
p=="5" ? true
p==="5" ? false
=== means same type also same value
== just same value

Reference and datatype checking, are these the same?

I have a simple function in my library that checks the validity of an object reference (object here meaning, a reference to a created HTML element, mostly DIV's). It looks like this:
function varIsValidRef(aRef) {
return ( !(aRef == null || aRef == undefined) && typeof(aRef) == "object");
}
While experimenting i found that this has the same effect:
function varIsValidRef(aRef) {
return (aRef) && typeof(aRef) == "object";
}
I understand there are some controversies regarding the short hand () test? While testing against various datatypes (null, undefined, integer, float, string, array) i could find no difference in the final outcome. The function seem to work as expected.
Is it safe to say that these two versions does the exact same thing?
No, in my opinion these functions don't work the same:
First option
If aRef is not undefined or null and the type of the var is object it returns true.
Second option
First we convert aRef to a boolean. Values like null, undefined and 0 become false, everything else become true. If it is true (so not one of those values) it checks if the type is object.
So the second option return false if aRef is 0, something you don't want. And it isn't option a elegant way to check it, because you check if an object or string or something is equal to a boolean.
And at least they don't return the same thing. The first option returns a boolean, but the second option returns the value you put in the function if (aRef) is false:
varIsValidRef(0);
>>> 0
varIsValidRef('');
>>> ""
varIsValidRef(undefined);
>>> undefined
varIsValidref(null);
>>> null
Because JavaScript use these values as falsy values you don't see the difference between these return values if you use if statements or something like that.
So I suggest you to use the first option.
they are strongly different:
!(aRef == null || aRef == undefined)
this part is evaluated to false with any of these "null", null, "undefined", undefined
(aRef)
while this other with any of these 0, "", false, null, undefined, NaN
Interesting case, but it seems logical for both to behave the same way despite being totally different. Lets see the first staement.
return ( !(aRef == null || aRef == undefined) && typeof(aRef) == "object");
Here,
null and undefined both denote a false state combined with the ! infront, makes it equal to the expression aRef which will return true in case both are either not null or not undefined.
They don't do the same, though they end up with the same results.
The first function is more strict in what it will count as false together, or if it's not, if its an object.
The second function will check if aRef is !false or not any of the falsy values (ie [], null, undefined) and check if the type is an object if it isn't.
I would prefer the first function, since its stricter in what it accepts, but if its all the same the function which performs the best should be used.
As for the controversy, its true that you have to be careful about how/when you use falsy values in equations but if it does what you want it to do (and for that you'll need to know what falsy values are) and you implement it correctly it should be no problem. The two are hard to put together though. So with that, if this does what you want it to do, and nothing more or less, by all means use it.

Check for false

Is there any better way of doing this?
if(borrar() !== false)
{
alert('tatatata bum bum bum prapra');
}
return false;
If you want to check for false and alert if not, then no there isn't.
If you use if(val), then anything that evaluates to 'truthy', like a non-empty string, will also pass. So it depends on how stringent your criterion is. Using === and !== is generally considered good practice, to avoid accidentally matching truthy or falsy conditions via JavaScript's implicit boolean tests.
If you want an explicit check against false (and not undefined, null and others which I assume as you are using !== instead of !=) then yes, you have to use that.
Also, this is the same in a slightly smaller footprint:
if(borrar() !== !1)
You can use something simpler:
if(!var){
console.log('var is false');
}
If you want it to check explicit for it to not be false (boolean value) you have to use
if(borrar() !== false)
But in JavaScript we usually use falsy and truthy and you could use
if(!borrar())
but then values 0, '', null, undefined, null and NaN would not generate the alert.
The following values are always falsy:
false,
,0 (zero)
,'' or "" (empty string)
,null
,undefined
,NaN
Everything else is truthy. That includes:
'0' (a string containing a single zero)
,'false' (a string containing the text “false”)
,[] (an empty array)
,{} (an empty object)
,function(){} (an “empty” function)
Source: https://www.sitepoint.com/javascript-truthy-falsy/
As an extra perk to convert any value to true or false (boolean type), use double exclamation mark:
!![] === true
!!'false' === true
!!false === false
!!undefined === false
Checking if something isn't false... So it's true, just if you're doing something that is quantum physics.
if(!(borrar() === false))
or
if(borrar() === true)
Like this:
if(borrar())
{
// Do something
}
If borrar() returns true then do something (if it is not false).

Categories

Resources