Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between ‘var $x’ and ‘var x’ in javascript? [duplicate]

What's the difference between var $x and var x in javascript?

like image 451
Alexsander Akers Avatar asked Nov 26 '09 15:11

Alexsander Akers


People also ask

What is var x in JavaScript?

var is the keyword that tells JavaScript you're declaring a variable. x is the name of that variable.

What is difference between x ++ and ++ x in JavaScript?

Difference between x++ and ++xx++ executes the statement and then increments the value. ++x increments the value and then executes the statement.

What is the difference between VAR X 1 and X 1?

The former creates a local variable, while the latter creates a global variable. If you use strict mode, only var x = 1 would work. If you are using 'use strict' in your js file then later one will give error.

What are the two types of variables in JavaScript?

JavaScript variables have only two scopes. Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.


2 Answers

Nothing. People tend to use the $x syntax because it's easier to remember you're dealing with a jquery object rather than an element or an id.

In general I tend to use something similar to:

var $x = $(selector) //$x holds reference to a jquery object
var elX = document.getElementById(id); // elX hold ref to an element node
var xId = $(selector).attr('id'); //xId holds ref to an id attribute
like image 147
Steerpike Avatar answered Oct 25 '22 15:10

Steerpike


The difference? One variable starts with $.

And neither has anything to do with jQuery - it's just javascript.

like image 20
Oli Avatar answered Oct 25 '22 14:10

Oli