In: Computer Science
// 5. Predict what the following code will print (write it
down), then try it.
var myVariable = "global";
var myOtherVariable = "global";
function myFunction() {
var myVariable = "local";
return myVariable;
}
function myOtherFunction() {
myOtherVariable = "local";
return myOtherVariable;
javascript
// global variables
var myVariable = "global"; // variable contains a string "global"
var myOtherVariable = "global"; // variable contains a string "global"
// function to return a string which is "local"
// variable inside the function is local scope local variable
function myFunction() {
var myVariable = "local"; // variable contains a string "global"
return myVariable; // return the variable
}
// function to return a string which is "local"
// variable inside the function is local scope local variable
function myOtherFunction() {
myOtherVariable = "local"; // variable contains a string "global"
return myOtherVariable; // return the variable
}
// display the global vars
console.log("My global var: " + myVariable);
console.log("My other global var: " + myOtherVariable);
// function calls to display the returned local vars
console.log("My local var: " + myFunction());
console.log("My other local var: " + myOtherFunction());
I HAVE EXPLAINED THE CODE IN USING COMMENTS.
IF YOU NEED FURTHER HELP PLEASE COMMENT.
THANK YOU