Hey.

var arr = [2 + 3, 1 + 7]; alert(arr[0] + '::' + arr[1]) //5::8 var x = 100; var arr2 = [2 + x, 4 + x]; alert(arr2[0] + '::' + arr2[1]) //102:104 

For me, the processing of variables inside the array has become a discovery.

I try the same for the object

 var obj = { foo: x } alert(obj.foo) //100 

Where can I read more extensively on this topic? Where else can variables be used like this?

  • 3
    These are the basics of js, read the basics of js! - Specter
  • apparently missed these basics - zloctb
  • 2
    CoffeeScript went further: x = 'value' y = 'another value' obj = {x, y} which is equivalent to: var obj, x, y; x = 'value'; y = 'another value'; obj = {x: x, y: y}; - Specter

1 answer 1

Where else can variables be used like this?

I will tell you a little where they can be used in the near future (you never know, maybe someone does not know)

Destructuring assignment:

 var a = 1, b = 2; [a, b] = [b, a]; // или например так: var { x:a, y:b } = { x:1, y:2 }; 

Where can this be useful? example from backbone.js sources:

 set: function(key, value, options) { var attrs, attr, val; if (_.isObject(key) || key == null) { attrs = key; options = value; } else { attrs = {}; attrs[key] = value; } 

the if body can be easily replaced by:

 [attrs, options] = [key, value] 

Generator Expressions:

 [ i for ( i in [5,6,7,8,9] ) ] // [0,1,2,3,4] [ i for each ( i in [5,6,7,8,9] ) ] // [5,6,7,8,9] [ i for each ( i in [5,6,7,8,9] ) if (i % 2 != 0)] // [5,7,9] 

besides spheres of application is enough

Optional named function arguments

 function foo({ name:name, project:project}) { console.log(project); console.log(name); } foo({ name:'soubok', project:'jslibs' }); foo({ project:'jslibs', name:'soubok'}); 

more details: