user160820
user160820

Reputation: 15230

Can a `var` declaration be split into multiple lines without repeating the `var` keyword?

I have many variables in my javascript function and don't fit on one line declaration.

var query_string = $('list_form').serialize(), container = $('list_container'),position = container.cumulativeOffset(), layer = $('loaderLayer'),
            remote_url = "/web/view/list_offers.php?" + query_string;

Is there a way to define these variables on multiple lines with only one var keyword?

Upvotes: 0

Views: 169

Answers (3)

Sarfraz
Sarfraz

Reputation: 382881

var query_string = $('list_form').serialize(),
    container = $('list_container'),
    position = container.cumulativeOffset(),
    layer = $('loaderLayer'),
    remote_url = "/web/view/list_offers.php?" + query_string;

If I recall it correctly, that is the pattern advocated by Doughlas Crackford to declare multiple variables that script needs.

Quick Tip: Beawere of JavaScript Hoisting :)

Upvotes: 4

Tom Gullen
Tom Gullen

Reputation: 61775

You can seperate declarations by commas:

var a, b, c

I don't see this often but it's valid. You can also add the initial values in:

var a = 5, b = $('#myDiv').html(), c= 6*43, d = query_string;

You really don't see this often, but again it's valid. I would argue that it's hard to read, and therfore hard to maintain, so you are better off just doing:

var a = 5;
var b = $('#myDiv').html();
var c= 6*43;
var d = query_string;

Upvotes: 0

Declare the variables with out giving any datatype like var as below.

query_string== $('list_form').serialize(); container = $('list_container'); position = container.cumulativeOffset(); layer = $('loaderLayer'); remote_url = "/web/view/list_offers.php?" + query_string;

it will work.

Upvotes: -1

Related Questions