in Javascript, in the return statement of a function, I cannot explicitly declare a variable like that return let text = "hello world!"
, so far so good
But also, when I declare a variable I can do it without a keyword like var
, let
or const
, it's what w3school call an automatically declared variable : https://www.w3schools.com/js/js_variables.asp like that : newVariable = "I'm a new variable"
instead of that : let newVariable = "I'm a new variable"
or that : const newVariable = "I'm a new const variable"
Now, I noticed that if I use an automatically declared variable in a return statement, it seems to have declared the variable outside of the function scope :
let myP = document.getElementById("output");function printInfos(name, age) { return info = `${name} is ${age}`;}printInfos("john", 4);myP.textContent = info; // output "john is 4"
<p id="output"></p>
What I suppose is happening is the following :
- the function return the whole expression after expansion
info = 'john is 4'
- then it is evaluated as an automatically declared variable
info
But I wonder how much it is good practice or not ?
I already consider automatically declared variables as bad practice, but in most cases I'm not even sure why other than readability (when I see the variable without keyword I wrongly assume it has been declared earlier), since I can treat them just like a declaration with let
But the case of a declaration inside a return statement confuses me since it allows me to do something I cannot do when I "properly" declare the variable, it feels like a bug
so what is it ? Can I use it ?