Does OO Javascript have a `to_bool` or `__len__` equivalent? - javascript

Does OO JS have a mechanism for casting instance objects to boolean? I would like to be able to use custom instance objects directly in conditionals, and make assertions along the lines of !!(new Foo(0)) === false, !!(new Foo(1)) === true.
Python has __nonzero__ and __len__ (see here)
Ruby has to_bool.
How does JS do this for String literals "" and zero 0?

No, JS does not provide a trap method for casting to boolean. Truthiness of a value is statically determined by the language rules and cannot be changed.
You should give your instances a method to be explicitly invoked like isValid(), isTruthy(), isEmpty() or whatever concept your object represents.

Related

Is it safe to use integers (1, 0) instead of booleans (true, false) to minify JavaScript?

When JavaScript is used client-side, it has to be transferred over the network, which is why we commonly minify the code, for example by removing whitespace and shortening identifiers (variable and function names, etc).
In JavaScript / ECMAScript, many functions will accept a boolean to trigger certain behavior. For example, DOMTokenList.toggle() or EventTarget.addEventListener(). Using the integers 1 and 0 instead of the boolean values true and false, respectively, when calling upon such functions would save some additional bytes.
However, JavaScript has two comparison operators, == and ===, and while 1 == true would evaluate to true, 1 === true would evaluate to false. Then again, maybe the standard dictates that built-in functions have to be able to deal integers when accepting a boolean or similar. In short, is it safe to replace booleans with integers in the context of built-in functions?
It depends on the built-in function. For some, passing an integer produces the same result as passing a boolean, for others it doesn't. In general, yes, if a function expects a boolean it will attempt to coerce any value into a boolean, but there are probably exceptions.
However, a minifier does in general not know whether a function call is a call to a builtin function, or what the function's signature is. The first goal is to be correct (not introducing bugs), not to output the smallest bundle.
A standard trick that minifiers do employ, and which is always equivalent, is replacing false with !1 and true with !0.

General Term For Getting Property Of A Nullable Object

Considering the JavaScript below:
var foo = undefined;
if(foo?.bar == true){
console.log("Wow. Impossible...");
}
Is there a general programming term for the ?. following the foo variable?
This allows you to compare a member of a potentially null object without having to explicitly check if the variable is null.
I'd like to be able to see if this functionality exists in other languages, but I'm not really sure what to look up.
It is known as Optional Chaining in JS.
Ref:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
https://javascript.info/optional-chaining
It is known differently in different languages, e.g. in C# it is called Null-Conditional.

Equivalent to !== null and === null in Java [duplicate]

Java is a Strong Static Casting so does that mean there is no use for "==="
I have looked at tons of documentation and have not seen Identical Comparison Operator.
=== is useful in weak typed languages, such as Javascript, because it verifies that the objects being compared are of the same type and avoids implicit conversions.
=== has absolutely no use in a strongly typed language such as Java because you can't compare variables of different types without writing a specific method for doing this.
For example, if you want to compare an int to a String in Java, you will have to write some special method as such:
boolean compareIntString(int i, String s) {
return (i == parseInt(s));
}
But this is pretty much overkill. (And as you'll notice, as written, this method only accepts an int and a String. It doesn't accept just any two variables. You know before you call it that the datatypes are different.)
The main point is, that while you can do i == s in Javascript, you can't do i == s in Java, so you don't need ===.
I guess, the short answer is that Java's == is Javascript's ===. If you want to emulate Javascript's == and compare two items, ignoring data type, you'll have to write a custom method which accepts generic data types as arguments... and figure out the logic on comparing, at a minimum, all the possible combinations of Java's primitive data types...
No java does not have === operator. Reason is pretty well explained by nhgrif. Here is the list of operators in java and their precedence:
Source: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

What is this practice called? `objectName && objectName.thing`

I'm trying to find the name of the practice (in any language) in which one checks for an object to be in existence before performing a lookup on it. Usually this is done by throwing in an && in between the object and the object lookup expression, like so in JS:
var example = objectName && objectName.thing;
such that example is evaluated to either undefined or objectName.thing, and avoids a runtime error.
I could have sworn I've heard this before, but I've completely forgotten. What is this practice called?
This is sometimes called a "guard," since the truthiness of the left operand guards access to the right operand. Of course, it's just a logical AND, but the use of AND in this specific context is occasionally called a "guard".
From Douglas Crockford's A Survey of the JavaScript Programming Language:
The && operator is commonly called logical and. It can also be called guard.
From Guard and Default Operators of JavaScript by Sean McArthur:
In Javascript, the way the languages determines logical operations and the values Javascript treats as true or false lead to people using the AND and OR operators for guard and default situations
This practice is sometimes called validation, or evaluation. You can use a ternary operator to do so.
var example = objectName ? objectName.thing : null
This will assign objectName.thing or null to example depending on objectExample

