Angular Templates - inline expressions vs calling to function - javascript

Is there any difference between those two:
<li [ngClass]="{disabledField: condition1 && condition2 && condition3}">Click</li>
vs
<li [ngClass]="{disabledField: shouldDisableField()}">Click</li>
and in component class:
shouldDisableField(): boolean{
return this.condition1 && this.condition2 && this.condition3;
}

The only difference is between a function call and evaluating an expression in JavaScript, Angular is irrelevant here. Function call is usually marginally slower, so the first option should be marginally faster.
Angular view compiler produces the following code for updateRenderer function:
function(_ck, _v) {
var _co = _v.component;
---> var currVal_0 = _ck(_v, 3, 0, ((_co.condition1 && _co.condition2) && _co.condition3));
_ck(_v, 2, 0, currVal_0);
}
And
function(_ck, _v) {
var _co = _v.component;
--> var currVal_0 = _ck(_v, 3, 0, _co.shouldDisableField());
_ck(_v, 2, 0, currVal_0);
}
As you can see only one line is different and that is all that matters.
You can read more about updateRenderer function in the article:
The mechanics of DOM updates in Angular.

Most answers here only mention the difference in performance as marginal.
I don't think this is correct and the performance here can be quiet significant.
Please refer to Phil Parsons great article about this:
Function calls in Angular expressions are killing your apps performance
You should be aware of the performance hit as shown there

Not really, though I would suggest the second, as this is much cleaner and will help with minimising data transfer in templates. Admittedly this may seem insignificant, but its good practice to compartmentalise javascript code, plus it will get the benefit of code minification AND gzip (if enabled on HTTP requests).
However, saying that, if this is an exception case, then the first may be more helpful with for other developers (or yourself) down the track, but I would only use this in a rare case, as the second gives you the ability to update/extend/fix it much easier, particularly if you're likely to re-use the same rule/condition.
With regards to Angular's binding model, I'm not sure if there is much in the way of caching (if that's what you were thinking) or performance that I've personally seen.
Hope that helps.

As explained in above answers, both the approaches will work fine.
<li [ngClass]="{disabledField: condition1 && condition2 && condition3}">Click</li>
<li [ngClass]="{disabledField: shouldDisableField()}">Click</li>
But there are some points which make them different.
One of the most important things is AOT strategy. Function calls may be a headache while migrating from JIT to AOT (which normally happens with most of the developers). If the called function is a private function, AOT Compilation throws a compile time error as it treats template and component as 2 different entities.
The other point is, data bindings are readable and can be understood easily.
Having said that, we may come across a situation, where data bindings alone wont solve the problem. Calling a function in those cases wouldn't be a wrong thing to do!
Hope this helps you! :)

There is not really a difference. I would use
<li [ngClass]="{disabledField: condition1 && condition2 && condition3}">Click</li>
if i'd only one expression like that in my template. Otherwise I'd use
<li [ngClass]="{disabledField: shouldDisableField()}">Click</li>
to reduce the written code.

Related

Which is more efficient in a function: conditional execution or conditional exit?

I would really hear some opinions on which of the following solutions is more efficient in JavaScript/TypeScript:
function whatever(param) {
if (param === x) {
doStuff();
}
}
or
function whatever(param) {
if (param !== x) { return false; }
doStuff();
}
Obviously the second one reduces the number of blocks and improves code readability, but does it offer any benefits or drawbacks compared to the first one?
In assembly you'd write both as:
// first
whatever:
CP x, param
JP nz, whatever2
CALL doStuff
whatever2:
RET
// second:
whatever:
CP x, param
JP z, whatever2
RET
whatever2:
CALL doStuff
RET
So while the first one uses 4 instructions, the second uses 5. So in case the JS engine is able to optimize it down to this optimal bytecode (very unlikely, but it makes estimations easier), the second one will be 1 tick slower, which is less than a nanosecond.
Here is a test where I run the comparison 10000 times.
The difference is pretty much non-existant.
There is no significant difference in efficiency, even if you have more than one of these preconditions in your function. No matter what language you use. Some compilers will probably even generate the same machine instructions from both versions.
Stop thinking about efficiency too much. Think about readability and maintainability!
It depends on the use case here, I don't think there is much difference in the context of performance or code readability.
I would personally go with the second approach as it also reduces indentations. Indentation gives me a clear indication of initialization of newer block. If I notice a new indent, I would assume there should be a for loop here or an if statement.
If the code is part of the main flow or the most common flow, I wouldn't want that to be further indented.
Again, All this is my personal style guide rules which have helped me to be able to deduce the code logic faster.

