I try something like this:
var varr = var;
varr x = 10;
It doesn't work, for obvious reasons, but you get the idea. How do I define keywords in Javascript, like how I can in C:
#define var int
var x = 10;
The above code wouldn't work, but is there a way to do something similar in Javascript? Not that I would absolutely need to, but just wondering.
var is a reserved token by Javascript and thus cannot be used incorrectly, or as part of variable names.
When JavaScript parses our code, behind the scenes it’s converting everything into appropriate characters, then the engine attempts to execute our statements in order and as var is a reserved token it will throw Uncaught SyntaxError: Unexpected token 'var'
JavaScript doesn't allow you to use the reserved keyword as the identifier's value, What you're gonna do is a pretty clear mistake here. you defined variable and assign as value unsupported datatypes which js don't know, Learn more
var <variable-name> = <reserved-keyword>
expected value:
var <variable-name> = <value>
javascript support all datatypes which you use in C, Int, Float, String, Obj...
Example of:
var x; // declare empty variable
x = 1;
var y = "String";
var z = [];
var foo = {};
The reason why this is possible in C is because #define allows you to declare macros that are replaced in the source code before compilation. Javascript doesn't have a concept of macros so it's not a part of the language however there are tools in JS that let you add this kind of compilation step even though it's not a part of JS itself.
Babel is probably the most popular way to do this and https://github.com/kentcdodds/babel-plugin-macros is pretty useful although I'm not sure if you can use it to redefine parts of the language.
You can instead use something like https://github.com/sweet-js/sweet-core to do what you want which lets you add a pre-processor step to replace macros however like I said, JS doesn't support macros so this is a step you have to execute to generate valid Javascript.
syntax varr = function (ctx) {
return #`var`;
};
varr test = 10;
$ sjs test.sweet
var test = 10;
It's also important to mention that in C this is something that's built into the language so IDEs understand how to deal with macros, but if you're using an external tool you're not going to have a fun time using macros that redefine keywords, especially when it comes to things like syntax highlighting. This is something I'd definitely discourage, but it is technically possible if you're willing to step outside the bounds of just Javascript.
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
This question already has answers here:
Why would a JavaScript variable start with a dollar sign? [duplicate]
(16 answers)
Closed 9 years ago.
I just have a quick question and cant find anything on google. I was going through some code another programmer put together and he declares ALL of his javascript variables with $ in front of them...for instance:
var $secondary;
Is there a reason for this? Could this cause problems in the future if JQuery ever ends up being used. I'm just curious because I was going to clean it up if so.
Is there a reason for this?
Hard to say. Maybe he came from a PHP background where $ prefixes the variables. Maybe he's a jQuery addict. Who knows? You'd have to ask him. That aside, $ is a perfectly legitimate character to use in a JavaScript variable name but as you noted, it could cause issues with jQuery. But that's why jQuery offers a noConflict() option.
I use this convention too keep track of if a variable is storing a JQuery object. So say the function getJQueryObject() returns a JQuery object and I want to store it.
i.e:
var $myJQobj = getJQueryObject();
Makes it clear that $myJQobj is a JQuery object unlike i.e
var myStr = "hello";
The $ as the first character in the identifier doesn't have any special meaning, you aren't invoking a method like $(), it's just a perfectly valid identifier in JavaScript. But the factthat the $ is used in JQuery makes what I was talking about before even clearer.
$ is a valid variable character, and in PHP all variables start with it. It's possibe that that particular developer uses $ as a "flag" to mean "this is a variable". It has no special meaning.
$ just a character that you can use in a variable name. Some people like to use it to denote variables that contain jQuery objects:
var $foo = $('#foo');
var bar = 42;
But that's just a personal preference. It has no special meaning.
its just a convention for jQuery DOM selctions.
var $logo = $('a.logo');
it wont cause any issues - it just lets other devs know that you're working with a jQuery wrapped dom element.
$ is fine for use in JavaScript. PHP uses the same variable syntax so maybe he was used to it from that.
You can see this being used to autocomplete local JavaScript variables in http://codemirror.net/2/demo/complete.html
But,How i use this autocomplete in c language?
How i edit this code?
http://codemirror.net/demo/complete.js
Are you talking about editing the script to auto-complete C in the browser?
First you need to identify the where local variables in C are defined. You're looking for keywords like int float long or patterns like type_name identifier_1 = value, identifier_2;
The next thing you need to do is identify the function parameters. The pattern you're looking for is
return_type function_name(parm1, param2){
// current code
}
Last you need to include constants created with #define and variables defined in file scope (C) or global scope (C++).
type_name identifier = value;
#define constant value
// Outside of any sort of scope
/* something */{
}
It would be difficult to just edit the script that works on JavaScript because the two languages behave differently and have different rules. If you need some help of the ways to parse the data from C and other languages using JavaScript you might look into google-prettify which is a syntax highlighting script.
Good luck.
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Why would a javascript variable start with a dollar sign?
JQuery : What is the difference between “var test” and “var $test”
What is the difference between this two ways of initializing variables?
var $val = 'something'
OR
var val = 'something'
as I see they are the same thing.
Maybe in this case $ is only the part of name in variable?
(it will become a meaningless question in that case:/)
Thanks
The $ in the variable name is only part of the name, but the convention is to use it to start variable names when the variable represents a jQuery object.
var $myHeaderDiv = $('#header');
var myHeaderDiv = document.getElementById('header');
Now later in your code, you know the $myHeaderDiv is already a jQuery object, so you can call jQuery functions:
$myHeaderDiv.fade();
To get from the DOM-variable to the jQuery variable:
var $myHeaderDiv = jQuery(myHeaderDiv); //assign to another variable
jQuery(myHeaderDiv).fade(); //use directly
//or, as the $ is aliased to the jQuery object if you don't specify otherwise:
var $myHeaderDiv = jQuery(myHeaderDiv); //assign
$(myHeaderDiv).fade(); //use
To get from the jQuery variable to the DOM-variable.
var myHeaderDiv = $myHeaderDiv.get(0);
You are correct. $ is a part of the name of the variable.
This is not perl or PHP :)
No real difference..
It is usally used to signify a variable holding a jquery or other javascript framework object, because they can have shorthand $ function..
It is just easier to identify the type of the contents..
There are 28 letters in the alphabet as far as JavaScript is concerned. a-z, _ and $. Anywhere you can use a letter in JavaScript you can use $ as that letter. (<c> Fellgall # http://www.webdeveloper.com/forum/showthread.php?t=186546)
In your example $val and val will be two different variable names.
syom - in my case, i use the $ prefix to indicate that it's a variable that is referenced by jquery. It's purely a part of the variable and not a reserved character.
keeps it easy to identify in long code runs..
jim