Why does ('0' ? 'a' : 'b') behave different than ('0' == true ? 'a' : 'b')
First, for completeness:
('0' ? 'a' : 'b')
is 'a'
, because '0'
is a non-empty string, which always evaluates to true
:String: The result is false if the argument is the empty String (its length is zero);
otherwise the result is true.
Now to
'0' == true
.Two type conversions will take place here. We can follow this in the specification, section 11.9.3, The Abstract Equality Comparison Algorithm.
The operands are denoted as x
and y
(x == y
).
In our case, x
is a string ('0'
) and y
is a Boolean (true
). Hence step 7 is executed:
When booleans are converted to numbers, the following conversion takes place:If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
Now we haveBoolean: The result is 1 if the argument is true. The result is +0 if the argument is false.
'0' == 1
which matches the condition in step 5:How strings are converted to numbers is more complex but of course can also be found in the specification.If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
So the final comparison is
0 == 1
which is false
(step 1. a. vi.) In JavaScript, why is 0 equal to false, but when tested by 'if' it is not false by itself?
The reason is because when you explicitly do "0" == false
, both sides are being converted to numbers, and then the comparison is performed.
When you do: if ("0") console.log("ha")
, the string value is being tested. Any non-empty string is true
, while an empty string is false
.
Equal (==)
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.
(From Comparison Operators in Mozilla Developer Network)
Why == 0 is false in javascript?
Because the operands are two strings with different content. Type coercion only takes place if the data types of the operands are different.Why “” == “0” is false in javascript?
Related questions:
- Why does ('0' ? 'a' : 'b') behave different than ('0' == true ? 'a' : 'b')
- '\n\t\r' == 0 is true?
Lets have a look how the comparisons are actually resolved:If
""
evaluates to false and"0"
evaluates tofalse
the logic predicts that it is the same as i writefalse == false
"" == false
is coerced to 0 == 0
"0" == false
is coerced to 0 == 0
false == false
: same data type, hence the values are directly compared
As you can see "0"
doesn't "evaluate" to false
, it is converted to an integer, and that value is compared. (""
does evaluate to false
(empty string) but when converted to a number, it is 0
).
There is a big difference between converting a value to a boolean and comparing a value to a boolean. Most obvious example: !!"0"
(true
) and "0" == false
(true
).
When you compare values of different datatypes with loose comparison (==
), they are always coerced to numbers (or potentially strings, if you are comparing an object with a string).
Have a look at the specification for more information about the comparison algorithm.
How are iloc and loc different?
Label vs. Location
The main distinction between the two methods is:
loc
gets rows (and/or columns) with particular labels.iloc
gets rows (and/or columns) at integer locations.
s
of characters with a non-monotonic integer index:>>> s = pd.Series(list("abcdef"), index=[49, 48, 47, 0, 1, 2])
49 a
48 b
47 c
0 d
1 e
2 f
>>> s.loc[0] # value at index label 0
'd'
>>> s.iloc[0] # value at index location 0
'a'
>>> s.loc[0:1] # rows at index labels between 0 and 1 (inclusive)
0 d
1 e
>>> s.iloc[0:1] # rows at index location between 0 and 1 (exclusive)
49 a
Here are some of the differences/similarities between s.loc
and s.iloc
when passed various objects:<object> | description | s.loc[<object>] | s.iloc[<object>] |
---|---|---|---|
0 | single item | Value at index label 0 (the string 'd' ) | Value at index location 0 (the string 'a' ) |
0:1 | slice | Two rows (labels 0 and 1 ) | One row (first row at location 0) |
1:47 | slice with out-of-bounds end | Zero rows (empty Series) | Five rows (location 1 onwards) |
1:47:-1 | slice with negative step | three rows (labels 1 back to 47 ) | Zero rows (empty Series) |
[2, 0] | integer list | Two rows with given labels | Two rows with given locations |
s > 'e' | Bool series (indicating which values have the property) | One row (containing 'f' ) | NotImplementedError |
(s>'e').values | Bool array | One row (containing 'f' ) | Same as loc |
999 | int object not in index | KeyError | IndexError (out of bounds) |
-1 | int object not in index | KeyError | Returns last value in s |
lambda x: x.index[3] | callable applied to series (here returning 3rd item in index) | s.loc[s.index[3]] | s.iloc[s.index[3]] |
Replacements for switch statement in Python?
Python 3.10 (2021) introduced the match
-case
statement which provides a first-class implementation of a "switch" for Python. For example:
def f(x):
match x:
case 'a':
return 1
case 'b':
return 2
case _:
return 0 # 0 is the default case if x is not found
The match
-case
statement is considerably more powerful than this simple example.The original answer below was written in 2008, before
match
-case
was available:You could use a dictionary:
def f(x):
return {
'a': 1,
'b': 2,
}[x]
Why would ternary (0 ? yes : no) return yes in javascript?
Non-empty strings are truthy. "0"
is not 0
.
However, comparison will coerce 0
to a number.
Note, the only string which can be coerced to true
during comparison is "1"
. (Please let me know if there are edge cases I'm missing!)
"true" == true // false
"foo" == true // false
"0" == true // false
"1" == true // true
What does axis in pandas mean?
It specifies the axis along which the means are computed. By default axis=0
. This is consistent with the numpy.mean
usage when axis
is specified explicitly (in numpy.mean
, axis==None by default, which computes the mean value over the flattened array) , in which axis=0
along the rows (namely, index in pandas), and axis=1
along the columns. For added clarity, one may choose to specify axis='index'
(instead of axis=0
) or axis='columns'
(instead of axis=1
).
+------------+---------+--------+
| | A | B |
+------------+---------+---------
| 0 | 0.626386| 1.52325|----axis=1----->
+------------+---------+--------+
| |
| axis=0 |
↓ ↓
Detecting an undefined object property
The usual way to check if the value of a property is the special value undefined
, is:
if(o.myProperty === undefined) {
alert("myProperty value is the special value `undefined`");
}
To check if an object does not actually have such a property, and will therefore return undefined
by default when you try to access it:if(!o.hasOwnProperty('myProperty')) {
alert("myProperty does not exist");
}
To check if the value associated with an identifier is the special value undefined
, or if that identifier has not been declared:if(typeof myVariable === 'undefined') {
alert('myVariable is either the special value `undefined`, or it has not been declared');
}
Note: this last method is the only way to refer to an undeclared identifier without an early error, which is different from having a value of undefined
.In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check foo === undefined
might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.
However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.
If you are worried about this (unlikely) edge case, you can use the void operator to get at the special undefined
value itself:
if(myVariable === void 0) {
alert("myVariable is the special value `undefined`");
}
How can I map True/False to 1/0 in a Pandas DataFrame?
A succinct way to convert a single column of boolean values to a column of integers 1 or 0:
df["somecolumn"] = df["somecolumn"].astype(int)
What is the difference between null and undefined in JavaScript?
undefined
means a variable has been declared but has not yet been assigned a value :
var testVar;
console.log(testVar); //shows undefined
console.log(typeof testVar); //shows undefined
Related Topics
How to Read JSON File with Fetch() in JavaScript
When Do I Need to Specify the JavaScript Protocol
Why "This" Is Undefined Inside a Fat Arrow Function Definition
Understanding JavaScript Promises; Stacks and Chaining
How to Find a Reason Angularjs "Argument 'Myctrl' Is Not a Function, Got Undefined"
How to Read the Correct Time/Duration Values from Google Spreadsheet
In JavaScript, Can You Extend the Dom
How to Use Getelementsbyclassname in JavaScript-Function
How to Check "Checkbox" Dynamically - Jquery Mobile
Jquery:Select All Element with Custom Attribute
Twig Variable in External Js File
JavaScript Displaying a Float to 2 Decimal Places
How to Make a Directive Update Ng-Model on Jquery on Event
How to Calculate the Number of Years Between Two Dates
Gmail Extension, Sendmessage to Background from Page Context