0

[solved]Does any code after a return statement in a function have any effect?

I know that among several return statements only the first one is executed, but what if after a return statement, I reassigned value to a variable ? Will that new value just be ignored? Is any code after a return statement in a function just not even relevant?

21st Mar 2021, 6:27 PM
Einstein Shilly shally
Einstein Shilly shally - avatar
6 Answers
+ 2
Yes any code after a return isn't executed because the control is immediately shifted to from where the function was called. You can use some conditional statements to make sure the return is happening just when required.
21st Mar 2021, 6:31 PM
Avinesh
Avinesh - avatar
+ 4
This is not very likely but it can cause a problem if not understood. You can have an issue if you assign a variable you have used in the function (but not had it passed to the function explicitly). See the code below; function demo() { console.log(n); return; //var n = 0; } var n = 1; window.onload = function() { demo(); } This will output 1, but if the commented-out line is de-commented, you will get a null output. This is because the very fact that you declared the variable inside the function (even though that line was never executed) means that a global variable of the same name is now not visible inside the function. Hope that makes sense!
21st Mar 2021, 6:42 PM
Russ
Russ - avatar
+ 2
No. It is considered dead code https://en.wikipedia.org/wiki/Dead_code
21st Mar 2021, 6:31 PM
Benjamin JĂŒrgens
Benjamin JĂŒrgens - avatar
+ 2
1. see the answer from Russ 2. If it contains syntax errors it could lead to parsing errors
22nd Mar 2021, 5:26 AM
John Doe
+ 1
Avinesh thank you so much
21st Mar 2021, 6:33 PM
Einstein Shilly shally
Einstein Shilly shally - avatar
+ 1
Benjamin JĂŒrgens thank you so much
21st Mar 2021, 6:33 PM
Einstein Shilly shally
Einstein Shilly shally - avatar