Naming conventions - HTML elements in JS - javascript

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

Related

Using Script Tags As A Template System

** Revised **
I made this basic example which I believe is evicence that JavaScript may be useful as it's own template engine:
http://jsfiddle.net/julienetienne/u6akrx7j/
<script>talk[0].text('Hello World!');</script>
It's just a simple example but as you can see there are many possibilities eg.
It doesn't necessarily have to detect the tag nodes in that manner, it could do it by class, id. It is also possible to obtain the script node of the function,
you could simply print variables like p('Page Title');
A self closing list of elements could be similar to e.g. li('', menu);
And you could clearly build up other complex data sets as you can with any other common template engine.
Before this edit I made the mistake of comparing it to PHP. I'm actually considering it more of an alternative to e.g. handlebars, underscore, moustache, dust and similar.
But before I get to excited I would really like to know if there are any issues in regards to using in this way. (I'm not concerned with novice best practices).
The benefits of an organic template system seems quite apparent. The biggest advantage is that there is no syntax to learn and it's cleaner than seeing %{{foobar}}% like markings.
Considering my example is just a tiny minimalistic concept, please tell me the drawbacks of a system like this compared to common template engines.
Thanks
It looks like it's a PHP-style templating system, but it is apparently not:
In the fiddle the script parts could be written anywhere in the page.
The part that defines the position of the texts to be inserted into the DOM is defined by the line var talk = document.getElementsByTagName('div'); and the structure of the HTML.
If you'd use more div than the ones already there the texts will appear at a totally different (and supposedly wrong) position.
The disavantage will thus be, that you can't use the system independently of the underlying markup. That makes it different from a use case in PHP, where you can echo the variables by defining their position in the markup.
Have a look at Angular or similar front end frameworks, if you are looking for a way how to implement a templating system.

Should you use named functions when developing a JavaScript library?

For example:
module.exports = {
myLibraryFunction: function myLibraryFunction() {
...
}
}
The disadvantage is obvious. It's not very DRY, which means it can easily become out-of-sync if you're not careful. It also makes your code a little more verbose.
So what are the advantages? Is the tradeoff worth it?
I use this approach when writing JS libraries. The largest advantage is that tools like the Chrome debugger will have a definite name for your function as opposed to either "anonymous" or some name composed of the function path based on the variable names containing the function. If, however, you don't care about having method names when debugging, then it really comes down to a matter of taste. If you were to minify the resulting JS code, naming elements like that would get stripped out anyway.
As far as to how DRY this approach is, consider that the repeated names occur right next to each other. A quick copy & paste is all it takes to keep them in sync. It would be nice if a JS included a feature that causes a function to be named according to the variable it has been assigned to at the point of creation (or at least the ability to dynamically re-assign the function's name). Sadly, however, this is the only way JS allows for us to name these otherwise anonymous functions.

Javascript "$" meaning before a variable or namespace

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';

Javascript: $$ Global Variable Considered Evil?

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.

What is the best-practice casing style for javascript? Why?

One aspect of javascript that it's hard to find information on is casing practices. By casing practices, I mean what casing style (ie. camel-case, pascal-case, etc) should be used for what elements (Constructors, private functions, public functions).
The only rule I've heard was from a Douglas Crockford lecture on YUI theater, stating that constructors should be the only functions that start with an uppercase letter.
Beyond that there doesn't seem to be many casing standards that people follow in javascript.
Does anyone know any casing best practices for javascript, and why it's reasonable to use them?
Also do you follow a casing style with your .js files?
I prefer PascalCase for constructors and camelCase for everything else. That's the style that JS standard library uses and well... every JS framework I've seen so far :)
And I use all_lowercase naming convention for all files served from web. There are some case-insensitive file systems out there.
The core language uses InitialCaps for constructors (e.g. Object, Date, Number, RegExp) and camelCase for methods and properties (e.g. something.toString(), quantity.valueOf(), regexp.ignoreCase). This convention is also followed in the DOM specifications and implementations (e.g. HTMLElement.setAttribute()). So it makes the most sense to adopt the same convention, or you finish up with a horrendous mishmash of styles like:
var number_of_fish_requested = document.getElementById("fish").value;
var fish_count = parseInt(number_of_fish_requested, 10);
which just becomes utterly confusing, not only to type but, much more importantly, to read.
(You spend more time reading code, trying to debug or modify it, than you ever do writing it in the first place.)
What I have seen so far is a very large diversity of casing standards.
As far as I'm concerned, I use C# styling for writing my JavaScript code. I use classes a lot (well functions as classes, and usually don't have independent functions.)
So, I use PascalCase for class names, public methods, properties and all global variables and camelCase for arguments, local variables and private functions. This somehow reflects my common environment, helping to distinguish the variable scopes.
I also tend to keep my class functions in a separate file with the same name as my ClassName (ClassName.js, ClassName.min.js).
This was about my approach.
I also noticed that Java programmers, follow the Java rules (and the writing style resembles the Java language.) Ruby on Rails programmers follow their own naming standards such as underscore_separated_var_name.
Further, as you mentioned, there is a tendency to use pascalCase a lot in naming in very popular frameworks whose authors come from different communities like Linux/Open source community and Microsoft developers (jQuery, knockout.js, JSJaC, etc.)
I should note that none of these methods are wrong or right, when it comes to JS. The primary purpose of your naming conventions and file structuring is the readability. If you are consistent then you in future and your fellow developers will quickly understand and get on with your code.
I prefer camelCase for everything except for constructors. The reason (and I believe this is why Mr. Crockford suggested this as well) is because in other languages, such as Java, the convention is capitalize your classes, which is what constructors are used for.
That is my $0.02.
All lower case with underscore separators is the easiest to read; it follows natural language. "Best" will get you in to a holy war; the reality is case doesn't matter as much as other design issues but it's an easy topic to polarize.
ALongButNotReallyReadableIdentifier
an_even_longer_but_completely_readable_identifier
The accepted answer is true but there are some exceptions.
In window.JSON and window.XMLHttpRequest the term is capitalized.
Also most people use PascalCase for enum type objects in Javascript and capitalized values within. Sometimes namespaces are done in PascalCase also.
example:
MyCompany.Web.UI.MyComponent.ThemeOption = { BLACK: 0, SILVER: 1, BLUE: 2}

Categories