In C/C++:
i = 0 || 2; // i == 1
In JavaScript:
i = 0 || 2; // i == 2
What about Java, C# or other C-like languages?
digital mam
In C/C++:
i = 0 || 2; // i == 1
In JavaScript:
i = 0 || 2; // i == 2
What about Java, C# or other C-like languages?
In JavaScript:
i = 0 || 2; // i == 2
the induction of i, anything greater than 0 but less than 2 is 1) ... in JS if the callback is greater than the initial state (0) then it is forced to 2 .. risking looking like a moron ... there wasn't much meat on the bone in
Re: Re: JavaScript vs. C/C++ behavior
By: Mortifis to Digital Man on Tue May 21 2019 12:51 am
In JavaScript:
i = 0 || 2; // i == 2
the induction of i, anything greater than 0 but less than 2 is 1) ... in JS if the callback is greater than the initial state (0) then it is forced to 2 .. risking looking like a moron ... there wasn't much meat on the bone in
The trouble with boolean operations in JavaScript is the concept of "truthy" anf "falsy" values. Javascript will always try and make a boolean comparison work, even if it is not comparing two boolean values. Thus, we wind up with "falsy" values that evaluate to FALSE when compared, and "truthy" values that evaluate to TRUE.
The "falsy" values are: FALSE, 0, "" '' and `` (the empty string), null, undefined, and NaN.
The "truthy" values are everything else, including empty objects and arrays.
This particular assignment does a boolean OR comparison. The first element that is "truthy" is the one that is assigned to the variable. Since 0 is always a "falsy" value, it is skipped, and we wind up with i === 2.
Sysop: | Chris Crash |
---|---|
Location: | Huntington Beach, CA. |
Users: | 578 |
Nodes: | 8 (0 / 8) |
Uptime: | 28:48:14 |
Calls: | 10,737 |
Files: | 5 |
Messages: | 443,806 |