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.
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 5 years ago.
Improve this question
I'm new to JavaScript and working on a coding challenge as part of a bootcamp application process.
The question requires writing a single function to accomplish a task.
Although I've looked far and wide, I've yet to come across an answer.
If I write a function that contains other, nested functions, would that still be considered one function?
If I write a function that contains other, nested functions, would that still be considered one function?
Yes. A function is an encapsulation unit, it's a blackbox. You can call it, and get results back, but how it is implemented does not matter when looking from outside. A function that modularises its internal implementation into multiple local function is indistinguishable from one that does not as long as it behaves the same.
Yes.
From a technical perspective you can't even write a function that doesn't call use nested functions. The act of declaring variables alone is going to call a chain of functions to allocate memory which in turn eventually calls functions in assembly which then calls functions in your processor to which calls functions to your memory driver which calls.
Similarly calling operators to set or manipulate your variables are function calls which are all layered APIS calling a chain of functions.
Suppose you write a function min that looks like this:
function min(a,b) {
return Math.min(a,b);
}
This is still a single function even though it is calling a global function.
The same logic applies if you write an internal function for a complex object
function min(data) {
var smallest = function(a,b) {
if (a.x<b.x) { return a;}
else if (a.y>b.y) { return b;}
else if (a.y<b.y) return a;
return b;
}
return smallest(data[0],data[b]);
}
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
Given the following function:
function lamePathValidator(path) {
if (typeof path !== 'string') {
throw new TypeError(`Invalid path "${path}": should be a string.`);
}
return path;
}
Is it considered bad practice if occasionally it's being used without storing the return value to a variable?
...
lamePathValidator('./data');
...
Edit: The only use case in which I need the returned value, is for property assignments in constructors, such as:
constructor(basepath) {
this._basepath = this._validatePath(basepath);
}
I could of course write:
constructor(basepath) {
this._validatePath(basepath)
this._basepath = basepath;
}
The former block is more concise though.
Edit #2:
I could also pass constructor parameters to a _validateAll(params) function since none of them are actually being altered in any way. It's "validate", not "sanitize" after all. :)
There are lots of functions that return data that is not always useful, but sometimes is. In those cases not storing the output when you don't need it makes sense.
However if the return value is never useful then you shouldn't be returning it in the first place. In your example function the path is not altered so there is no reason to return it, the calling code already has it.
A function can return a value if required. It is not mandatory to return some value from it. In your case there is no need to return any value.
Read the js function documentation here
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
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.
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
}