1

There are about 35 variables on a page which starts as blank. Each variable is used for a different purpose.

var a = '', b = '', c = ''; 

Is there a shorter way of writing these variables?

2
  • 1
    Just remember that being idiomatic should be more important than be fast ;) Commented Jun 29, 2015 at 7:09
  • 1
    @Deerloper Is entirely right. I find your method to be much easier to read than Milind's answer Commented Jun 29, 2015 at 7:15

2 Answers 2

2

Like this:

var a = b = c = '', 

Working Demo

Sign up to request clarification or add additional context in comments.

11 Comments

Can this technique be use to all similar vars? e.g.: var a = b = c = 10, OR var a = b = c = 'Yes',
@Becky: yes..absolutely. check the demo. it is alerting the sum of three variable to 30 when var a = b = c = 10 is used.
Beware when defining object var a = b = c = [1,2,3,4]. All variables are sharing the same reference.
@Becky No, it means they all refer to the same object. So modifying c will update a and b.
Nope. It means defining all variables with [1,2,3,4]. However, they share the same reference so any changes you made on any of them will affect all the rest.
|
1

Whenever you see yourself repeating something, you want to look for a better way of doing it:

In this case, there's something called an Array of variables. Usually, you use arrays with loops to achieve repetitive tasks.

An array is a list of variables that can be accessed by index. It's as if you had a variable named a0, a1, a2, a2, etc... Wouldn't be awesome to be able to go through all the variables without having to type each one explicitly?

This is how arrays and loops work together:

var a = new Array(); // declare the array; "a" is the name of your array here a[0] = ""; // this is how you assign the first index in the array a[1] = ""; // second, etc // now stop doing this manually and do the code below // this is how you loop 30 times assigning each variable in the array to an empty string for (var i=0; i < 30; i++) { a[i] = ""; } console.log("This is the array: ", a); 

PS: there are better ways of addressing your question but this one is the most straightforward =)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.