correct function parameters designation - javascript

Every time i pass some parameters to a JavasScript or jQuery functon, i use some random letters. What are the correct letters for the corresponding variable types?
function(o){} for example is for a object. But what are the other letters? Do someone have a list of those?

I advise you not to assign names according to types but according to the data that the variable contain. If you pass an object that contains the configuration for a function call the variable configuration if you pass a variable that contains a name call it name and so on. In this way the code is more readable and understandable.

Any letter will do, there is no such thing as a standard for using letters as parameters.
However, using letters for parameters is bad practise, because a letter does not describe what the parameter is intended for.
Consider this example:
function ShowBusyCursor(s) {
//...
}
If you look at the function header, you cannot guess what the parameter s stands for. But if you change the code to this:
function ShowBusyCursor(cursorIsDisplayed) {
//...
}
The parameter cursorIsDisplayed is a lot more developer-friendly and tells you it's a boolean that can be set to true to display the cursor. If you used s, you would have to look into the code to figure that out.

Here is a good list of letters I could think of:
o - object
a - array
s - string
d - date
n - number
r - regexp
b - boolean
But seriously, jokes apart, I think you might be mixing up the packed/minified source with the actual source that developers write. For example, this little function looked like this originally:
function myFunction(personName) {
this.name = personName;
}
But after minifying, it becomes:
function myFunction(a){this.name=a}
packer is one such utility by Dean Edwards that will minify your Javascript. Play with your source code at this website and see the compressed output. Check the Shrink variables option on the right to see how parameters and other variables get renamed.
This however shouldn't affect how you write your code at all. Be it Javascript, or any other language, all identifiers - variables, function names, class names, etc. should be named after what they represent or do rather than obscure shorthands.

Re-iterating what mck89 said, it's better to go with explanatory variable names rather than just a letter for the type. What if you have more than one parameter of the same time, do you start appending numbers?
I have often seen explanatory variable names which include the type, for instance sFirstName would be a string denoted by the "s", bForce would be a boolean, oConfig would be an object and nSubTotal would be a number.

This is a variation of Hungarian notation, and I'd advise against using single-letter variable names. What if you need to pass in 2 of any one data type? Like others have said, it also doesn't represent the meaning of the variable very well. I think this is much better:
function foo(sFirstName, sLastName)
{
alert("Hi, my name is " + sFirstName + " " + sLastName);
}

Related

How can I set the default data type on javascript?

I wanna set the javascript data type on my vars.
ex:
var friends = {
name: String(),
age: Number(),
classmate: Boolean()
};
Is this right?
It works on the browsers. but I can't be certain. cause, below works too.
var friends = {
name: '',
age: 0,
classmate: false
};
I want to know if these things are right or not or good or bad.
both are right but the right way is to assign the type first, it will strictly followed while executing script and initial time of assign values to variable.
Javascript is a weakly typed language, so this isn't doing anything for you. You do not need to declare the type of variables and you gain no protection by specifying a type when you initialize them. If you need strong typing, I would consider TypeScript; otherwise, I would enjoy not having to deal with them.
First, javascript variables and properties are dynamic - they can take any values of any datatype. What you are actually doing in your example is some sort of casting.
var friends = {
index1: Number("12"),
index2: String("12")
};
If it's a good or bad thing to initialize your variables such way really depends on your requirements. If you want to ensure that the value of each variable is consistent all through out the scope (and prevent any exceptions or unwanted results), then I guess it would be a good practice for you.
Take for instance.
var sum = friends.index1 + friends.index2;
console.log(sum);
The result is "1212" and not 24. Hopefully this makes sense to you.
There are other ways to ensure that the value is of type that you expected. You can check it using typeof. Through this, you may no longer have to cast or "specify" the datatype during variable initialization.
if( typeof friends.index1 == "number" ) ...
In javascript values have a data type but variables don't. There is no mechanism to define the type of a variable and you can store any kind of value into an existing variable. (In some languages this kind of weak typed variable is called a variable of variant type).
For you information, ECMA script 2015 (ES6) introduced typed arrays that allow you to view a binary array buffer as an array of different length integer and floating point numbers. This is not specifically related to the wording of your question however, and is not the same as having typed variables.
Note the first example in the post does not give variables a data type. After
var friends = {
name: String(),
age: Number(),
classmate: Boolean()
};
object property name contains a zero length string object, age contains 0 and classmate contains false, but you can reset them to anything afterwards.

