4

I see sometimes js snippets that are using the $ in front of the argument ($argName).

function someName(arg) {
  // some code
  // using arg
}

function someName($arg) {
  // some code
  // using $arg
}

In this js example it works either way with or without the $ in front of the arguments. Can anyone explaine if it has any use?

CerebralFart
  • 3,336
  • 5
  • 26
  • 29
Giorgio25b
  • 406
  • 4
  • 13
  • 1
    The "$" character is just a character that can be used in an identifier - there's nothing special about it. – Pointy Mar 19 '15 at 14:14
  • 3
    some people use it as a convention to name a jQuery element or an angular builtin service. – Daniel A. White Mar 19 '15 at 14:15
  • [Hungarian notation](http://en.wikipedia.org/wiki/Hungarian_notation) why people only use it for jQuery object drives me mad. – epascarello Mar 19 '15 at 14:25
  • @epascarello I find it useful as it reminds colleagues that they needn't rewrap the parameter in another `$()` call. It's a long way from full MS-style Hungarian notation IMHO, and more useful given that JS isn't a strongly typed language. – Alnitak Mar 19 '15 at 14:49
  • @Alnitak JSDoc or any other code documentation seems to fix that problem without making a special case exception for one variable type. – epascarello Mar 19 '15 at 15:30
  • @epascarello I find it a useful convention. If you don't, that's fine. – Alnitak Mar 19 '15 at 15:31

2 Answers2

8

The $ character is legal in JS identifiers, and is often used simply as a code convention to indicate that the passed parameter is already a jQuery object (as opposed to a native DOM element).

This serves as a reminder that it's not necessary to re-invoke the jQuery $(param) wrapper function on that parameter.

It's also used quite a lot in Angular JS code.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

It's sometimes used to reference an object from another library , like JQuery or AngularJS , what you're talking about here looks like AngularJs's dependency injection to me

UPDATE

See this answer it might be useful

Community
  • 1
  • 1
Yazan Rawashdeh
  • 1,017
  • 2
  • 16
  • 26