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.
Related
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.
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
I'm trying to decide what style to use for module-level function definitions.
Here are the options I've considered:
// function expression using an arrow
const foo = (arg)=> {
// ...
};
// function expression with the `function` keyword
const bar = function(arg){
// ...
};
// function declaration
function baz(arg){
// ...
}
I prefer the foo style, but it seems to be non-standard. Are there considerations against it that I haven't considered? For example, are there significant performance penalties to using function expressions, const, or arrows, either natively or when transpiling?
Here's what I have so far:
Advantages of using const with a function expression instead of using a function declaration:
Nothing is ever hoisted if you only use const and let: it makes the language simpler to work with.
Using const makes the interpreter throw an error if you try to define two functions with the same name in the same scope (this has been surprisingly helpful).
Using const lets you say what you mean: most of the time, one wants to define a function, not assign to a variable.
Using const instead of a function declaration makes it clearer that functions are values in JS.
Disadvantages of function expressions:
A function declaration causes both the variable declaration and function body to be hoisted to the top of the current function body (I think). This may actually be helpful if you like to lay your JS files out with function-using code on top and function definitions at the bottom.
I couldn't find any cases where function expressions are harder to debug or where it was harder to use recursion with function expressions.
Advantages of using arrows instead of the function keyword:
The fat arrow has simpler semantics in this sense. It's probably better to not ask for new values of this and arguments unless they are really needed.
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 8 years ago.
Improve this question
I defined some variables in Javascript:
var aaa = "aaa";
var bbb = "bbb";
var ccc = "ccc";
But my friend says it should be better to define them as:
var aaa = "aaa",
bbb = "bbb",
ccc = "ccc";
Because JsLint will report errors on my code.
I'm not sure why we should do it as the second one, since I found my version is better to view if the value is very big, like:
var aaa = {
some1 : 111,
some2 : 222
};
var bbb = {
some1 : 111,
some2 : 222
};
In JavaScript there is no block scope, only function level scope. So, if you use multiple var statements, the developers who are coming from other languages might not feel the difference. For example,
var numbers = [];
for (var i = 0; i < 10; i += 1) {
numbers.push(i);
}
If you are familiar with C, C++ or JAVA, you might think that the i is not available outside the for loop. But it is, because of the reason mentioned in the first line.
So, to avoid the confusion, JSLint encourages you to use only one var statement per function, and that too should be the first line of that function.
Quoting from the jslint's documentation,
In many languages, a block introduces a scope. Variables introduced in a block are not visible outside of the block.
In JavaScript, blocks do not introduce a scope. There is only function-scope. A variable introduced anywhere in a function is visible everywhere in the function. JavaScript's blocks confuse experienced programmers and lead to errors because the familiar syntax makes a false promise.
JSLint expects blocks with function, if, switch, while, for, do, and try statements and nowhere else.
In languages with block scope, it is usually recommended that variables be declared at the site of first use. But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. It is recommended that a single var statement be used per function. This can be declined with the vars option.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm a bit confused when using some of parentheses, brackets, and curly braces in Javascript and jQuery. Is there a simple way of understanding when to distinguish when to use these?
Example 1:
$("#theDiv").animate({width: "500px" }, 1000);
Example 2:
$("img").attr({src: "/images/hat.gif", title: "jQuery"});
Example 3:
$('a[rel="nofollow self"]')
Thanks.
Unfortunately, the best answer is "use them each as appropriate where necessary".
Parenthesis () in JavaScript are used for function calls, to surround conditional statements, or for grouping to enforce Order of Operations.
function myFunc() {
if (condition1) {
}
if ( (1 + 2) * 3) {
// very different from (1 + 2 * 3)
}
}
Braces {} are used during the declaration of Object Literals, or to enclose blocks of code (function definitions, conditional blocks, loops, etc).
var objLit = {
a: "I am an Object Literal."
};
Brackets [] are typically mostly used for accessing the properties of an Object (or the elements of an Array), so mylist[3] fetches the fourth element in the Array.
var mylist = [1,2,3,4];
alert(mylist[2]);
It doesn't help that you're trying to start with jQuery, which also uses its own Selector Grammar within Strings that are passed to function calls (which can make it look much more complicated than it actually is). This: $('a[rel="nofollow self"]') is only a single function call, and the inner brackets are handled by jQuery.
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
}