return
does always tell the function “We’re done, spit out the value of the thing to my right.” Think of a function like a little mechanical box that you can put things into and get things out of. Say we have a function called bob:
function bob(){
}
right now, this function is an empty box. it doesn’t do anything. but lets put something inside it, ok?
function bob(){
var foo = 3 * 2
}
now bob is doing something. It is assigning the variable foo
the value of 3*2, but if you called this function, it would still do nothing. We need some way to get the value of foo
out of bob. that’s where return comes in.
function bob(){
var foo = 3 * 2
return foo
}
Now we’re getting somewhere! return tells bob to return foo back to us. so at this point, if you called bob, it would be just like calling foo:
var bar = bob()
is identical to
var bar = 3 * 2
That’s kinda silly, but there are times where maybe you want to hide a complex calculation that always give the same result. and maybe you want to be able to change how the program reaches that result, but you only want to have to do it in one place. Where functions real power comes in is when you put in a value to get out a different value. But you need return on the other end to get anything out:
function bob(foo){
return 3 * foo
}
Now we’re cooking with mesquite! Think of those parentheses after the function name as the opening at the top of the box: whatever you put there is going to go inside. The function will do its magic, and then with the return
statement, it spits back out whatever you want it to spit out.
so calling bob:
bob(2)
will give you 6. But remember, without the return, you will just be sending the 2 in to languish forever.
There are other ways around this structure, but they are usually code smell, and you want to avoid them when possible. Hopefully that will clear up any misunderstanding you have of the return
statement.
The problem we have with your example is that you are calling Array.shift()
twice. each time you call it, it chops the first value off of the array that you are calling it on:
/* say we pass in [1, 2, 3 ,4] as arr and 5 as item */
function nextInLine(arr, item) {
arr.push(item); // at this line, arr will equal [1, 2, 3, 4, 5]
arr.shift(); // at this line, arr equals [2, 3, 4, 5]
return arr.shift(); // at this line, arr equals [3, 4, 5]
/* what Array.shift() does is chop off the value of the first item and
'return' that value. So this second calling of it on arr returns a
a value of '2' instead of the '1' that the challenge is expecting.
*/
}