Roger G. Zapata
Roger G. Zapata

Reputation: 405

Can the return statement in Javascript return multiple things at once?

I just heard a guy from the Treehouse courses saying that the return statement in JavaScript can't return multiple values at once, the example he gave was:

function example() {
var message = "HI";
return 1, message, 'some text';
}

I decided to test this myself but instead of using "," I used the "+" operator, and when tested on Google Chrome worked perfect. This is how I tweaked the code:

function example() {
    var message1 = ' Hi';
    var message2 = ' How are you?';
    return 1 + message1 + message2 + ' Some text!' + message1.toUpperCase();
}

So my question is, Can the return statement behave like this or was simple luck what I did? and is the Threehouse dude right about his statement that "the return statement can't return multiple values at once" ?

Thanks for your help.

PS: I'm new with JS so please try to answer in a non-technical vocabulary if possible! :)

Upvotes: 1

Views: 3855

Answers (2)

Dai
Dai

Reputation: 155145

Functions, generally speaking, only return one value - but that one value can be a collection of values. In JavaScript you can do this with an object with named properties. In other languages like C# and Python you can use tuples (which serve a similar purpose) - and almost any language will let you return an array (though you lose object type information in that case).

Here is a JavaScript example using an object:

function returnMultiple() {
    return { foo: "bar", baz: "qux" };
}

var multiple = returnMultiple();
console.log( multiple.foo );
console.log( multiple.baz );

Upvotes: 3

Mirko Vukušić
Mirko Vukušić

Reputation: 2121

Your code returns a single value too. To understand it better here is example with just one more line:

function example() {
var message1 = ' Hi';
var message2 = ' How are you?';
var mySingleReturnValue = 1 + message1 + message2 + ' Some text!' + message1.toUpperCase();
return mySingleReturnValue

}

So all you're doing is concatenating several "values" to a single value which is a string. I guess you should start with learning types in javascript (string, numeric, object, etc.) and basic things you can do with them (add, substract, concatenate, etc.)

Upvotes: 1

Related Questions