Skip to content Skip to sidebar Skip to footer

Declare Variables And Return Value In One Statement In Javascript

In many functions I have noticed the following pattern: function declares variables, combines it to the result and returns result. It is shown in this very simple example: function

Solution 1:

Maybe this works for you, which is not advisable because of using assignment alogn with the comma operator.

functionfn(a, b) {             // declaration in local scopereturn a = 1, b = 2, a + b; // return value with comma operator
}

A newer approach takes default values and returns just the addition of both.

fn = (a = 1, b = 2) => a + b;

Solution 2:

What you are trying to do (declare using var and return in same statement) is not possible with JavaScript syntax.

The most concise you can get is your first option:

functionfn() {
    var a = 1,
        b = 2;
    return a + b;
}
fn(); // 3

Post a Comment for "Declare Variables And Return Value In One Statement In Javascript"