TypeError: invalid 'in' operand obj - javascript

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') { ... }

Related

How to compare string in javascript so that empty equals null

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.

Javascript - How to convert string '0' to number 0

I'm trying to do error handling on 2 input values. I'm using regex to confirm that the input is always a number. The issue I'm having is that I don't want my error handling to kick in if the user literally inputs 0. Right now I'm using:
number = parseInt(incomingValue) || ""
to set my variable. The issue is that this turns '0' into ""
Its fine if an empty value becomes an empty string because I am disabling my error checking when the lengths are equal to 0, but I need to properly turn '0' into a number 0. Anyone have any ideas?
Additionally, I'd also like to turn '000' (and so forth) into a number 0
You can turn '0' or '000' into a number by just doing:
parseInt('0'); // 0
parseInt('000'); // 0
The reason your code is not working is that javascript treats 0 as a falsly value, so when you do this:
const number = parseInt('0') || ""
the expression parseInt('0') will return 0 which is falsy. As a result, the || "" will be executed which will set number to "". You'll need to separate your parseInt and your default assignment to achieve what you want.
Use "Number()":
console.log(Number('0'));
console.log(Number('000'));
console.log(typeof(Number('0')));
console.log(typeof(Number('000')));
Or put "+" before '0' and '000':
console.log(+'0');
console.log(+'000');
console.log(typeof(+'0'));
console.log(typeof(+'000'));
Or put "* 1" before or after '0' and '000':
console.log('0' * 1);
console.log('000' * 1);
console.log(typeof('0' * 1));
console.log(typeof('000' * 1));
You can use parseInt(incomingValue) to get the int value.
For comparing you can use === for equal value and equal type means (incomingValue === 0) will be true in case of incomingValue = 0.
You can try typeof to distinguish what type of variable you are receiving
typeof true === 'boolean'
typeof null === 'object'
typeof 62 === 'number'
typeof 'Hello World' === 'string'

Why does JavaScript preferentially coerce to strings when concatenating but numbers when comparing?

Why does JavaScript preferentially coerce operands to strings when using the concatenate + operator but preferentially coerce operands to numbers when performing == equality checks?
'1' + 1 is coerced to '1' + '1' and returns '11'.
'1' == 1 is coerced to 1 === 1 and returns true.
In the comparison case they are coerced to numbers, and not strings. See sources below:
1) Douglas Crockford's Encyclopedia
The == operator produces the same result as this function:
function coercing_equal(left, right) {
if (left === right) {
return true ;
}
if (left === null) {
return right === undefined;
}
if (right === null) {
return left === undefined;
}
if (typeof left === 'number' && typeof right === 'string') {
return left === +right;
}
if (typeof left === 'string' && typeof right === 'number') {
return +left === right;
}
if (typeof left === 'boolean') {
return coercing_equal(+left, right);
}
if (typeof right === 'boolean') {
return coercing_equal(left, +right);
}
if
(typeof left === 'object' &&
(
left.constructor === Number ||
left.constructor === String ||
left.constructor === Boolean
) &&
(typeof right === 'string' || typeof right === 'number')
) {
return coercing_equal(left.valueOf(), right);
}
if (
(typeof left === 'string' || typeof left === 'number') &&
typeof right === 'object' &&
(
right.constructor === Number ||
right.constructor === String ||
right.constructor === Boolean
)
) {
return coercing_equal(left, right.valueOf());
}
return false ;
}
2) MDN
When type conversion is involved in the comparison (i.e., non–strict comparison), JavaScript converts the types String, Number, Boolean, or Object operands as follows:
When comparing a number and a string, the string is converted to a number value. JavaScript attempts to convert the string numeric literal to a Number type value. First, a mathematical value is derived from the string numeric literal. Next, this value is rounded to nearest Number type value.
If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.
If an object is compared with a number or string, JavaScript attempts to return the default value for the object. Operators attempt to convert the object to a primitive value, a String or Number value, using the valueOf and toString methods of the objects. If this attempt to convert the object fails, a runtime error is generated.
Note that an object is converted into a primitive if, and only if, its comparand is a primitive. If both operands are objects, they're compared as objects, and the equality test is true only if both refer the same object.
Is there any rhyme of reason to this or is it just another case of 'because JavaScript'? It is tough to remember as far as my understanding currently takes me.
why do you expect there is a one reason?
I believe there could be different aspects possible:
HTML data is not typed - it's all strings. The same is for HTTP. So there will be probably a lot of conversion required if you try to
element.getAttribute('maxlength')> str.length
So we better just deal with that fact string/number mix is not rear case(at least when EcmaScript started to be used)
trying to have the same approach for both "+" and ">" operators would generate more "WTF?". Say if we try to use "toString approach everywhere" then 2> '11'. On the other side for "toNumber approach everywhere" we would see NaN in string concatenation result much more often that we would want.
Yes, it looks confusing. But it's more because of ambiguous goal of "+" as operator "add" and operation "concatenate" in the same time. Then you should used to operate this automatically.

