tags:

views:

62

answers:

4

Rather than doing

my_var = my_var+'extra string';

is there a shorthand method like .= in php?

+3  A: 

Use +=

var s = 'begin';
s += 'ning';
npup
ha - should have guessed that!
Haroldo
A: 

Yes: my_var += 'extra string';

Aaron Digulla
A: 
+=

Example:

my_var += "extra string";
Guffa
+2  A: 

Performance Tip

If you're writing some Javascript code to build up a long string (say, a fairly big block of HTML, or a long parameter list for an ajax request), then don't get in the habit of doing this:

var longString = "";
for (var i = 0; i < someBigNumber; ++i) {
  if (i > 0) longString += "<br>" + whatever;
  longString += someMoreStuff();
}

As the longString gets longer and longer, Internet Explorer will puff harder and harder on each iteration of the loop. Even when someBigNumber isn't really that big, the performance of that loop can be really terrible.

Luckily, there's an easy alternative: use an array:

var accumulator = [];
for (var i = 0; i < someBigNumber; ++i) {
  accumulator.push(someMoreStuff());
}
var longString = accumulator.join("<br>" + whatever);

Way, way faster in Internet Explorer than repeated string appends.

Pointy
Better yet, Pointy, you big dummy, do stuff like that with a framework! Frameworks are generally very well optimized, and will generally do most everything in a well-tested, efficient, safe way.
Pointy
Lol (15 chars).
BalusC
Good answer, was about to write that.
stereofrog