This function declaration doesn't make sense to me. What does the $ sign do?
function $(id) { return document.getElementById(id); }
Also, this code is interfering with other Javascript code. If I comment it out, then the other Javascript code I'm trying to use works, but then I lose some other functionality.
Why might it be interfering with my other code.
What does the $ sign do?
Nothing special. It is just a character that can be used in variable/function names.
There has been a trend to use $ as the name to the gateway function for a number of libraries (including Mootools, Prototype and jQuery). This has two major problems:
It makes them conflict with each other
It violates the principles of self-documenting code
Also, this code is interfering with other Javascript code.
Presumably something else is using a variable called $ then.
You are declaring a function called $ that wraps document.getElementById, apparently for convenience. Nothing special.
Reference What characters are valid for JavaScript variable names?
As for the interference, there is likely another global variable called $, which is being clobbered. See jQuery.
JavaScript variables can start (and only consist of) a $ (amongst others).
Previously, the $ was added solely for machine generated variables.
This was in the spec I believe, but has since been removed (don't quote me).
Dollar sign was added to the language specifically for use by code
generators and macro processes, so if you have machines writing code
then the machines need to be confident that the variables that they
create will not conflict with variables that the humans are going to
create. To distinguish them, we’ll allow the machines to use dollar
sign. Some of the ninjas found out about that and thought oh, dollar
sign, I can use dollar sign as a function name, so they’re out there
doing that. And it looks stupid. I mean, look at a program with dollar
sign.
Source: Douglas Crockford.
If it is interfering with other code, you may be using a library which uses this identifier. If that's the case, look at the no conflict mode for that library (if it has one).
Let me guess: are you using jQuery or prototype?
$ and _ are valid characters in variable/function names. The code is the same as declaring function a(id) {return document.getElementById(id);}.
It's typically used as a shortcut for selecting an element because typing document.getElementById is much too long for how often it's used.
Related
$ is not a function is a common error message newbies encounter when trying to use JQuery in Drupal 7.
The explanation is that the usage of $ is disabled in Drupal to avoid conflicts with other libraries. But which other library is using $?
At least two major ones:
PrototypeJS,
Mootools,
It is probably because using one char for most commonly used function saves a lot of time. And due to some restrictions for characters in variable name in JavaScript there are actually two candidates for such one-char names: $ and _ (_ is used often for eg. gettext functions or throw-away variables). Thus I would rather expect that if some framework has some shortcut function with one char name, it is probably $.
One of the common problems is several different versions of JQuery itself, though I'm not sure that is the reason in Drupal.
Another possibility is Mootools
zepto also uses $, and is a lightweight alternative to jQuery:
http://zeptojs.com/
In addition, it matches most of the jQuery API.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Lambda function syntax in JavaScript without curly braces
Dealing with Protovis - they implement some strange delegate functions which are given without curly braces - can someone shade a light on it for me, please?
Example:
vis.add(pv.Label)
.data(cols)
.left(function() this.index * w + w / 2)
.top(0)
.textAngle(-Math.PI / 2)
.textBaseline("middle");
In general, as explained in the question #missingno linked to, this is an alternate syntax for declaring functions, primarily supported by Firefox. Instead of:
function() { return "stuff" };
you omit the curly braces and return statement:
function() "stuff";
The end of the function occurs anywhere that a normal statement might end - a semicolon (;), a comma (,), or a close parenthesis ()).
In Protovis, there are a lot of cases where you need to declare short, one-statement anonymous functions to pass in as arguments to method calls. This is such a common pattern that that library includes a parsing utility to make sure that the above syntax is supported in browsers other than Firefox. If you enclose your Protovis code in script tags like this:
<script type="text/javascript+protovis">
// ...
</script>
the script will be evaluated by the Protovis parser, which ensures support for the special syntax.
My two cents on this: The upside of this syntax is that it's really fast (plus all the examples use it). A typically script using Protovis involves a lot of anonymous functions, so this can save you some typing, and it looks pretty awesome. When I first started using Protovis, I used it a lot - not just in method calls, but in variable declarations as well.
But, it has a few really heavy problems:
Because all your code is run through the Protovis parser, which essentially munges the code to re-add the return statements and then eval() it, it becomes fantastically hard to debug simple syntax errors. You get all these "Unexpected identifier" errors pointing to the eval() line in the Protovis code, with no indication of where the issue (a missing semicolon, etc) is occurring in your own code.
If you want your code to work outside Firefox, you have to include all your code in the special javascript+protovis script tags, which means no external files. Once you start doing anything of even marginal complexity, you really want to keep your scripts separate most of the time.
As with any "clever" syntax, it can get really hard to read, especially when you're using it in unexpected ways (e.g. outside of a method call). Yes, it's concise, but there's a definite price to pay in legibility.
All that said, I still use it when I want to make a rough sketch quickly. But most of the time, I'd suggest sticking to normal script tags and standard, curly-braced function declarations.
I am trying to decipher a .js script and I am finding it filled with $ throughout? Is there any reason to use this? I'm pretty new to JavaScript.
I think you are reading a JavaScript library famously known as jQuery (or possibly another library). The $ is just a short form for a namespace or use as an identifier.
You can think of it like this jQuery('p') to select all the paragraphs on a page,
or for short form you can just write $('p').
Here is a link for jQuery tutorials/docs jQuery
Here is a list of standards section 7.6 describes it in detail ECMA Standard
A number of libraries have used $ as their primary symbol. It's nothing to do with JavaScript per se, but it's a short distinctive symbol and so libraries have tended to glom onto it. (You can start an identifier with $ in JavaScript, and identifiers can be one character long, so $ is a valid identifier, just like a or x.)
I know of at least three libraries that use $ for something:
jQuery - It's the all purpose function for jQuery, an alias of the jQuery function; more here.
Prototype - It's Prototype's replacement for document.getElementById, more here. Prototype also has $$, which is for looking things up via CSS selectors.
MooTools - Same use as Prototype (because MooTools is either "inspired by" or "forked from" Prototype, some years back, depending on who you ask), more here. And like Prototype, it has $$.
$ is a variable. A number of frameworks use it as a short hand for using it. Prototype and Jquery are the two big ones. This does not mean that the $ automatically is either one of those. It could be anything as anything in JavaScript can assign something to the $. This is something to be aware of, because when you start combining scripts from different sources, it's really easy for one to accidentally reassign a variable to something else.
Most likely it is a framework reference, but you'll have to read the code to be sure. At one point in time the $ was meant to be used to indicate that the code referenced by it was auto generated, but this is just a guideline.
if you're new to javascript, $() can look strange.
Try to think of it like
var $ = function(){
//do something
}
So the dollar sign is just the name of a variable like any other.
var myFunction = function(){
//do something
}
// this is exactly the same just a different name.
So the dollar sign has no special meaning in javascript.
Frameworks like to use it because you are using their functions so often, having to write e.g. jQuery() every time would be tedious. Having one character is nice and short.
I think they also have a preference for the $ symbol, purely because it is unusual so it is quickly distinguishable from other code.
A quick way to find out if it is jQuery is to do console.log(jQuery) if the console returns a string of code $() is jQuery. If you get undefined, it is something else.
Maybe you're reading jQuery code.
Because JavaScript lets you define variables which start with $ sign, or literally which are only $. For example, you can do:
var $ = "something";
alert($);
jQuery is a library built on JavaScript (the most popular at the time) and it has a global object to keep everything encapsulated. You access that global object using $.
The script is probably using a third party library such as Prototypejs or jQuery or he defined his own function $() which explain why the dollar sign appears so often in that script.
It's a jQuery function. That's what it is most probably. Might also be the Prototype library, or just a function that does something that's needed many times in the code, like getElementById etc
Without seeing the code, it sounds like the script you are looking at makes use of jQuery, as the $ is the default jQuery object.
Typically the $ will represent jQuery or another specific library (Moo Tools, etc.) . $ is the shortened form of referencing the jQuery object (or whatever library it was assigned). It makes the code much more readable and easy to use.
If you are just learning javascript, you will soon become very familiar with jQuery. :)
Either its jQuery or an old PHP habit by some javascript programmer :)
$ is only a function. It means you work with some javascript superstructure (framework).
I was having issues with some jquery and posted about it here. After following a few of the suggestions, I was able to isolate the problem - IE8 did not like the variable name new_email. In fact the debugger had been telling me that the issue was at character 4 of that line, but I couldn't believe it was the variable name, so I kept looking for other issues.
After finally giving in and changing the variable name to newEmail, IE8 no longer blows up - the code works as expected with no errors.
I've been unable to find any documentation stating that you can't use underscores in jquery variable names, and indeed, the code worked correctly in every other browser with the underscore in place. Is this an unwritten rule in IE8? Is it something that real jquery developers just know? I'm worried if this really is true, as I inherited this code, and the app is enormous - I know there are several dozen variables in various places that have underscores in them.
This is actually a javascript variable and not a jQuery variable, an important distinction, and in Javascript the underscore is a valid character for variable names. You must have changed something else unrelated.
Is it possible that variable name was already assigned elsewhere? Also note that you aren't using the var keyword which can cause further issues with scope.
You can always post a jsfiddle.net example if you would like more assistance though.
here is a working jsfiddle that uses your variable
please note that you should probably be more specific than ":text"
jQuery is written in JavaScript, which is a language based on the ECMAScript Language Specification (PDF). The specification states that "underscore[s] are permitted anywhere in [a variable name]".
Your problem, as HurnsMobile, stated is most definitely not with the underscore but some other part of your code. It may also be caused by some quirk or bug in IE8 but even IE8 should be able to handle simple variable names.
I am a JavaScript learner and have been researching this matter, but with no success. What is the $ symbol used for in JavaScript besides regular expressions? Any resources or readings regarding this would be appreciated. Thanks.
It doesn't mean anything special.
But because $ is allowed in identifier names, many Javascript libraries have taken to using $ as the "central" interface to them, or at least as a shortcut for accessing their functionality.
For example, if you're using jQuery and you say $("div"), this is a call to the $ function with argument "div". When you say $.post(), it's calling the post method on the $ object (Javascript is nice in that functions are first-class objects).
I became acquainted with it in JavaScript when I started using the Prototype framework. In Prototype, $ is simply the name of an often used function (very, very much simplified - a short for document.getElementById). Personally, I like the terseness of it.
Afaik, it's not used for anything by the language itself.
For what it's worth, Douglas Crockford advises against using $ in the variable/function names you write:
Do not use $ (dollar sign) or \
(backslash) in names.
Adding another, rather opinionated, quote from Mr. Crockford's talk "And Then There Was JavaScript":
Dollar sign was added to the language
specifically for use by code
generators and macro processes, so if
you have machines writing code then
the machines need to be confident that
the variables that they create will
not conflict with variables that the
humans are going to create. To
distinguish them, we’ll allow the
machines to use dollar sign. Some of
the ninjas found out about that and
thought oh, dollar sign, I can use
dollar sign as a function name, so
they’re out there doing that. And it
looks stupid. I mean, look at a
program with dollar sign.
If you are asking why some variables and function names start with $, then that is simply a convention when using jQuery and/or AngularJS.
In code that uses jQuery, $ is often used as a prefix for variables that contain jQuery selections.
e.g. var $container = $('.container');.
In AngularJS, they use the $ prefix to mean "core Angular functionality". That way, you know which methods and services are added by the framework, and which are custom to your application.