Pros and Cons of explicit data conversion in JavaScript [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Does any of you guys use explicit data conversion in JavaScript?
For example:
//ModificationAllowed is an integer (1 or 0) value from registry
canModifyRecord = Boolean(application.settings('ModificationAllowed'));
if (canModifyRecord) {
... do something
}
I want to keep my code as clean as possible but maybe explicit conversion is redundant?

Yes and no. It all depends on the context.
If I'm fetching data for a model representation, then yes. I'll make sure the data I store is correctly typed.
If I do calculation with data coming from the user or a server, then yes. I convert everything to Number() or I parseFloat them.
But for boolean check, if my check is localize and not used elsewhere in the application, then I usually don't do the conversion for brevity sake. But ensuring correct type (with the !! hack for example) cannot harm.
So as a rule of thumb:
Is the data to be reuse elsewhere? Then ensure a correct type.
Is the data scope limited to the current method/function? Then, only convert if it brings real value (like calculation). Otherwise, type automatic conversion is usually ok.

Converting to a boolean is redundant if you only use that variable as the condition of an if conditional, as you do here. In ECMAScript terms, if already converts its condition to a boolean using ES5's ToBoolean, which is the same mechanism used by Boolean(arg).
Other cases will be affected by the conversion, notable in equality tests (whether strict or non-strict):
"foo" == true // false
Boolean("foo") == true // true
This is because the behavior of the non-strict equality algorithm is heavily type-dependent. In particular, see step 6 and 7 for boolean-to-other comparison behavior, which casts the non-boolean operand to a number.

Using !! converts a variable to a boolean nice and easily for me
canModifyRecord = !!application.settings('ModificationAllowed');
if (canModifyRecord) {
... do something
}

Related

Using !! in if statements [duplicate]

This question already has answers here:
What is the !! (not not) operator in JavaScript?
(42 answers)
Closed 2 years ago.
I have come across code in a web app where it uses !!, I was told that this enforces a check for true or false instead of truthy or falsy. Is this correct?
if (!!this._currentItemIndex) {
this._findItemByCurrentIndex();
}
I have been having trouble finding any resources online to explain this.
Normally you'll see code like:
let x = !!y;
Where this is casting whatever value y has into a simple true or false outcome, a boolean. This is often employed to avoid retaining references to things you don't need, like y could be a complex structure but you don't care about the details, you just want to track if it was assigned.
It's unusual to see this employed in an if since it really doesn't do anything useful. It converts to a boolean, but if will anyway. This is just junk code.
It might as well be if (!!!!!!!!!!!!!!!!!!!!x) for all the good it does.
A better version would look like:
if (this._currentItemIndex) {
// Some non-zero value was assigned
}
Or if it is populated:
if (this._currentItemIndex > 0) {
// Communicates intent better
}

Google: "EcmaScript 5 getters and setters for properties are discouraged" Why? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
According to the Google JS style guide getters and setters are discouraged. Why is this?
Mozilla JS Object docs explicitly advocate using getters and setters in js. I'm confused about the discrepancy.
Because using getters and setters can, from the outside point of view be confusing.
Lets say I make an object myObject with the following property status. That property uses a getter and computes a result for getting it. Example:
const status = myObject.status;
const open = status.open; // true
const color = status.color; // "blue"
Now everytime I use myObject.status it looks like I just access a direct property but it s not true. In fact it calls a function that can take a lot of computation.
Now another person who didn't implement myObject comes in and does this
const open = myObject.status.open; // true
const color = myObject.status.color; // "blue"
And it works ! But a potentially compute heavy function is called twice instead of once.
It can also have side effects (worst situation, don't use getters with sideeffects), and when you look for a bug and you don t know where it comes from it is hard to tell.
That is why some recommend to use const status = myObject.getStatus();. It is an explicit function call.

One-line if vs && in JavaScript [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Is there any meaningful difference between
condition && console.log("this may run");
and
if (condition) console.log("this may run);
If not, which is a best practice?
You should use the second.
Your code should say what it means. That is what is meant by writing "semantic" code. If you are writing an if condition, then you should use the if statement, because that's what it is there for. The && is, semantically, a logical and, which should be used in cases where you are interested in the logical value resulting from the logical conjunction of two values.
Writing semantic code, as other answers have suggested, makes it easier to write and understand and maintain. As far as this comment goes:
If someone else may need to read or maintain it, then use the second.
Remember that "you six months from now" is "someone else".
Here are some specific reason for using if when you mean if:
If you want to add an else clause, you can just add it. If you have written a && b then you will have to rewrite it as a ? b : c.
Assuming you have used curly braces, as in if (a) { b; }, then you can easily add another step to the body, by writing if (a) { b; c; }. If you had written a && b, then you would need to rewrite this as a && (b, c) or something equivalent; this will not even be possible in some cases, if c cannot function as an expression.
Some linters will (reasonably) complain about a && b.
Note that minifiers will typically convert your second example into the first, so if your rationale for using && is to save bytes, they will be saved anyway by the minifier.
There is no difference as such, but you can say that the former one is the shorthand notation of the later one.
I would suggest you to use the later condition, it makes the code more explainable, producing the same results and with the almost the same number of characters.
If only you may ever maintain the code, then use the one you like.
If someone else may need to read or maintain it, then use the second.

How can you reliably test if a value is equal to NaN? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I only know to use isNaN to test if a value is equal to NaN. Is it really reliable?
The NaN property represents a value that is “not a number”. This special value results from an operation that could not be performed either because one of the operands was non-numeric (e.g., "abc" / 4), or because the result of the operation is non-numeric(e.g., an attempt to divide by zero).
While this seems straightforward enough, there are a couple of somewhat surprising characteristics of NaN that can result in hair-pulling bugs if one is not aware of them.
For one thing, although NaN means “not a number”, its type is, believe it or not, Number:
console.log(typeof NaN === "number"); // logs "true"
Additionally, NaN compared to anything – even itself! – is false:
console.log(NaN === NaN); // logs "false"
A semi-reliable way to test whether a number is equal to NaN is with the built-in function isNaN(),
but even using isNaN() is an imperfect solution.
A better solution would either be to use value !== value, which would only produce true if the value is equal to NaN. Also, ES6 offers a new Number.isNaN() function, which is a different and more reliable than the old global isNaN() function.

Ternary Statements in Javascript: pitfalls of no assignment? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Sometimes I use ternary statements to simplify & reduce the length of my code.
Ternary statements are traditionally used to assign a value to a variable, but in JS I can also write ternary statements with no assignment to execute differing outcomes based on the boolean response to the question - example:
anyVariable > someValue ?
funcOne(anyVariable):
funcTwo(anyVariable);
This code throws no errors, but jsLint complains that it saw an expression where it expected an assignment or function call.
Are there any pitfalls or potential issues I should be aware of when using ternary statements (in Javascript) in this fashion?
There should not be any pitfalls in this fashion. Consider the following statement -
b = a = 10;
we can omit the "b=" portion of the statement without any issues. And its the same case for the ternary statements.
Generally you should avoid this type of use because an error in previous lines may cause problem with the later code. But if you use if-else then you can avoid such problems.
// user made a typo on the first line. but this code has correct syntax
b = 10 +
a > 10 ? fun(20) : fun(0);
// same scenario using if-else will generate a compilation error which is preferred.
b = 10 +
if (a>10) {
fun(20);
}
else {
fun(0);
}
JS(L|H)int is going to complain about that because it's just a expression and not a statement. In cases like this, it's "better" (argumentative) to use an if:
if(anyVariable > someValue){
funcOne(anyVariable);
} else {
funcTwo(anyVariable);
}
edit
If terseness is a goal you can always omit the curly braces:
if(anyVariable > someValue) funcOne(anyVariable)
else funcTwo(anyVariable);
/edit
The bonus here is that your code is more readable (since it's all assignments or function calls), and if you need to extend or do more than one operation in each clause, you're set up for it.
Where the ternary operator is used well, however, is in assignments:
var thisVariable = someValue > thatValue ? someValue : thatValue;
That will pass the linter, and the statement, while terse, is still pretty readable, however, when testing against "falsey" values, I do prefer:
var thisVariable = someValue || thatValue;
If someValue is "falsey", it will set thisVariable to thatValue.
I'd avoid it, if you use it incorrectly then it'll cause errors (I've seen invalid left hand assignment amongst others). If you're using a good minifier (such as Uglify), it'll do all this for you when running your build process - which keeps your development code readable and easy.
I'd stick with using it for assignment only.

Categories

Resources