Can I use Capital letter for in javascript - javascript

Can i write something like this
class Person{
testMethod(){
return true;
}
}
var People = new Person();
console.log(People.testMethod());
can i initialize with Capital Letter for class instance ?

Yes, you can. But it is not a standard way of naming your instance variables as it makes readability poor. If a third person reads your code, he/she would like to expect the Class names starting with Capital letters and instance variables with small letters.
Here is a list of naming conventions that should be followed as a good practice. https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Coding_Style

Yes you can! But the standard in Javascript is that capital letter are for Classes or constructor functions! And camel case for variables and functions!
I really recommend you to use ESlint to force you to follow some code style! Also I recommend Standard JS rules: https://standardjs.com/ (probably the most used code style)

Class name conventions
Class, interface, record, and typedef names are written in UpperCamelCase. Unexported classes are simply locals: they are not marked #private and therefore are not named with a trailing underscore.
Type names are typically nouns or noun phrases. For example, Request, ImmutableList, or VisibilityMode. Additionally, interface names may sometimes be adjectives or adjective phrases instead (for example, Readable).
Rules common to all identifiers -
Identifiers use only ASCII letters and digits, and, in a small number of cases noted below, underscores and very rarely (when required by frameworks like Angular) dollar signs.
Give as descriptive a name as possible, within reason. Do not worry about saving horizontal space as it is far more important to make your code immediately understandable by a new reader. Do not use abbreviations that are ambiguous or unfamiliar to readers outside your project, and do not abbreviate by deleting letters within a word.
priceCountReader // No abbreviation.
numErrors // "num" is a widespread convention.
numDnsConnections // Most people know what "DNS" stands for.
n // Meaningless.
nErr // Ambiguous abbreviation.
nCompConns // Ambiguous abbreviation.
wgcConnections // Only your group knows what this stands for.
pcReader // Lots of things can be abbreviated "pc".
cstmrId // Deletes internal letters.
kSecondsPerDay // Do not use Hungarian notation.

Related

Is ECMAScript case sensitive?

I understand that JavaScript (the language that implements the spec) is case sensitive. For example, variable names:
let myVar = 1
let MyVar = 2 // different :)
I haven't been able to find anything in the spec itself that indicates that this is a requirement, so I'm not sure if that was just a design decision independent of the spec.
I think I found something that specifies this. Names and Keywords says:
Two IdentifierNames that are canonically equivalent according to the Unicode standard are not equal unless, after replacement of each UnicodeEscapeSequence, they are represented by the exact same sequence of code points.
Since uppercase and lowercase letters have different code points, identifiers with different case are not equal.
Yes it is case sensitive but generally JavaScript developers follow camel case convention.

Why getElementById in that word? g is small and e and i word is capital?

doucument.getElementById("xyz").value;
this this statement why we write get in small and element word staring form capital word E same as B And I
It's called Camel Case and it's just a styling/naming convention
It's called lowerCamelCase. This is just writing style.
Java naming convention dictates the following: "Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized." - from https://www.oracle.com/technetwork/java/codeconventions-135099.html
So in short, it's like that because convention dictates it should be.
Because as it called camelCase and it is one of the Javascript coding conventions, here's a list of other style Coding Conventions from w3school.
js_conventions

JavaScript RegExp: R naming conventions

We're all familiar with naming conventions in R (if not: Venables & Smith - Introduction to R, Chapter 1.8). Regular expressions, on the other hand, remain terra incognita and the most hated part in my programming life so far ... Recently, I've officially started JavaScript recapitulation, and I'm trying to create precise RegExp to check correct R object name.
Brief intro:
Object names must start with . or lower/uppercase letter, and if they start with . cannot continue with numeric... afterward, alphanumeric symbols are allowed with . and underscore _.
Long story short, here's my JS code:
var txt = "._.";
var inc = /^\.(?!\d)|^[a-z\.]/i;
document.write(inc.test(txt));
This approach manages the first part (. and/or lower/upper case and numeric after .), but I cannot pass something like & [\w\.]. I can write a function that will take care of this one, but is it at all possible to manage this with a single RegExp?
I'm not familiar with R or its naming conventions, but I'll give it a shot:
If you're only trying to verify that the name begins correctly, all you need to do is remove the \. from the character class, leaving you with: /^\.(?!\d)|^[a-z]/i. Otherwise, the . may still be the first character with no restrictions on the remaining ones.
If you want to verify the that entire name is correct, something like this should work:
/^(?:\.(?!\d)|[a-z])[a-z0-9_\.]+$/i

Javascript and CSS, using dashes

