JavaScript define and return a variable on one lin

2020-04-21 02:01发布

In JavaScript, if I want to return a variable but don't want to modify it or leak it into the global scope, can I define and return it on one line like this?

return var Foo = 'bar'

However, I don't think I've seen this anywhere, I more commonly see this:

var Foo = 'bar'
return Foo

The first one is a bit less redundant, but is it bad practice?

标签: javascript
3条回答
疯言疯语
2楼-- · 2020-04-21 02:24

I cannot see why you would want to do that since once you return you are out of scope.

Just do

return 'bar';
查看更多
We Are One
3楼-- · 2020-04-21 02:35

It’s a bit difficult to offer a useful answer without understanding what you’re trying to do, but this:

return var Foo = 'bar'

isn’t valid JavaScript, so you certainly can’t do it that way.

I agree that your second example is redundant - there’s no point declaring a variable in a function if you’re only going to refer to it when you return it. The way to remove that redundancy is to not declare a variable at all:

function exampleFunction() {
    return 'bar';
}
查看更多
家丑人穷心不美
4楼-- · 2020-04-21 02:37

Well, you'll definitely need to declare the variable in the scope you want it in. You can then set the value, and return it in one line:

var Foo; // Declares Foo in this scope, though this expression has no L-Value
return (Foo = 'bar'); // Sets Foo to 'bar' and returns the value of Foo

It's questionable why you're doing this though. Ideally, Foo would be declared somewhere else in some parent scope. Or, you'd return a new function that would enclose the value of Foo.

查看更多
登录 后发表回答