How to deal with missing variables in JavaScript? - javascript

I am building an app in Angular, so any Angular specific answers are acceptable, however my question is to JavaScript at large.
My app used several JSON files to store information. Those JSON files are loaded in the head with script tags, and the objects inside them are assigned to variables in a service. There are 3 main JSON objects that I am working with, and some of them have dependencies on the others.
For example, one of them has a Description attribute which contains text combined with an expression, such as: The value is {{10+(2*var)}}.
However, one of the other objects has children, some of which may or may not be included at the time the Description is compiled. One child has a value that will be stored as var2 and the other child doesn't.
If I change my expression to: The value is {{(10+(2*var))*var2}}, then the value will be valid only if the first child is used and defines var2. If the second child is used, var2 is not defined, and as a result leave me with "NaN".
The best method I can think of, is to make another object that contains all possible values from sub children, and set them to default values, and then override them when a child with the value is present.
This has several downsides however. First off, I have to have all variables (there are a lot) present in yet another object, when most of them are not needed. I will also have to "reset" this object repeatedly.
Is there a more efficient, more standardized way of accomplishing this sort of thing?

Well you could default the variables directly in the template so you don't need to worry about existence or order of execution.
The text value would be:
The value is {{(10+(2*(var||1)))*(var2||1)}}
When var2 is missing, it simply multiplies by 1.
You can also use ternary conditon in an Angular expression, such as
The value is {{(var2 ? 10+(2*var))*var2 : 10+(2*var))}}
Note: I would strongly recommend not naming a variable var as it is a keyword in javascript that could cause you trouble when trying to parse them with Angular (or in many other contexts).

Related

Difference between var and other more specific types in dart

