I am writing a lot of Javascript code these days and I am making good use of JQuery. I am wondering if it is considered evil to create strange global variable names. I know that a lot of Javascript frameworks such as JQuery use the dollar character; $, but that greatly simplifies code as it can do so many things.
I am thinking of creating a $$ global variable in my code which would be defined as below:
function $$(tagName)
{
return $('<' + tagName + ' />');
}
The benefit of this is that my code has (1) abstracted out the logic of creating a new element, (2) made the code more concise, and lastly (3) I can almost create html elements within Javascript as concisely as html itself because JQuery has so many other selectors to chain off:
$$('div').attr( { id : 'myDiv', 'class' : 'MyDivClass' }).append(
$$('ul').append(
$$('li').text('first'),
$$('li').text('second'),
$$('li').text('third')
);
);
Do you believe the above approach of creating $$ is legitimate or would you regard it as a no-no?
This is of course an opinion, but if I was new to your application, I would have to go look up what that function does in order to understand the code. Also, the function is simple enough that other developers would likely not bother using it, so you'd end up with a mix of techniques which is confusing.. And really, is this so bad?
$('<div/>').attr( { id : 'myDiv', 'class' : 'MyDivClass' }).append(
$('<ul/>').append(
$('<li/>').text('first'),
$('<li/>').text('second'),
$('<li/>').text('third')
)
);
I prefer a clear, meaningful, self-documenting name over JQuery style $ any day of the year.
Also I find it confusing that the same name has different meanings depending on the context it is used in. Like $ in JQuery or this in javascript and will avoid using them as much as I can.
EDIT: In my opinion it should be up to the user to decide whether he wants to use a shorthand name for the framework he uses. It requires only one line of code:
var $ = jQuery;
When I look at pages with jQuery in it, all I see is a big mess flooded with dollar signs that do different things in different places. If the library had used meaningful names for the functions it offers it would be a lot easier to decipher other peoples code. Javascript is already difficult and unreadable as a language itself.
Personally I don't think it's adding that much functionality to account for the "namespace pollution", not to mention the possible confusion of people reading your code that aren't familiar with your method.
It's just saving a trivial couple of characters on each invocation of the method, so in that respect it can only be considered a form of syntactic sugar. And the cons outweigh the pros, in my opinion.
It would be good if you take a look at the construction of e.g. jQuery .
It does'nt work with several global variables/functions, there is only one global object required "jQuery" .
Everything else are properties of this one object, so they have minified naming-conflicts.
In the special case of $$ : maybe sometimes you need to work with prototypejs, but you cant, because prototypejs already uses $$.
So my suggestion: create one global object, your own "library" , give it a distinct name, and let your functions/variables be member of this object.
I don't think it's "evil" in general, but if you're going to pop something into the global namespace with a "distinguished" name it might be better if it were something a little more interesting. For your purposes, given your example code, the jQuery micro-template system would probably be a better approach anyway.
Related
Anybody knows what is the meaning of the $ sign before an object attribute.
For example:
pages.$page
I've seen in some javascript codes and I'm not sure if it using some kind of framework.
I've used something like this (this.$el) to access to cached element in Backbone.
Thanks in advance!
As far as javascript is concerned, $ is just another character at the beginning of a variable name, at the end of a variable name, in the middle or all by itself.
As far as some frameworks are concerned like jQuery, it's a character that the framework uses in a specific way (by convention, not because it means anything special to javascript).
For example, in jQuery $(selector) is one of the main functions in jQuery and as such it is a popular convention to assign the resulting jQuery object to a variable with a $ in it like this:
var resetButton$ = $("#reset");
This convention then indicates to the reader that the variable contains a jQuery object.
Other frameworks also use the $ sign, some in similar ways, some in other ways, but in all cases, it's just another character in javascript, but because it stands out, it's often used as a meaningful convention.
Once you become familiar with one of these types of conventions, it can make code a lot easier to read and your brain can actually recognize the meaning of the code even quicker with common, learned conventions. But, these conventions of naming variables a certain way are completely optional.
It is used to mark an element or object as a jQuery object (usually). It's a perfectly valid variable name though.
Many people use $varName to indicate that it is a jQuery variable/property
var $divs = $('div');
var nonJqueryVar = 'hello';
How do I name the HTML element objects in JS?
var divEditorArea = document.getElementById("editorarea");
var btnCheckSyntax = document.getElementById("checksyntax");
Is this a good way?
To my knowledge, there is no convention for naming HTML elements in JS. Javascript is such a diverse world that even if there was a convention, it would hardly be followed by the majority of the community. See, for example, the variety of code linters and code style conventions there are (https://www.sitepoint.com/comparison-javascript-linting-tools/).
Names should show your intentions clearly, so that code is easily understandable. I don't think that adding the type of the HTML element to the JS variable names is of much use for clarity purposes (the 'btn' and 'div' in you example), but there could be cases where it adds clarity. And, if you are in a team, you probably should follow the team's conventions.
Use your best judgement and always strive for clarity in your code.
If you use vanilla JS, as Vinicius told there is no convention for naming JS variables for HTML DOM elements.
I would name them as:
let elCheckSyntax = document.querySelector("#checksyntax");
OR
let elementEditorArea and elementCheckSyntax
another way would be some team like to prefix the DOM elements with $. So as soon as anybody in the team sees any variable prefixed with $ they know it's a DOM element.
like this
let $editorArea;
let $checkSyntax;
so, it totally depends on your convenient if you work independently and your team's naming convention
GWT outputs codes like this:
function com_mycompany_mywebapp_client_CTest_$$init__Lcom_mycompany_mywebapp_client_CTest_2V(){
this$static}
What does the $ mean, or is it just another character like an underscore? Would this_static mean the same thing?
Nuthin. It's just a character. Think of it as an S with a stick stuck through it.
The dollar sign was added to be used for machine-generated symbols so they wouldn't collide with manually written symbols. But syntactically it's just like underscore, it doesn't mean anything special.
When people discovered they could use just $() as a function name, they started to use it as a shortcut for document.getElementById() and different people extended it in different directions. Now it is often used in libraries and frameworks like Prototype or jQuery which both use $() functions in their own way (that's why you have to use jQuery.noConflict() to use both Prototype and jQuery in the same page). The dollar sign is often used in front of variable names to remember that it's a jQuery object, like this:
var $links = $('a');
But some people don't like it being used that way - eg. see the Code Conventions for the JavaScript Programming Language by Douglas Crockford.
This is sort of a meta-question. Many snippets of JavaScript I've seen here on SO are named with a dollar sign prefix (for example, $id on the second line of the snippet shown in this question). I'm not referring to jQuery or other libraries. I am well aware that this is valid, but it seems awkward to do when not necessary. Why do people name their variables like this? Is it just familiarity with a server-side language like PHP carrying over into their JavaScript code?
I thought perhaps it was to identify a variable as being a jQuery object, for example when you save the result of a selection to a variable in order to eliminate duplicate selections later on, but I haven't seen any consistent convention.
Syntactically, the dollar sign itself means nothing -- to the interpreter, it's just another character, like _ or q. But a lot of people using jQuery and other similar frameworks will prefix variables that contain a jQuery object with a $ so that they are easily identified, and thus not mixed up with things like integers or strings. You could just as easily adopt the same convention by prefixing such variables with jq_ and it would have the same effect.
In effect, it is a crude sort of Hungarian notation.
I will sometimes prefix a variable name with $ to indicate that it is a jQuery-wrapped element (most often when I'm using $(this) in a function a lot, I will assign that to $this).
Part of where the lack of convention may come from is people copy-pasting code together that uses different conventions, thus producing inconsistent code.
Also, sometimes (rarely I hope) people who program in PHP a lot will put $'s at the beginning of their variable names out of habit.
I suspect the person in that example was just copying the jQuery pattern, or is used to PHP/Perl, without really understanding that it isn't necessary and has no special meaning.
However, I have seen [experienced] programmers use it for variable names that are reserved keywords, such as $class or $this. Or even for globals. It's really a personal preference more than anything, in that case.
Namespaces were once a consideration for ECMAScript (the old ECMAScript 4) but were taken out. As Brendan Eich says in this message:
One of the use-cases for namespaces in
ES4 was early binding (use namespace
intrinsic), both for performance and
for programmer comprehension -- no
chance of runtime name binding
disagreeing with any earlier
binding. But early binding in any
dynamic code loading scenario like
the web requires a prioritization or
reservation mechanism to avoid early
versus late binding conflicts.
Plus, as some JS implementors have
noted with concern, multiple open
namespaces impose runtime cost unless
an implementation works
significantly harder.
For these reasons, namespaces and
early binding (like packages before
them, this past April) must go.
But I'm not sure I understand all of that. What exactly is a prioritization or reservation mechanism and why would either of those be needed? Also, must early binding and namespaces go hand-in-hand? For some reason I can't wrap my head around the issues involved. Can anyone attempt a more fleshed out explanation?
Also, why would namespaces impose runtime costs? In my mind I can't help but see little difference in concept between a namespace and a function using closures. For instance, Yahoo and Google both have YAHOO and google objects that "act like" namespaces in that they contain all of their public and private variables, functions, and objects within a single access point. So why, then, would a namespace be so significantly different in implementation? Maybe I just have a misconception as to what a namespace is exactly.
For the sake of the bounty I'd like to know two things:
Does a namespace need early binding?
How does a namespace implementation
differ from an object with
private members?
If you declare a variable within a closure after a definition of a function will call that variable, it still uses the scoped variable.
function ShowMe() {
alert(myVar); //alerts "cool"
}
var myVar = "cool";
This process would get another layer of complicated with regards to namespacing.
Beyond this there are numerous namespace methods along with expand/applyIf etc that can do a lot of the same functionality. namespace() in ExtJS, or $.extend in jQuery for example. So, it may be a nice to have, but isn't an absolute need within the constructs of the language. I think that formalizing some of the extensions for Array, and support for ISO-8601 dates in Date are far more important myself. Over having to simply check each namespace layer for definition...
window.localization = $.extend(window.localization || {}, {
...
});
window.localization.en = $.extend(window.localization.en || {}, {
...
});
OK first Some of the terminology:
Early binding -- check/validate when the line of code is parsed.
Late binding -- check/validate when the line of code is executed.
Prioritisation/reservation --I think they mean if you do early binding and check the name spaces as the code is parsed there must be a process to validate a variable name when the variable is added dynamically later on and a different set of rules for what is valid as there may be several scopes involved at this point.
I am frankly surprised that only these quite technical reasons were given. Take the common case:-
onclick=' var mymark = "donethat";'
What namespace should "mymark" belong to? There doesnt seem to be any easy answer to that question. Especially given that the code snippet:-
window.forms.myform.mybutton.onClick = ' var mymark = "donethat";'
Should put the variable in the same name space.