What is the difference and benefits/drawbacks between object literals and functions that return an object inside an IIFE?

So to clarify the question, I understand what an IIFE and object literal is. However, I am unsure what the difference(s) is/are between these two examples (aside from the fact that one is a function and the other is an object literal):
Example 1:
(function(){
var myStuff = {
arbitraryValue: 42
}
return myStuff.arbitraryValue;
})();
Example 2:
(function(){
var myStuff = function() {
return {
arbitraryValue: 42
};
}
return myStuff().arbitraryValue;
})();
Both examples return the same results, and are called (almost) the same way. But:
1) What are the fundamental differences between them?
2) Is there a benefit to using one over the other?
3) I've seen code where (in the 2nd example) return myStuff.arbitraryValue works just the same as return myStuff().arbitraryValue. How is that possible?
4) Is this overkill if I'm just trying to avoid global conflicts and write clean code?
5) Are either of these examples considered "best practice," or is there another option?
Many thanks in advance!
1) What are the fundamental differences between them?
The first (probably) uses less CPU cycles because it has one less function call and is less to write. It's also easier to understand so is likely easier to maintain.
2) Is there a benefit to using one over the other?
The first uses less code and is likely easier to understand and maintain.
3) I've seen code where (in the 2nd example) return myStuff.arbitraryValue works just the same as return myStuff().arbitraryValue. How is that possible?
Perhaps using get, a feature of JavaScriptâ„¢ but not ECMAScript.
4) Is this overkill if I'm just trying to avoid global conflicts and write clean code?
Yes, though you haven't shown what is done with the returned value. In the example it disappears into the ether.
5) Are either of these examples considered "best practice," or is there another option?
"Best" infers a complarison with other things that are less preferred based on objective criteria. Without those criteria (which might be some of: speed, robustness, maintainability, support or other features, desirable or not) it can't be determined.
If you propose a circumstance where you'd like to use one or the other, advice can be given on whether there are better ways or not based on the criteria suggested (or others you may have) and in comparison to alternatives.

jQuery best practice - using selectors vs function(variable)

This is a general question about best practice in jQuery syntax/code organisation.
Consider the following snippet, used in a jQuery AJAX function:
if(obj.status == "error"){
$("#alert").html(obj.message);
}
I have also seen this written as:
function alert_box(str)
{
var html_str = '';
$("#alert").html(html_str);
}
if(obj.status == "error"){
alert_box(obj.message);
}
Functionally, this is precisely the same. My question: Is there any semantic or practical reason for differentiating between the two? What about load time / performance issues?
This is seems to be a question of "why use functions in general"? The idea behind a function is that you're making a code block reusable without having to write out the same code again. If you want to do that same thing in several places throughout your script, the function makes sense. If you only do that once, it may not be as practical. Then again, functions also help you hide details where you don't care about them - so you can summarize an action while the details of that action are somewhere in that function definition.
In this specific case, that function is broken anyway. Rather than using the passed in argument str, you have an empty variable html_str that you're replacing the html contents of an element with. Also, there's no need here to use html rather than text, which is better performance.
function alert_box(str) {
$("#alert").text(str);
}
Even though this is only a one liner, this can still be practical because it would let you use alert_box in several places throughout the script and not have to change those places later if you decide to change what alert_box does. Even something like changing the id of the element would require changes in several places, for example.
It also worth noting that this function searches the DOM for "#alert" each time it runs. It would be most optimal to cache that reference like this:
$alert = $("#alert");
function alert_box(str) {
$alert.text(str);
}
A few things that are great to study:
KISS
DRY
SOLID aka OOP

if..else vs if(){return} [duplicate]