I come from Javascript's "let", and I am a bit confused on what the big differences are between var and other types. I understand that there are some cases where we need to use var(anonymous data types), and some where we need to use explicit types. I also understand that the var is less concise and the types are more, but is there a more in depth or practical application of using types instead of var within Flutter development?
You never need to use var; you always can choose to specify an explicit type instead.
var is used if you want to declare a variable and want the type to be inferred from the initializer. (If there is no initializer, the variable will be of type dynamic. However, since dynamic disables static type checking for that variable and incurs an extra runtime cost, you should avoid dynamic when possible and should explicitly variables as dynamic when it's necessary.
If the variable type is inferrable, whether you use implicit or explicit types is a matter of style.
Advantages of using explicit types:
Can be more readable without tooling (i.e., without IDE support that can show you variable types).
Can catch type errors where the inferred type isn't the expected type.
Advantages of using implicit types:
Less verbose, which arguably makes the rest of the code more readable.
Can avoid type errors where the explicit type is accidentally less precise than the inferred type. For example: List someList = [1, 2, 3]; actually declares someList to be of type List<dynamic> even though the right-hand-side would otherwise be inferred as List<int>.
Dart is a statically typed language so Dart needs to be able to determine the type at some point. But it is also smart enough to automatically determine the type based on the context. E.g. the type of the returned value from a function.
It is really a question about style but personally I think the type should be specified for method signatures and class variables. For all variables inside a method, I will use var/final and use clear variable names.
Another reason I try use var/final as much as possible is this can prevent some nasty issues with e.g. generics (List list = <String>['test'] makes list variable the type List<dynamic>.
dynamic in Dart is really just saying to the compile "just let this pass and check if the program makes sense at runtime". So we really don't want to have much dynamic in our code base since we are then using the compilers ability to statically check your program makes sense.
You have
var Multiple asignment and Dynamic type.
It can be assigned from expressions of different types. Be careful, Dart will infer the correct type, as long as variables are declared and initialized at the same time if you are using var.
final Single assignment.
It is often used for when declaring properties inside widget classes.
const Compile time constant.
Is used to define hard-coded values, such as colors, font sizes and icons.
Used as a constructor when you're defining widget classes
Const as a constructor, the widget is optimised by Flutter, and it isn't rebuilt when the parent changes.
Prefer const over final when possible.

Is there any difference between class and staticClass in Vue.js?

Is there any difference between class and staticClass in Vue.js render functions? Using Template Compilation, I can see that it outputs different results depending on what is passed to HTML class attribute.
For example, when I pass a single string (for example 'foo') it outputs staticClass in data object:
<div class="foo"></div>
compiles to:
function anonymous() {
with(this){return _c('div',{staticClass:"foo"})}
}
but when I add a colon : (shortcut for v-bind) in front of class attribute it outputs class:
<div :class="'foo'"></div>
compiles to:
function anonymous() {
with(this){return _c('div',{class:'foo'})}
}
I am curious about the difference between class and staticClass, and which one should i use when writing own render functions.
I have googled a little, but have not found any clue.
Thanks in advance.
The key difference is that staticClass can only be a string. class supports all the other formats, such as arrays and objects.
The class attribute is special in many ways. For most attributes you can't specify both a bound and non-bound version on the same element. It also needs to be merged differently when combining the attributes from nested components. All of this merging happens here:
https://github.com/vuejs/vue/blob/531371b818b0e31a989a06df43789728f23dc4e8/src/platforms/web/util/class.js
When templates are compiled down to render functions they employ a number of undocumented features to take advantage of extra knowledge that comes from the template. This would be one such example, where it knows that an unbound class can only be a string so it tries to retain that knowledge by storing it separately as staticClass.
In theory there are a couple of advantages to that:
Manipulating the value doesn't need to worry about the array and object forms of class.
The staticClass can never change, so there's no need to check it when updating the DOM.
However, in practice that second optimisation isn't implemented (there's something that looks similar in the template compiler but it's not quite the same thing). Further, it's not entirely clear from looking at the code that there's much gained from a manipulation standpoint either. If anything it looks like it just makes things more complicated trying to maintain the two separate concepts right until the last possible moment. Perhaps the benchmarks suggest otherwise...
As for which one you should be using in your render functions, only class is documented so I'd stick with that:
https://v2.vuejs.org/v2/guide/render-function.html#The-Data-Object-In-Depth

Arguments and temporary variables in Javascript Functions

I come from C and C++ language and I have a hard time understanding some thing about JavaScript : are variables (parameters) copied in JavaScript when entering a function?
In C/C++, arguments are duplicated for the function and can not be change within the function (of course you can pass pointers as arguments but they cant be change themselves). In JavaScript, it looks like (with closure for instance) you can declare variables inside a function, then use them afterwards. you can also change the parameters inside a function and they keep these modifications afterwards.
Am I right if I say there is only one context of execution in a JavaScript application?
In C you can pass a structure either by value in which case it is copied into a function (and out of it if you return it), or you can pass a pointer to the structure in which case it is not copied and all the changes you make are visible to the caller. In C++ it is the same except you can also pass by reference which behind the scenes is like passing a pointer but the compiler hides it from you a bit.
Think of Javascript as getting all structures passed by reference. Nothing is every copied unless you explicitly copy it.
Also Javascript variables don't contain objects in the variable, they only contain references to the object. So in C/C++ terms all objects are heap based, there are none stored on the stack.
For simple types such as numbers there may be a copy made but as you can't tell it doesn't really matter what it does. Strings are probably passed by reference but as you can't modify an existing string there's no way to tell that either.
I say probably because it's the semantics of the call that matter, different Javascript runtimes could choose to implement things differently provided you can't tell the difference.

Javascript best practices - Using server-side values

For the past few years I have always used a client-side hidden <input> field to store a server-side value and use it in Javascript land.
For example, let's say I need an Ajax timeout value from my app configuration.
I'd probably store it like this in my JSP:
<input type="hidden" id="ajaxTimeout" value="${serverValue}" />
and then use it like this where my AJAX call lived in an external file:
$("#ajaxTimeout").val()
I was having a discussion about this today and it was suggested that it is best practice to store values which are only going to be used by Javascript within HTML <meta> tags.
Does this matter? Is there a preferred way to obtain server-side information which is solely to be used in Javascript?
My understanding is that if the hidden input field is not part of a form then it is safe enough to use to store value as it won't be attached to any requests. Having said that, I've always thought this was indeed a bit of a hack.
Thoughts?
::EDIT::
Two fantastic answers:
Use objects literals for general in-page data that is not tied to any particular DOM element.
Use data attributes to store custom data tied to DOM elements: http://www.w3.org/TR/2010/WD-html5-20101019/elements.html#attr-data
In addition to the plain old object literal method given in other answers, if the value you want to pass to the client is about a specific DOM element (or there is a DOM element that represents the logical object that the value is about), you can put the value in a data attribute:
<div id="videoplayer" data-startplayingat="1:02">HTML Content</div>
This is accessible as an entire attribute, data-startplayingat, or in modern browsers there is the dataset attribute. jQuery syntax is $('#videoplayer').data('startplayingat').
The official W3C spec on data attributes explains all this.
Here are a few interesting highlights:
The name must not use upper case letters, and must be XML compatible.
The dataset attribute converts dashes, such that a name like start-playing will become startPlaying.
One potential drawback for the object literal method (which I like and have used myself) is that if you want the object in a .js file, then normally static javascript files have to be run through your dynamic parser--which will cause a potentially small (but still present) performance loss. Putting the object declaration into a <script> tag in an HTML file works around this, but then you can have script load order issues to deal with.
We personally do something like this:
var options = {
selector: '#divId',
serverSideVariableHere: <%=AspNetProperty %>,
anotherServerSideVariableHere: <%=AspNetPropertyTwo %>
}
var viewModel = new KnockoutViewModel(options);
ko.applyBindings(viewModel, $(options.selector)[0]);
This is simply an example using KnockOut JS, but this idea can be expanded to any JavaScript library you choose to use (or not ;))
We then pass these options to whatever use them, such as Knockout ViewModels, or whatever. That way our JavaScript remains testable and we can pass in whatever values we want to our tests.
Using meta tag for something other than browser meta-"instructions" is no less of a hack IMO.
I would consider storing JavaScript data where it belongs - in JavaScript, using JavaScript object literals.
I strongly prefer JSON snippets in data- attributes. This lets you scope them to the related HTML element, and you don't pollute your Javascript global namespace, or have to generate additional code to handle namespacing otherwise. Coupled with a JSON serialiser on the server side this minimises having to manually escape anything in your values.
(Also I have a Thing™ against <script> tags with content in general. View and logic separation and all that.)

Javascript performance: Variable vs Large object's attribute

I am building a number of HTML5 games and I am not sure about one thing in javascript.
When dealing with a large object (with a lot of attributes and methods), is it somehow different, if I store the attribute value in a variable?
Say I have to check for some value in application.data.setings.foo.bar multiple times per second. Should I store it in a variable fooBar? If I understand it correctly, the variable would be just a reference, so it shouldn't matter.
so: Should you store values of large objects' attributes in variables?
This diagram give you your answer. http://oreilly.com/server-administration/excerpts/even-faster-websites/writing-efficient-javascript.html#access_times_for_object_properties_by_de
I believe what you are asking is:
If you have a variable called:
application.data.settings.foo.bar = { some: 'value' }
Is it more performant to access it by using application.data.settings.foo.bar - or to instead say: var bar = application.data.settings.foo.bar and then refer to bar.
My guess is that the assignment to variable is probably slightly more performant - simply because there are less steps for the interpreter to take in order to access the relevant item. If you use application.data.settings.foo.bar - the interpreter has to utilize the reference to the application object, then reference it's data property, then reference its setting property, then reference its foo property, then reference its bar property. This is 5 steps.
If you reference it into a local variable for access - you are still hitting the same object, but you are hitting it directly on each reference.
At the end of the day, however, this is unlikely to be a performance enhancement which is hugely noticeable, unless you are doing a lot of heavy, rapid-access looping or something similar.
For numbers you may see a performance improvement if you place it in a variable

Categories