lohe
lohe

Reputation: 127

Can anybody explain what that expression does?

I stumble on a part of code, I don't understand and don't know how to research as well. A simplified version of it is as follows:

    var obj = {
            token: 'asdfasdfaksjdfk23432',
            userId: '1q2w3e4r',
            test: true
        },
        obj1 = {
            token: 'asdfasdfaksjdfk23432',
            userId: '1q2w3e4r',
            test: false
        };
    if((obj = obj1).userId){
        console.log(true);
    };

Just wondering, what does the (obj = obj1) part means|does.

Upvotes: 0

Views: 43

Answers (2)

Morphasis
Morphasis

Reputation: 1433

I think you will find that this is assigning the values inside the if statement. This is not super clear and you should probably not do this.

For example your code is the same as:

var a = 4;
var b = 10;

if (a = b) {
  // Will output 10, 10 because it sets a to b.
  console.log(a, b)
}

This is because it will run a = b setting the value of a to b.

A better solution would be to declare this prior to the if statement for clarity.

Hope that helps.

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370739

It's a very confusing way of

(1) assigning obj1 to obj (discarding whatever obj happened to have previously)

(2) Checking whether obj1.userId is truthy or not

Assignments resolve to an expression, unfortunately. It's equivalent to:

obj = obj1;
if (obj1.userId) {
    console.log(true);
}

(note that the if block should not have a ; after its last }. For that matter, it shouldn't be evaluating the assignment as an expression either, but that's the whole question...)

Upvotes: 2

Related Questions