I'm new to JavaScript and I'm just trying to understand why 'z' comes back as undefined.
var z = functionWithParameters(4, 3);
function functionWithParameters(x, y) {
if (typeof z !== 'undefined') {
document.getElementById("functionWithParameters").innerHTML = z;
console.log('inside function: ' + z);
console.log('inside function: z is a ' + typeof z);
}
console.log('before return: z = ' + z);
return x * y;
}
console.log('outside function: z = ' + z);
<p id = "functionWithParameters"></p>
<script>
functionWithParameters(4, 3);
</script>
If I run the code as is, without commenting anything, it results with:
before return: z = undefined
outside function: z = 12
inside function: 12
inside function: z is a number
before return: z = 12
If I removed: if (typeof z !== 'undefined'), the code results with:
inside function: undefined
inside function: z is a undefined
before return: z = undefined
TypeError: document.getElementById(...) is null[Learn More] (from Firefox),
and the line: console.log('outside function: z = ' + z); does not execute. I though may this was because the function has a return statement, but commenting out the return did not change the results.
Any help with understanding this would be awesome. Thanks for any feedback.