javascript linting error

C++, C#, Java, PHP, ect...
Post Reply
Mardonis
Posts: 139
Joined: Wed Jun 29, 2011 7:54 pm

javascript linting error

Post 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.
User avatar
Chris
Posts: 1580
Joined: Wed Sep 30, 2009 7:22 pm

Re: javascript linting error

Post by Chris »

Code: Select all

foo = foo === undefined ? bar : foo;
You can't defined variables using string names like in PHP.
Fighting for peace is declaring war on war. If you want peace be peaceful.
Mardonis
Posts: 139
Joined: Wed Jun 29, 2011 7:54 pm

Re: javascript linting error

Post by Mardonis »

Would this be the same?

if (foo === undefined) {
bar;
} else {
foo;
}
User avatar
KyleMassacre
Posts: 573
Joined: Wed Nov 27, 2013 12:42 pm

Re: javascript linting error

Post 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"
Mardonis
Posts: 139
Joined: Wed Jun 29, 2011 7:54 pm

Re: javascript linting error

Post 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.
User avatar
Jackolantern
Posts: 10893
Joined: Wed Jul 01, 2009 11:00 pm

Re: javascript linting error

Post by Jackolantern »

I have always loved ternaries and find them very quickly readable compared to an IF statement, but to each their own :)
The indelible lord of tl;dr
Post Reply

Return to “Coding”