This question already has answers here:
Using 'return' instead of 'else' in JavaScript
(13 answers)
Closed 5 years ago.
In the following example - given that the return value isn't of any importance - is there a reason to prefer either method over the other?
// Method 1
function (a, b) {
if (a == b){
// I'm just interested in
// the stuff happening here
} else {
// or here
}
return true;
}
// Method 2
function (a, b) {
if (a == b){
// I'm just interested in
// the stuff happening here
return true;
}
// or here
return true;
}
It seems that best practices (mostly by places I've worked for) is to set default values at the top of a method or function and only change those values if some condition occurs. Thus, the use of else is not needed so Method 2 is preferred.
Since the example is JavaScript, special attention needs to be paid in regards to code size. So Method 2 would create less code for the same functionality, furthering its argument as the preferred.
However, if you have more than 2 possible conditions, an else or else if cannot be avoided. However, most places I've worked prefer a Switch Case in these situations.
I would prefer Method 1 because it is less confusing to read. Also, less duplicate code.
I would base my decision on clarity of code and readability, i.e.:
Choose method 1 when you need to do more stuff in the block after the if-block.
Choose method 2 when you only need two blocks of code, it's then clearer to read
Choose method 1 again in cases where you explicitly think your readers wouldn't understand your cryptic code without the word "else"; this is common when the blocks become larger than a few lines.
Many of today's programmers consider less indentation easier to read and I agree. In which case general preference should go to using the second method.
I would recommend method 1 as it is more readable and self documented.
Any modern browser's interpreter should eliminate any performance advantage in either direction.
There are a couple of reasons method 1 is preferable that haven't been mentioned yet. Having a single point of exit makes any future modifications that require an action common to both branches easier and less likely to be buggy (because the author missed the early return. Similarly, in some cases it makes debugging easier, by providing a common place to put a breakpoint or alert().
Readability here really depends on the role of the function.
If this function will ALWAYS return true, then I would prefer the Method 1 It is clear because it only returns in one place, and it is easy to see it will always be true.
In the above case, Method 2 is more confusing. It returns in multiple places, and is more confusing thusly. Consider a developer unnecessarily traversing possible branches and then seeing how they affect the return value. In this simple case, it is not as big of a deal, but when you get more elaborate conditionals, I would really avoid this approach.
I would only use Method 2 if you have very little code in the if block. Such as something that would deal with an edge case.
Hope that helps.

JavaScript object definition conditionals - which is better?

I've come across two different ways to define/name objects and functions in JavaScript that first check for the existence of the name before using it. The issue is, I don't know which one is better (from speed and usability standpoints) and it's impossible to use the boolean operators in a Google search to figure it out.
The first one I see most often:
var myNewObject = myNewObject ? myNewObject : function () {
// Code goes here.
};
The second one seems more concise, but I've only seen it one or two places, so I don't know if there's a standard or even a name for it:
var myNewObject = myNewObject || function() {
// Code goes here.
};
Functionally, they both do the same thing and they both seem to work in every browser I can test in. My question is this - which is better and why? Also, while the first definition is essentially a single-line conditional ... what is the second one called?
I would choose the latter if only for the fact that you type myNewObject twice instead of thrice.
Also, while the first definition is essentially a single-line conditional ... what is the second one called?
Short-circuit evaluation
I would use the second example, which is described as (Minimum Eval). Its simpler and seems more readable.
It's just like getting an event from onClick method across multiple browsers.
element.onclick = function (evt) {
evt = evt || window.event
}
The latter, it's similar to the null coalesce operator in c# ?? when used in that manner
see: Is there a "null coalescing" operator in JavaScript?
FWIW I see the second approach more often, and (for my part) I feel it's more clear, concise, and idiomatic.
Both methods work.
But I think the most optimized version is to simply use a normal if test like:
if(!myNewObject)
myNewObject = ...
Doing in any one of the method you suggest in your answer, it might involve an unnecessary reassignment every time the function/object is already defined. I mean if myNewObject is already defined, the JavaScript runtime would have to perform an unnecessary reassignment myNewObject = myNewObject (unless the runtime doesn't optimize it out).
On Mozilla website they suggest to use a simple if, view this.

Categories