Role of 'prototype' property amidst design of `function` type object?

As per the understanding, The main purpose for the existence of prototype property in a function type object is to allow properties/methods sitting under prototype to get inherited by other objects. This enables prototypical inheritance.
Considering window['Number'] function type object,
In general, Idea is to understand the thought process on what comes under prototype. So. I would like to take a specific example i.e., Number, with below questions.
From design perspective, how would I understand,
1)
why parseFloat()/parseInt()/isFinite()/isInteger()/isFinite()/isNaN()/NEGATIVE_INFINITY/NaN
are part of function type object Number?
2)
why methods toExponential()/toFixed()/toPrecision() are part of Number.prototype object?
Note: Have an idea on class based inheritance using java syntax, where both static/instance members can be inherited.
If you understand classic class based inheritance, then Number.parseFloat is a static class method, while Number.prototype.toFixed is an instance method. The "class methods" do not need an instance of Number to work, you simply call them directly as Number.parseFloat(foo). Instance methods on the other hand require an instance first:
var foo = new Number(bar);
foo.toFixed();
Properties declared on the prototype object are visible from all instances. Thus:
var n1 = new Number(1), n2 = new Number(2);
Those are two instances of Number, and via each instance it's possible to call the functions on the Number prototype:
alert( n2.toExponential() ); // "2e+0"
Because of the way that function invocation works in JavaScript, the .toExponential() function in that example will be invoked with this referring to the number instance used to make the function call — n2 in this case.
Now, the .toExponential() function could have been defined as a property of the Number constructor itself, but then the parameter would have to be passed explicitly (like Number.toExponential(2)). That's not how the runtime was designed, however. As with so many "why?" questions about how languages and APIs work, it's ultimately just a design preference on the part of the language designers. It should be clear that something like .parseFloat() would really not make any sense as a prototype method, because the whole point of .parseFloat() is to turn something that's not a number into a number. (It could have been added to one or more other prototype objects, but again the preference of the language designers was to just make it a callable function on the Number constructor itself; that's a recent ES6 addition to the spec of course.)
Finally note that in the particular case of the Number constructor, it's pretty rare that you'd actually explicitly instantiate a number object. Generally that happens implicitly when a number primitive value is used with the . or [ ] operators as if it were an object reference. Primitives are not objects, but the language automatically wraps a primitive value in a Number object in those cases, so the first example above would work the same if it were written like this:
var n2 = 2;
alert(n2.toExponential());
The variable n2 has a plain primitive 2 in it, but that will be wrapped in a Number instance in order to allow the method call.
I do not know whether you mean a program design perspective or a language (core library) design perspective, so I'll try to answer both.
Before we begin, please forget "class" or "instance" or "static".
JavaScript is not class based.
There only object and inheritance.
Now, let's see the object diagram.
Note that new Number does not inherits Number.
Neither prototype nor constructor is an inheriting relationship.
This means number instances inherits toExponential, toFixed, etc. but does not inherits parseFloat, parseInt etc.
So you call them like Number.parseFloat() and new Number(n).toFixed().
This is how JS is designed. If you don't like it you can design your own Number library.
For example, you may create your own Number that has toFixed methods on the Number object rather than on its prototype object, like this:
var SheepyNumber = {
toFixed: ( n ) => Number.toFixed( n )
}
SheepyNumber.toFixed( 3.14159265358979323846 ) // Evaluates to '3'
Do not add toFixed to Number object. It may work for now,
But if later specifications introduces this function with any different in parameter or logic,
then your program may break when you use the standard implementation,
or a third party library may break if you keep your own implementation.
Either way, you lost.
Which leave us the question, why does JS not put toFixed to Number, like we just did, but instead put toFixed to Number.prototype?
The obvious answer is this is more object-oriented.
Since new Number has an internal value property, toFixed can take that value, instead of taking in an extra argument.
The real answer is no one knows.
JavaScript copied Java for its core API - you can find most of these methods in the Java Float class.
Some of these Java methods are instance methods (corresponds to methods on Number.prorotype), some are static (corresponds to methods on Number), but most are both - including a counterpart of toFixed.
Why JavaScript did not put isFinite or isNaN to Number.prototype?
Why did no browsers implement toFixed on Number which can co-exists with the one on Number.prototype, during the first browser war that shaped the JavaScript as we know now?
Language design is an art.
And you may not always know who is responsible or why, because it has been shaped by many hands.

Categories