JavaScript define and return a variable on one line

前端 未结 3 740
轻奢々
轻奢々 2021-01-25 03:19

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?

re         


        
3条回答
  •  旧时难觅i
    2021-01-25 03:43

    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';
    }
    

提交回复
热议问题