what can be the fastest code to have this check :
two strings are different only if they have different characters ?
so that
null == undefined == ''
now i use
if(!s1 && !!s2
||
!!s1 && !s2
||
!!s1 && !!s2 && s1 != s2
)
but does not cover all cases
(s1 || '') == (s2 || '')
|| will convert any falsey value to an empty string.
This will work as long as the variables are guaranteed to hold either a string, null, or undefined. If it can have a number, 0 will also be converted to an empty string, so 0 == '' would be true.
Numeric strings are strings, so this will still work for them.
Related
I have a if else function in javascript:
if(document.getElementById('lengthFront').value > 4 && document.getElementById('lengthFront').value < 296 && document.getElementById('lengthBack').value > 4 && document.getElementById('lengthBack').value < 296)
{
document.getElementById('param_length').classList.remove('bg-danger');
}
else
{
document.getElementById('param_length').className = "bg-danger";
}
Bu I need an extra check so it won't be executed when lengthFront or lengthBack is empty, I have tried different solutions but I can't find the right way to get it working. All my solutions are pointing to else
I have tried to add:
document.getElementById('lengthFront') == '' && document.getElementById('lengthBack') == '' &&......
document.getElementById('lengthFront') == false && document.getElementById('lengthBack') == false &&......
document.getElementById('lengthFront') == null && document.getElementById('lengthBack') == null &&......
document.getElementById('lengthFront') =!= undefined && document.getElementById('lengthBack') != undefined &&......
Any suggestions
if(document.getElementById('lengthFront') && document.getElementById('lengthFront').value != '')
First condition makes sure that the element exists, second one makes sure it's value is not empty.
For the most concise and readable approach to dealing with DOM elements that may or may not exist and that may not have a valid value if they do exist, might I suggest you leverage two friends: logical AND && which you can use as a faux null coalescing operator, and the 'conditional ternary' operator ?: in such a way that you can check for null and blank string, and then assign a default value (0) or the element value, all in the initial assignment statement. Also, you'll want to avoid multiple redundant getElementByXXX queries by simply assigning the result to a variable (better readability, less typing, performs faster):
var lengthFront = document.getElementById('lengthFront');
var lengthBack = document.getElementById('lengthBack');
var paramLength = document.getElementById('param_length');
lengthFront = (lengthFront && lengthFront.value != '') ? lengthFront .value : 0 ;
lengthBack = (lengthBack && lengthBack.value != '') ? lengthBack .value : 0 ;
if(lengthFront > 4 && lengthFront < 296 && lengthBack > 4 && lengthBack < 296) {
paramLength && paramLength.classList.remove('bg-danger')
} else {
paramLength && (paramLength.className = "bg-danger");
}
I am working understanding a JavaScript library and I came across this statement:
const assetsManifest = process.env.webpackAssets && JSON.parse(process.env.webpackAssets)
Then later on in the library, it uses the assetsMannifest like an object e.g.
assetsManifest['/vendor.js']
I thought the && operator was only used to return boolean values in logical checks. Can someone explain to me what is going on here?
Many thanks,
Clement
This operator doesn't always return true or false. It doesn't work like in some other programming languages. In JavaScript && operator returns the first value if it's falsy or the second one if not.
Examples:
null && 5 returns null because null is falsy.
"yeah yeah" && 0 returns 0 because every string is truthy.
Not so obvious :-)
Further reading:
Why don't logical operators (&& and ||) always return a boolean result?
&& returns first value converting to false or last value converting to true. It's because no need to calculate full logical condition with && if first value is falsy
console.log(55 && 66);
console.log(0 && 77);
console.log(88 && 0);
Also you can use && or || as if operator:
if (itsSunny) takeSunglasses();
equals to
itsSunny && takeSunglasses();
in that context it is checking if process.env.webpackAssets is a truthy value. If it is it will evaluate and return the next part. in this case JSON.parse(process.env.webpackAssets)
The logic is essentially
if (process.env.webpackAssets) {
return JSON.parse(process.env.webpackAssets)
}
else {
return process.env.webpackAssets // (null | undefined | 0 | '' | false)
}
Both && and || are evaluting there arguments in lazy mode and return the last value, after witch the result is known.
123 && (0 || '' && 78) || 7 && 8 || [] && {} || 90 || 77 && 13
###_^^ both results are possible 123 && ???
#_^^ first part is falsy, resume 0 || ??
#####_^^ can't be true, return ''
^^_########## 0 || '' return ''
^^_################ return ''
#######################_^^ resume
#_^^ resume
^^_# return 8
^^_###### return 8
^^_########################## drop
And the result is 8.
json= new Gson().toJson(name);
where name is of type string.
I am getting error saying "TypeError: invalid 'in' operand obj "
error is in the given part of java script
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
I have also tried
response=JSON.parse(response);
which is not working.
by link In operator you can see that
The in operator returns true if the specified property is in the specified object.
in your code ( length - 1 ) in obj you try checking that property (length - 1) that numeric in your obj
I think obj is a string, so it has the length property, but does not have numeric properties, so you must catch this case
I closed the code "( length - 1 ) in obj" between parentheses.
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && (( length - 1 ) in obj) );
That's working fine for me.
In my case the object was not empty but I needed to add double quotes on the object's key , example :
obj = {params : "paramsInputPreData"}
The Above will produce an error but the one below was okay :
obj = {"params" : "paramsInputPreData"}
so for me the key needed to be quoted as "params"
Hope it helps someone
When you have this error, you need to check the type of your variables, etc., you can always do something like this:
if (typeof x == 'string' || typeof x == 'number') { ... }
If I have a variable x = ""
And I check for the following condition
if x != 0
Is it evaluated as false across all the browsers ?
Why is 0 treated the same as "" ?
When you use the == operator JavaScript attempts to convert both operands to the same type for comparison. When you have a string and a number it attempts to convert the string to a number. "" converts to 0, giving you this result.
Because of this behaviour many people chose to use the === and !== operators instead. Their operands must be the same type to be considered equal.
Because both 0 and '' are evaluated like this:
0 == false //true
'' == false //true
Use === to check properly
Is "" that when casted is egual to 0:
"" != 0 -> string != int -> (int)string != int -> int != int
I want to try to do string call equivalent to the C# String.IsNullOrEmpty(string) in javascript. I looked online assuming that there was a simple call to make, but I could not find one.
For now I am using a if(string === "" || string === null) statement to cover it, but I would rather use a predefined method (I keep getting some instances that slip by for some reason)
What is the closest javascript (or jquery if then have one) call that would be equal?
You're overthinking. Null and empty string are both falsey values in JavaScript.
if(!theString) {
alert("the string is null or empty");
}
Falsey:
false
null
undefined
The empty string ''
The number 0
The number NaN
If, for whatever reason, you wanted to test only null and empty, you could do:
function isNullOrEmpty( s )
{
return ( s == null || s === "" );
}
Note: This will also catch undefined as #Raynos mentioned in the comments.
if (!string) {
// is emtpy
}
What is the best way to test for an empty string with jquery-out-of-the-box?
If you know that string is not numeric, this will work:
if (!string) {
.
.
.
You can create one Utility method which can be reused in many places such as:
function isNullOrEmpty(str){
var returnValue = false;
if ( !str
|| str == null
|| str === 'null'
|| str === ''
|| str === '{}'
|| str === 'undefined'
|| str.length === 0 ) {
returnValue = true;
}
return returnValue;
}
you can just do
if(!string)
{
//...
}
This will check string for undefined, null, and empty string.
To be clear, if(!theString){//...} where theString is an undeclared variable will throw an undefined error, not find it true. On the other hand if you have: if(!window.theString){//...} or var theString; if(!theString){//...} it will work as expected. In the case where a variable may not be declared (as opposed to being a property or simply not set), you need to use: if(typeof theString === 'undefined'){//...}
My preference is to create a prototype function that wraps it up for you.
Since the answer that is marked as correct contains a small error, here is my best try at coming up with a solution. I have two options, one that takes a string, the other takes a string or a number, since I assume many people are mixing strings and numbers in javascript.
Steps:
-If the object is null it is a null or empty string.
-If the type is not string (or number) it's string value is null or empty. NOTE: we might throw an exception here as well, depending on preferences.
-If the trimmed string value has a length that is small than 1 it is null or empty.
var stringIsNullOrEmpty = function(theString)
{
return theString == null || typeof theString != "string" || theString.trim().length < 1;
}
var stringableIsNullOrEmpty = function(theString)
{
if(theString == null) return true;
var type = typeof theString;
if(type != "string" && type != "number") return true;
return theString.toString().trim().length < 1;
}
you can say it by logic
Let say you have a variable name a strVal, to check if is null or empty
if (typeof (strVal) == 'string' && strVal.length > 0)
{
// is has a value and it is not null :)
}
else
{
//it is null or empty :(
}