C# String.IsNullOrEmpty Javascript equivalent

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 :(
}

JavaScript equality transitivity is weird

I've been reading Douglas Crockford's JavaScript: The Good Parts, and I came across this weird example that doesn't make sense to me:
'' == '0' // false
0 == '' // true
0 == '0' // true
false == undefined // false
false == null // false
null == undefined // true
The author also goes on to mention "to never use == and !=. Instead, always use === and !==". However, he doesn't explain why the above behavior is exhibited? So my question is, why are the above results as they are? Isn't transitivity considered in JavaScript?
'' == '0' // false
The left hand side is an empty string, and the right hand side is a string with one character. They are false because it is making a comparison between two un identical strings (thanks Niall).
0 == '' // true
Hence, why this one is true, because 0 is falsy and the empty string is falsy.
0 == '0' // true
This one is a bit trickier. The spec states that if the operands are a string and a number, then coerce the string to number. '0' becomes 0. Thanks smfoote.
false == undefined // false
The value undefined is special in JavaScript and is not equal to anything else except null. However, it is falsy.
false == null // false
Again, null is special. It is only equal to undefined. It is also falsy.
null == undefined // true
null and undefined are similar, but not the same. null means nothing, whilst undefined is the value for a variable not set or not existing. It would kind of make sense that their values would be considered equal.
If you want to be really confused, check this...
'\n\r\t' == 0
A string consisting only of whitespace is considered equal to 0.
Douglas Crockford makes a lot of recommendations, but you don't have to take them as gospel. :)
T.J. Crowder makes an excellent suggestion of studying the ECMAScript Language Specification to know the whole story behind these equality tests.
Further Reading?
The spec.
yolpo (on falsy values)
The answer to this question has to do with how JavaScript handles coercion. In the case of ==, strings are coerced to be numbers. Therefore:
'' == '0' is equivalent to '' === '0' (both are strings, so no coercion is necessary).
0 == '' is equivalent to 0 === 0 because the string '' becomes the number 0 (math.abs('') === 0).
0 == '0' is equivalent to 0 === 0 for the same reason.
false == undefined is equivalent to 0 === undefined because JavaScript coerces booleans to be numbers when types don't match
false == null is equivalent to 0 === null for the same reason.
null == undefined is true because the spec says so.
Thanks for asking this question. My understanding of == is much better for having researched it.
You can actually write a JavaScript function that behaves exactly like == that should give you some insight into how it behaves.
To show you what I mean here is that function:
// loseEqual() behaves just like `==`
function loseEqual(x, y) {
// notice the function only uses "strict" operators
// like `===` and `!==` to do comparisons
if(typeof y === typeof x) return y === x;
if(typeof y === "function" || typeof x === "function") return false;
// treat null and undefined the same
var xIsNothing = (y === undefined) || (y === null);
var yIsNothing = (x === undefined) || (x === null);
if(xIsNothing || yIsNothing) return (xIsNothing && yIsNothing);
if(typeof x === "object") x = toPrimitive(x);
if(typeof y === "object") y = toPrimitive(y);
if(typeof y === typeof x) return y === x;
// convert x and y into numbers if they are not already use the "+" trick
if(typeof x !== "number") x = +x;
if(typeof y !== "number") y = +y;
return x === y;
}
function toPrimitive(obj) {
var value = obj.valueOf();
if(obj !== value) return value;
return obj.toString();
}
As you can see == has a lot of complicated logic for type conversion. Because of that it's hard to predict what result you are going to get.
Here are some examples of some results you wouldn't expect:
Unexpected Truths
[1] == true // returns true
'0' == false // returns true
[] == false // returns true
[[]] == false // returns true
[0] == false // returns true
'\r\n\t' == 0 // returns true
Unexpected Conclusions
// IF an empty string '' is equal to the number zero (0)
'' == 0 // return true
// AND the string zero '0' is equal to the number zero (0)
'0' == 0 // return true
// THEN an empty string must be equal to the string zero '0'
'' == '0' // returns **FALSE**
Objects with Special Functions
// Below are examples of objects that
// implement `valueOf()` and `toString()`
var objTest = {
toString: function() {
return "test";
}
};
var obj100 = {
valueOf: function() {
return 100;
}
};
var objTest100 = {
toString: function() {
return "test";
},
valueOf: function() {
return 100;
}
};
objTest == "test" // returns true
obj100 == 100 // returns true
objTest100 == 100 // returns true
objTest100 == "test" // returns **FALSE**

Categories

Resources