BY Simmi Kava
JavaScript: Return Statement Behavior
Return Atypical Behavior
What would be the output of below JavaScript code and why?
Example 1
Array.from([3, 4],
function (value, index) {
return value + 1;
}).toString()
Output:
"4,5"
Example 2
Array.from([3, 4],
function (value, index) {
return
value + 1;
}).toString()
Output:
","
Surprised? Go back to the code example and revisit how the return
statement is placed in each of the above example.
The return
statement and the expression
must be placed in the same line.
Example 1 return
statement is written as:
return value + 1;
Example 2 return
statement is written as:
return
value + 1;
In the Example 2, a Semicolon is a automatically inserted after the return
statement. Hence, anything after the return statement has no impact on the logic and since the expression is ignored, the return value is undefined
and when we call toString() on undefined
, it returns empty value and index.
Visit ECMAScript: The return Statement link to learn more.
BY Simmi Kava
Like | Comment | Save | Share |
ARCHIVES
2024
2023
2022
2021