-4

I don't know how to describe this, but this doesn't error out in Javascript... but it doesn't mean its a good idea and that all versions of Javascript except it (or not).

Thoughts?

var r = 'r';
var t = 't';
var s = 's';

s = r = t;

// s = 't'
// r = 't'
// t = 't'

It doesn't seem standard and it may be harder for a developer to follow, but are there really any use cases for this?

kungfuu72
  • 9
  • 1

3 Answers3

1

This works because the assignment of r=t returns the assigned value. So yes you can infinitely assign values based on return values.

dovidweisz
  • 1,215
  • 13
  • 24
1

It is a fairly standard practice to chain assignments together. It even has a name called "chain assignment". I don't know where you get the idea of "this is bad coding" from, but this is definitely a normal thing to see. This works because assignments return the assigned value.

This is commonly used for initializing variables:

var a, b, c;
a = b = c = 5;  //one use case
//same as
a = (b = (c = 5)));

It doesn't seem standard and it may be harder for a developer to follow.

If a developer cannot understand this expression, I don't know what to say.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
0

I use it all the time in my modules to create a local shortcut to functions (for use within the module):

var doSomething = module.exports.doSomething = ()=>{};

It's nice the way javascript returns values. In languages like python you have to do this sort of thing way to often:

def do_something(ctx):
    ctx.update({
        'entry': entry,
        'section': 'select_category'
    })
    do_something_else(ctx)

instead of

def do_something(ctx):
    do_something_else(ctx.update({
        'entry': entry,
        'section': 'select_category'
    })

because the update method doesn't return anything.

Robert Moskal
  • 21,737
  • 8
  • 62
  • 86