Page 1 of 1

javascript linting error

Posted: Fri Jun 12, 2015 4:01 pm
by Mardonis
I have a piece of code below that says "Unexpected assignment expression." where (foo = bar).

function bar() {}

var foo;

foo || (foo = bar);

I have tried to create a variable before it and assign it to the variable. But it gives another error where foo is saying "Expected an assignment or function call and instead saw an expression." where foo || foobar (foobar is the variable i had to create when i tried var foobar = bar) (basically foo || foobar). I keep running into a wall trying to figure this one out. How would you recode this lint free?

Thanks.

Re: javascript linting error

Posted: Fri Jun 12, 2015 4:26 pm
by Chris

Code: Select all

foo = foo === undefined ? bar : foo;
You can't defined variables using string names like in PHP.

Re: javascript linting error

Posted: Fri Jun 12, 2015 5:56 pm
by Mardonis
Would this be the same?

if (foo === undefined) {
bar;
} else {
foo;
}

Re: javascript linting error

Posted: Sat Jun 13, 2015 3:03 am
by KyleMassacre
Mardonis wrote:Would this be the same?

if (foo === undefined) {
bar;
} else {
foo;
}
I don't believe that would work either.
I think you are looking for something like this if you are not a fan of ternaries:

Code: Select all

if(foo === undefined)
    foo = bar;
I don't see a need for an else statement to say that foo = foo. Of course it equals foo if it's not "undefined"

Re: javascript linting error

Posted: Mon Jun 15, 2015 12:46 pm
by Mardonis
ok cool, thank you. I was basically trying to NOT use ternaries like you said. wanted to get it back to a normal if statement for readability. Then I was going to optimize later.

Re: javascript linting error

Posted: Tue Jun 16, 2015 7:33 pm
by Jackolantern
I have always loved ternaries and find them very quickly readable compared to an IF statement, but to each their own :)