0
Return statement JavaScript
//Why do we need to use return statement? //For example: function add (x, y) { console.log(x + y); } add(10,20); // Will work and value will be 30. //But, if added to reuse in a variable, it won't work? //Example let sum = add(10,20); //Value will be undefined? Why?
5 Answers
+ 3
Functions are small blocks of code that will do things or return things:
Your function is a do something function
In your example:
function add(x, y){
console.log(x + y)
}
any call to add will ask the function add to output (x + y) on the standard output stream
to have your function return something so you can reuse it you have to use the return keyword
function add(x, y) {
return x + y;
}
This is going to return the x + y back to the caller.
let sum = add(10, 20)
sum will now be assigned the value of 30
You could also:
console.log(add(10,20))
and get the same out put of 30 like in the first example.
Hope that helps, happy coding.
+ 4
Jonathan P. Jundarino
Because you didn't return value.
learn about 'return'
+ 1
The community is full of some great individuals sharing information. Wish you well my friend.
0
A͢J thanks. I returned to comment section of return statement inside JavaScript course here. So, when we assign the function inside a variable, it will only do it's job, which is computing the expression. "If you tell me to compute 3+3 then I will only compute" I read something like that. So that's why we need return statement.
0
William Owens thanks so much. I love sololearn community because of people who will answer the questions.