Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAbe Layee
8,378 Pointsreturn in JavaScript.
I am little lost. Why is return so important in JavaScript? Anyone mind telling me about return keyword in javaScript or why is it so useful to return a fucntion. I copied this code from the JavaScript Basic. I am lost with the return 5 part. I understand the rest except the return 5. Why do we have to return 5 instead of return giveMefive? Can a return in function be any number or variable inside a function? Thank you in advance.
function giveMeFive() {
return 5; // Why is it 5 instead of giveMeFive?
}
// prints 5 to the console
console.log( giveMeFive() );
3 Answers
Robert Richey
Courses Plus Student 16,352 PointsFunctions are the actions or verbs in your program. It's common to have a function that returns a value, so that you can use it somewhere else in your program.
Let's take a closer look at that.
// when you call this function, you'll get back the value 5
function giveMeFive() {
return 5;
}
// anywhere you write giveMeFive(); you can instead think of it as being the literal number 5
console.log(giveMeFive());
// giveMeFive() executes first, then it's return value is placed into console.log. Then console.log executes, printing 5.
console.log(5);
Abe Layee
8,378 Pointsso the return can be any value as long is not many characters. A return can only return one value such as string,boolean,number, and so on. I think I got it now.
Robert Richey
Courses Plus Student 16,352 PointsIt's true that a function can only have one return statement, but you could return an array, or object and get many different values back.
function myName() {
var fullName = {
firstName: 'Robert',
lastName: 'Richey'
};
return fullName;
}
// antime I call myName(), I'll get back an object holding two values.
var name = myName();
console.log("My first name is: " + name.firstName);
console.log("My last name is: " + name.lastName);
Abe Layee
8,378 PointsThank buddy for making things clear to me. I apprecaite it man.
Robert Richey
Courses Plus Student 16,352 PointsMy pleasure. Happy to help :)