Andre Bulatov
Andre Bulatov

Reputation: 1139

With jQuery/JavaScript Is it slower to declare variables that will only be used once?

I just want to make sure I understand this basic idea correctly, and no matter how I phrase it, I'm not coming up with completely relevant search results.

This is faster:

function () {
    $('#someID').someMethod( $('#someOtherID').data('some-data') );
}

than this:

function () {
    var variableOne = $('#someID'),
        variableTwo = $('#someIDsomeOtherID').data('some-data');
    variableOne.someMethod( variableTwo );
}

is that correct?

I think the question may be "Is declaring variables slower than not declaring variables?" :facepalm:

The particular case where I questioned this is running a similarly constructed function after an AJAX call where some events must be delegated on to the newly loaded elements.

Upvotes: 2

Views: 190

Answers (2)

Glubus
Glubus

Reputation: 2855

The answer you will benefit from the most is It does not make a difference.

Declaring variables and storing data in them is something you do so that you do not have to query that data more than once. Besides this obvious point, using variables rather than chaining everything into one big expression improves readability and makes your code more manageable.

When it comes to performance, I can't think of any scenario where you should debate declaring a variable or not. If there's even an absolute difference in speed, it would be so small that you should not see this as a reason to not use that variable and just leaving your code to becoming spaghetti.

Upvotes: 2

Piyush.kapoor
Piyush.kapoor

Reputation: 6803

If you want to use the element $('#someID') again and again Then decelaring variable would be useful and caching $('#someId') is recommended.

var x = $('#someId')'

Upvotes: 1

Related Questions