What's the difference between str.fun() / str.fun / fun(str) in JavaScript?

I tried googling but couldn't find a precise answer, so allow me to try and ask here. If the question does not seem proper, please let me know and I'll delete it.
In JS you've got three different way of writing certain build in functionalities:
str.length
str.toString()
parseInt(str)
I wonder if there is a reason behind these different ways of writing. As a new user I don't grasp why it couldn't be streamlined as: length(str) / toString(str) / parseInt(str) or with dot formulation.
I however think if I do know the reason behind these differences, it would give me a better understanding of JavaScript.
Length is one of the attributes of string in JavaScript. Hence you use string.length to get the length of the string.
toString is a function for string objects, hence we use stringobj.toString().
parsInt(str) is a global function which takes string as a parameter.
JavaScript is object-oriented, so there are functions or procedures which require first an object to use as this in their bodies. str.length is a property, both syntactically and semantically. It doesn't require any parameters and represents some quality of the object. obj.toString() is a method (a function attached to an object), which doesn't represent any characteristics of the object, but rather operates on its state, computes some new values, or changes the state of the object a lot. parseInt(str) is a "global" function, which represents an operation not attached to any type or object.
Under the hood, these three ways may be well implemented with just calling a function, passing this as the first parameter (like C# does, for example). The semantic difference is the important one.
So why not use just the third syntax, like for example PHP does? First, it doesn't bloat the global environment with lots of functions which only work for one specific case and type, allowing you to specify any new function you want without breaking the old functionality. Second, it ecourages you to use object-oriented concepts, because you can already see working objects and methods in the language, and can try to make something similar.
And why isn't parseInt a method? It can as well be str.toInt() without any issues, it's just the way JavaScript designers wanted it to be, although it seems also a bit logical to me to make it a static method Number.parseInt(str), because the behaviour of the function is relevant more to the Number type than the String type.
JavaScript is based around objects. Objects have properties (e.g. a User object may have name and age properties). These are what define the user and are related to the user. Properties are accessed via dot-notation or brackets notation (to access Eliott’s age, we’ll use either eliott.age or eliott['age'] — these are equivalent).
These properties can be of any type — String, Number, Object, you name it — even functions. Now the proper syntax to call a function in JS is to put round brackets: eliott.sayHello(). This snippet actually fetches Eliott’s sayHello property, and calls it right away.
You can see Eliott as a box of properties, some of which can be functions. They only exist within the box and have no meaning out of the box: what would age be? Whose age? Who’s saying hello?
Now some functions are defined at the global level: parseInt or isNaN for instance. These functions actually belong to the global box, named window (because legacy). You can also call them like that: window.parseInt(a, 10) or window.isNaN(a). Omitting window is allowed for brevity.
var eliott = {
name: 'Eliott',
age: 32,
sayHello: function () { console.log('Hello, I’m Eliott'); }
};
eliott.name; // access the `name` property
eliott.age; // access the `age` property
eliott.sayHello; // access the `sayHello` property
eliott.sayHello(); // access the `sayHello` property and calls the function
sayHello(eliott); // Reference error: `window.sayHello` is undefined!
Note: Some types (String, Number, Boolean, etc.) are not real objects but do have properties. That’s how you can fetch the length of a string ("hello".length) and reword stuff ("hello, Eliott".replace("Eliott", "Henry")).
Behaviour of these expressions is defined in ECMAScript grammar. You could read the specification to understand it thoroughly: ECMAScript2015 specification. However, as pointed out by Bergi, it's probably not the best resource for beginners because it doesn't explain anything, it just states how things are. Moreover I think it might be too difficult for you to be able to grasp concepts described in this specification because of the very formal language used.
Therefore I recommend to start with something way simpler, such as a very basic introduction to JavaScript: JavaScript Basics on MDN. MDN is a great resource.
But to answer your question just briefly:
str.length is accessing a property of the str object.
parseInt(str) is a function call
str.toString() is a call of a function which is a property of the str object. Such functions are usually named methods.
Functions and methods are in fact very similar but one of the differences (except for the obvious syntax difference) is that methods by default have context (this) set to refer to the object which they're part of. In this case inside of toString function this equals to str.
Note: Accessing a property (as in str.length) could in effect call a getter function but it depends on how the object is defined, and is in fact transparent for the user.

Use string variable to access value of object

I have a text input.
I want the user to be able to fill out a value in that text input like some of these examples:
results[0].address_components[0].long_name
results[0].formatted_address
fo.o[0].bar (where fo.o is a single key)
etc. (pretty much literally anything)
Then I want to take that value and use it as a key on some parsed JSON. So like...
$.parseJSON('data.json').results[0].address_components[0].long_name would return something like San Francisco.
How can I do this?
If I save the input value as a variable, say selector, and then try $.parseJSON('data.json')[selector] it just comes back undefined.
If I try to regex the selector and convert all instances of [ into . and remove all ] and split at . then reduce, then selectors like fo.o (one key) will break...
Thanks in advance!
You should generally set the results of parseJSON to a variable, rather than parse it every time you access it. parseJSON is generally going to go down to C code (depending on the environment), but it will still be really inefficient to call it over and over.
var res = $.parseJSON('data.json');
From there, you can access it like you would any other JavaScript object:
res.results, which is identical to res["results"] (which, in your case appears to be some kind of array).
A string key with special characters (., -, and pretty much anything non a-zA-Z0-9) is always accessed via the second form: res["fo.o"].
Note that this chains, so you can access res["fo.o"]["bar"] exactly as you'd address res["fo.o"].bar.
I would recommend using a JavaScript library like lodash for this (if this is feasible in your project, otherwise looking at its implementation might help):
It provides a large set of utility functions. The get function does exactly what you are looking for, namely it resolves a path on an object.
Sample code (assuming _ is your lodash reference):
var path = 'results[0].address_components[0].long_name'; // the user input
var data = $.parse('data.json');
var result = _.get(data, path); // resolves the path on the data object
As for the fo.o property name, I doubt there would be an easy solution, as this essentially makes your syntax ambiguous. How would you distinguish between a property fo.o and fo?
use eval. You would put everything as a string. So just concatenate strings based on the input. Then eval it. for example:
var str = "$.parseJSON('data.json').results[0].address_components[0].long_name";
and then eval it at runtime.
var result = eval(str);

Does concatenation create garbage?

I did search this info on the web, some say yes because javascript must create a new string object to store the result of the concatenation, some say no because string objects are not collected.
Maybe it depends on the context. For example, if I had an array of objects like
animals["blue_dog","red_dog","yellow_cat","red_bird","green_bird"...]
and I had a function with animal and color arguments, in this function I would access my object like this:
animals[animal+"_"+color].
Most of the time I do concatenations when drawing text, which obviously doesn't happen a lot of times per frame. So even if it becomes garbage, it is insignificant. But when using a concatenation as an object's key, because of loops this concatenation could happen a thousand times per frame, and then this may become a problem.
Doing something like animals[color + "_" + animal] creates a temporary value for accessing the object. That temporary will be collected either by the garbage collector or at the end of the block/function call (implementation dependent).
My assumption (based on my own experience in working with compilers) is that since the result isn't stored in a variable, it will be placed on the stack and released once the function completes. But, again, this depends on how the engine is written.
I'm in no way an expert on compilers.
May or may not, depends on how optimal is the compiler.
This a + b + c is (a + b) + c so you have two concatenations. Result of (a + b) will be a temporary object (string here). That temporary is a garbage.
For the given expression this form a.concat(b,c) is conceptually better. It in principle does not require intermediate temporaries.
In my experience, concatenating strings can definitely produce garbage. I had a scenario where I had a lot of cells in a large table and each cell could have a different css class (from a set of combinations of maybe 30 different combinations) assigned. Doing this the normal way:
const class = group + empty + active;
Would produce a lot of garbage. I created a memoized function that received a bitmask as argument which would produce the class string and got rid of the garbage that way.
This reply is an excellent list of what to avoid:
https://stackoverflow.com/a/18411275

Do such AngularJS functions or variables of $promise and $checkSessionServer exist or still exist? [duplicate]

This question already has answers here:
What is the purpose of the dollar sign in JavaScript?
(12 answers)
Closed 2 years ago.
I quite often see JavaScript with variables that start with a dollar sign. When/why would you choose to prefix a variable in this way?
(I'm not asking about $('p.foo') syntax that you see in jQuery and others, but normal variables like $name and $order)
Very common use in jQuery is to distinguish jQuery objects stored in variables from other variables.
For example, I would define:
var $email = $("#email"); // refers to the jQuery object representation of the dom object
var email_field = $("#email").get(0); // refers to the dom object itself
I find this to be very helpful in writing jQuery code and makes it easy to see jQuery objects which have a different set of properties.
In the 1st, 2nd, and 3rd Edition of ECMAScript, using $-prefixed variable names was explicitly discouraged by the spec except in the context of autogenerated code:
The dollar sign ($) and the underscore (_) are permitted anywhere in an identifier. The dollar sign is intended for use only in mechanically generated code.
However, in the next version (the 5th Edition, which is current), this restriction was dropped, and the above passage replaced with
The dollar sign ($) and the underscore (_) are permitted anywhere in an IdentifierName.
As such, the $ sign may now be used freely in variable names. Certain frameworks and libraries have their own conventions on the meaning of the symbol, noted in other answers here.
As others have mentioned the dollar sign is intended to be used by mechanically generated code. However, that convention has been broken by some wildly popular JavaScript libraries. JQuery, Prototype and MS AJAX (AKA Atlas) all use this character in their identifiers (or as an entire identifier).
In short you can use the $ whenever you want. (The interpreter won't complain.) The question is when do you want to use it?
I personally do not use it, but I think its use is valid. I think MS AJAX uses it to signify that a function is an alias for some more verbose call.
For example:
var $get = function(id) { return document.getElementById(id); }
That seems like a reasonable convention.
I was the person who originated this convention back in 2006 and promoted it on the early jQuery mailing list, so let me share some of the history and motivation around it.
The accepted answer gives this example:
var $email = $("#email"); // refers to the jQuery object representation of the dom object
var email_field = $("#email").get(0); // refers to the dom object itself
But that doesn't really illustrate it well. Even without the $, we would still have two different variable names here, email and email_field. That's plenty good right there. Why would we need to throw a $ into one of the names when we already have two different names?
Actually, I wouldn't have used email_field here for two reasons: names_with_underscores are not idiomatic JavaScript, and field doesn't really make sense for a DOM element. But I did follow the same idea.
I tried a few different things, among them something very similar to the example:
var email = $("#email"), emailElement = $("#email")[0];
// Now email is a jQuery object and emailElement is the first/only DOM element in it
(Of course a jQuery object can have more than one DOM element, but the code I was working on had a lot of id selectors, so in those cases there was a 1:1 correspondence.)
I had another case where a function received a DOM element as a parameter and also needed a jQuery object for it:
// email is a DOM element passed into this function
function doSomethingWithEmail( email ) {
var emailJQ = $(email);
// Now email is the DOM element and emailJQ is a jQuery object for it
}
Well that's a little confusing! In one of my bits of code, email is the jQuery object and emailElement is the DOM element, but in the other, email is the DOM element and emailJQ is the jQuery object.
There was no consistency and I kept mixing them up. Plus it was a bit of a nuisance to keep having to make up two different names for the same thing: one for the jQuery object and another for the matching DOM element. Besides email, emailElement, and emailJQ, I kept trying other variations too.
Then I noticed a common pattern:
var email = $("#email");
var emailJQ = $(email);
Since JavaScript treats $ as simply another letter for names, and since I always got a jQuery object back from a $(whatever) call, the pattern finally dawned on me. I could take a $(...) call and just remove some characters, and it would come up with a pretty nice name:
$("#email")
$(email)
Strikeout isn't perfect, but you may get the idea: with some characters deleted, both of those lines end up looking like:
$email
That's when I realized I didn't need to make up a convention like emailElement or emailJQ. There was already a nice convention staring at me: take some characters out of a $(whatever) call and it turns into $whatever.
var $email = $("#email"), email = $email[0];
// $email is the jQuery object and email is the DOM object
and:
// email is a DOM element passed into this function
function doSomethingWithEmail( email ) {
var $email = $(email);
// $email is the jQuery object and email is the DOM object
// Same names as in the code above. Yay!
}
So I didn't have to make up two different names all the time but could just use the same name with or without a $ prefix. And the $ prefix was a nice reminder that I was dealing with a jQuery object:
$('#email').click( ... );
or:
var $email = $('#email');
// Maybe do some other stuff with $email here
$email.click( ... );
In the context of AngularJS, the $ prefix is used only for identifiers in the framework's code. Users of the framework are instructed not to use it in their own identifiers:
Angular Namespaces $ and $$
To prevent accidental name collisions with your code, Angular prefixes names of public objects with $ and names of private objects with $$. Please do not use the $ or $$ prefix in your code.
Source: https://docs.angularjs.org/api
Stevo is right, the meaning and usage of the dollar script sign (in Javascript and the jQuery platform, but not in PHP) is completely semantic. $ is a character that can be used as part of an identifier name. In addition, the dollar sign is perhaps not the most "weird" thing you can encounter in Javascript. Here are some examples of valid identifier names:
var _ = function() { alert("hello from _"); }
var \u0024 = function() { alert("hello from $ defined as u0024"); }
var Ø = function() { alert("hello from Ø"); }
var $$$$$ = function() { alert("hello from $$$$$"); }
All of the examples above will work.
Try them.
The $ character has no special meaning to the JavaScript engine. It's just another valid character in a variable name like a-z, A-Z, _, 0-9, etc...
Since _ at the beginning of a variable name is often used to indicate a private variable (or at least one intended to remain private), I find $ convenient for adding in front of my own brief aliases to generic code libraries.
For example, when using jQuery, I prefer to use the variable $J (instead of just $) and use $P when using php.js, etc.
The prefix makes it visually distinct from other variables such as my own static variables, cluing me into the fact that the code is part of some library or other, and is less likely to conflict or confuse others once they know the convention.
It also doesn't clutter the code (or require extra typing) as does a fully specified name repeated for each library call.
I like to think of it as being similar to what modifier keys do for expanding the possibilities of single keys.
But this is just my own convention.
${varname} is just a naming convention jQuery developers use to distinguish variables that are holding jQuery elements.
Plain {varname} is used to store general stuffs like texts and strings.
${varname} holds elements returned from jQuery.
You can use plain {varname} to store jQuery elements as well, but as I said in the beginning this distinguishes it from the plain variables and makes it much easier to understand (imagine confusing it for a plain variable and searching all over to understand what it holds).
For example :
var $blah = $(this).parents('.blahblah');
Here, blah is storing a returned jQuery element.
So, when someone else see the $blah in the code, they'll understand it's not just a string or a number, it's a jQuery element.
As I have experienced for the last 4 years, it will allow some one to easily identify whether the variable pointing a value/object or a jQuery wrapped DOM element
Ex:
var name = 'jQuery';
var lib = {name:'jQuery',version:1.6};
var $dataDiv = $('#myDataDiv');
in the above example when I see the variable "$dataDiv" i can easily say that this variable pointing to a jQuery wrapped DOM element (in this case it is div). and also I can call all the jQuery methods with out wrapping the object again like $dataDiv.append(), $dataDiv.html(), $dataDiv.find() instead of $($dataDiv).append().
Hope it may helped.
so finally want to say that it will be a good practice to follow this but not mandatory.
While you can simply use it to prefix your identifiers, it's supposed to be used for generated code, such as replacement tokens in a template, for example.
Angular uses is for properties generated by the framework. Guess, they are going by the (now defunct) hint provided by the ECMA-262 3.0.
$ is used to DISTINGUISH between common variables and jquery variables in case of normal variables.
let you place a order in FLIPKART then if the order is a variable showing you the string output then it is named simple as "order" but if we click on place order then an object is returned that object will be denoted by $ as "$order" so that the programmer may able to snip out the javascript variables and jquery variables in the entire code.
If you see the dollar sign ($) or double dollar sign ($$), and are curious as to what this means in the Prototype framework, here is your answer:
$$('div');
// -> all DIVs in the document. Same as document.getElementsByTagName('div')!
$$('#contents');
// -> same as $('contents'), only it returns an array anyway (even though IDs must be unique within a document).
$$('li.faux');
// -> all LI elements with class 'faux'
Source:
http://www.prototypejs.org/api/utility/dollar-dollar
The reason I sometimes use php name-conventions with javascript variables:
When doing input validation, I want to run the exact same algorithms both client-side,
and server-side. I really want the two side of code to look as similar as possible, to simplify maintenance. Using dollar signs in variable names makes this easier.
(Also, some judicious helper functions help make the code look similar, e.g. wrapping input-value-lookups, non-OO versions of strlen,substr, etc. It still requires some manual tweaking though.)
A valid JavaScript identifier shuold must start with a letter,
underscore (_), or dollar sign ($);
subsequent characters can also
be digits (0-9). Because JavaScript is case sensitive,
letters
include the characters "A" through "Z" (uppercase) and the
characters "a" through "z" (lowercase).
Details:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variables

Categories