I'm starting to learn some javascript and understand that dashes are not permitted when naming identifiers. However, in CSS it's common to use a dash for IDs and classes.
Does using a dash in CSS interfere with javascript interaction somehow? For instance if I were to use getElementByID("css-dash-name"). I've tried a few examples using getElementByID with dashes as a name for a div ID and it worked, but I'm not sure if that's the case in all other contexts.
Having dashes and underscores in the ID (or class name if you select by that) that won't have any negative effect, it's safe to use them. You just can't do something like:
var some-element = document.getElementByID('css-dash-name');
The above example is going to error out because there is a dash in the variable you're assigning the element to.
The following would be fine though since the variable doesn't contain a dash:
var someElement = document.getElementByID('css-dash-name');
That naming limitation only exists for the javascript variables themselves.
It's only in the cases where you can access the elements as properties that it makes a difference. For example form fields:
<form>
<input type="text" name="go-figure" />
<input type="button" value="Eat me!" onclick="...">
</form>
In the onclick event you can't access the text box as a property, as the dash is interpreted as minus in Javascript:
onclick="this.form.go-figure.value='Ouch!';"
But you can still access it using a string:
onclick="this.form['go-figure'].value='Ouch!';"
Whenever you have to address a CSS property as a JavaScript variable name, CamelCase is the official way to go.
element.style.backgroundColor = "#FFFFFF";
You will never be in the situation to have to address a element's ID as a variable name. It will always be in a string, so
document.getElementById("my-id");
will always work.
Using Hypen (or dash) is OK
I too is currently studying JavaScript, and as far as I read David Flanagan's book (JavaScript: The Definitive Guide, 5th Edition) — I suggest you read it. It doesn't warn me anything about the use of hypen or dash (-) in IDs and Classes (even the Name attribute) in an HTML document.
Just as what Parrots already said, hypens are not allowed in variables, because the JavaScript interpreter will treat it as a minus and/or a negative sign; but to use it on strings, is pretty much ok.
Like what Parrots and Guffa said, you can use the following ...
[ ] (square brackets)
'' (single quotation marks or single quotes)
"" (double quotation marks or double quotes)
to tell the JavaScript interpreter that your are declaring strings (the id/class/name of your elements for instance).
Use Hyphen (or dash) — for 'Consistency'
#KP, that would be ok if he is using HTML 4.1 or earlier, but if he is using any versions of XHTML (.e.g., XHTML 1.0), then that cannot be possible, because XHTML syntax prohibits uppercase (except the !DOCTYPE, which is the only thing that needs to declared in uppercase).
#Choy, if you're using HTML 4.1 or earlier, going to either camelCase or PascalCase will not be a problem. Although, for consistency's sake as to how CSS use separators (it uses hypen or dash), I suggest following its rule. It will be much more convinient for you to code your HTML and CSS alike. And moreoever, you don't even have to worry if you're using XHTML or HTML.
IDs are allowed to contain hyphens:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
And there is no restriction when using IDs in JavaScript except if you want to refer to elements in the global scope. There you need to use:
window['css-dash-name']
Other answers are correct as far as where you can and can't use hyphens, however at the root of the question, you should consider the idea of not using dashes/hyphens in your variable/class/ID names altogether. It's not standard practice, even if it does work and requires careful coding to make use of it.
Consider using either PascalCase (all words begin in capital) or camelCase (first word begins in lowercase, following words being in uppercase). These are the two most common, accepted naming conventions.
Different resources will recommend different choices between the two (with the exception of JavaScript which is pretty much always recommended camelCase). In the end as long as you are consistent in your approach, this is the most important part. Using camel or Pascal case will ensure you don't have to worry about special accessors or brackets in your code.
For JavaScript conventions, try this question/discussion:
javascript naming conventions
Here's another great discussion of conventions for CSS, Html elements, etc:
What's the best way to name IDs and classes in CSS and HTML?
It would cause an error in this case:
const fontSize = element.style.font-size;
Because including a hyphen prevents the property from being accessed via the dot operator. The JavaScript parser would see the hyphen as a subtraction operator. Correct way would be:
const fontSize = element.style['font-size']
No, this won't cause an issue. You're accessing the ID as a string (it's enclosed in quotes), so the dash poses no problem. However, I would suggest not using document.getElementById("css-dash-name"), and instead using jQuery, so you can do:
$("#css-dash-name");
Which is much clearer. the jQuery documentation is also quite good. It's a web developers best friend.

What is the purpose of the dollar sign in JavaScript?

The code in question is here:
var $item = $(this).parent().parent().find('input');
What is the purpose of the dollar sign in the variable name, why not just exclude it?
A '$' in a variable means nothing special to the interpreter, much like an underscore.
From what I've seen, many people using jQuery (which is what your example code looks like to me) tend to prefix variables that contain a jQuery object with a $ so that they are easily identified and not mixed up with, say, integers.
The dollar sign function $() in jQuery is a library function that is frequently used, so a short name is desirable.
In your example the $ has no special significance other than being a character of the name.
However, in ECMAScript 6 (ES6) the $ may represent a Template Literal
var user = 'Bob'
console.log(`We love ${user}.`); //Note backticks
// We love Bob.
The dollar sign is treated just like a normal letter or underscore (_). It has no special significance to the interpreter.
Unlike many similar languages, identifiers (such as functional and variable names) in Javascript can contain not only letters, numbers and underscores, but can also contain dollar signs. They are even allowed to start with a dollar sign, or consist only of a dollar sign and nothing else.
Thus, $ is a valid function or variable name in Javascript.
Why would you want a dollar sign in an identifier?
The syntax doesn't really enforce any particular usage of the dollar sign in an identifier, so it's up to you how you wish to use it. In the past, it has often been recommended to start an identifier with a dollar sign only in generated code - that is, code created not by hand but by a code generator.
In your example, however, this doesn't appear to be the case. It looks like someone just put a dollar sign at the start for fun - perhaps they were a PHP programmer who did it out of habit, or something. In PHP, all variable names must have a dollar sign in front of them.
There is another common meaning for a dollar sign in an interpreter nowadays: the jQuery object, whose name only consists of a single dollar sign ($). This is a convention borrowed from earlier Javascript frameworks like Prototype, and if jQuery is used with other such frameworks, there will be a name clash because they will both use the name $ (jQuery can be configured to use a different name for its global object). There is nothing special in Javascript that allows jQuery to use the single dollar sign as its object name; as mentioned above, it's simply just another valid identifier name.
The $ sign is an identifier for variables and functions.
https://web.archive.org/web/20160529121559/http://www.authenticsociety.com/blog/javascript_dollarsign
That has a clear explanation of what the dollar sign is for.
Here's an alternative explanation: http://www.vcarrer.com/2010/10/about-dollar-sign-in-javascript.html
Dollar sign is used in ecmascript 2015-2016 as 'template literals'.
Example:
var a = 5;
var b = 10;
console.log(`Sum is equal: ${a + b}`); // 'Sum is equlat: 15'
Here working example:
https://es6console.com/j3lg8xeo/
Notice this sign " ` ",its not normal quotes.
U can also meet $ while working with library jQuery.
$ sign in Regular Expressions means end of line.
When using jQuery, the usage of $ symbol as a prefix in the variable name is merely by convention; it is completely optional and serves only to indicate that the variable holds a jQuery object, as in your example.
This means that when another jQuery function needs to be called on the object, you wouldn't need to wrap it in $() again. For instance, compare these:
// the usual way
var item = $(this).parent().parent().find('input');
$(item).hide(); // this is a double wrap, but required for code readability
item.hide(); // this works but is very unclear how a jQuery function is getting called on this
// with $ prefix
var $item = $(this).parent().parent().find('input');
$item.hide(); // direct call is clear
$($item).hide(); // this works too, but isn't necessary
With the $ prefix the variables already holding jQuery objects are instantly recognizable and the code more readable, and eliminates double/multiple wrapping with $().
No reason. Maybe the person who coded it came from PHP. It has the same effect as if you had named it "_item" or "item" or "item$$".
As a suffix (like "item$", pronounced "items"), it can signify an observable such as a DOM element as a convention called "Finnish Notation" similar to the Hungarian Notation.
I'll add this:
In chromium browser's developer console (haven't tried others) the $ is a native function that acts just like document.querySelector most likely an alias inspired from JQuery's $
Here is a good short video explanation: https://www.youtube.com/watch?v=Acm-MD_6934
According to Ecma International Identifier Names are tokens that are interpreted according to the grammar given in the “Identifiers” section of chapter 5 of the Unicode standard, with some small modifications. An Identifier is an IdentifierName that is not a ReservedWord (see 7.6.1). The Unicode identifier grammar is based on both normative and informative character categories specified by the Unicode Standard. The characters in the specified categories in version 3.0 of the Unicode standard must be treated as in those categories by all conforming ECMAScript implementations.this standard specifies specific character additions:
The dollar sign ($) and the underscore (_) are permitted anywhere in an IdentifierName.
Further reading can be found on: http://www.ecma-international.org/ecma-262/5.1/#sec-7.6
Ecma International is an industry association founded in 1961 and dedicated to the standardization of Information and Communication Technology (ICT) and Consumer Electronics (CE).
"Using the dollar sign is not very common in JavaScript, but
professional programmers often use it as an alias for the main
function in a JavaScript library.
In the JavaScript library jQuery, for instance, the main function $
is used to select HTML elements. In jQuery $("p"); means "select all
p elements". "
via https://www.w3schools.com/js/js_variables.asp
I might add that using it for jQuery allows you to do things like this, for instance:
$.isArray(myArray);
let $ = "Hello";
let $$ = "World!";
let $$$$$$$$$$$ = $ + " " + $$;
alert($$$$$$$$$$$);
This displays a "Hello World!" alert box.
As you can see, $ is just a normal character as far as JavaScript identifiers or variable names go. In fact you can use a huge range of Unicode characters as variable names that look like dollar or other currency signs!
Just be careful as the $ sign is also used as a reference to the jQuery namespace/library:
$("p").text("I am using some jquery");
// ...is the same as...
jQuery("p").text("I am using some jquery");
$ is also used in the new Template Literal format using string interpolation supported in JavaScript version ES6/2015:
var x = `Hello ${name}`;

Categories

Resources