Arrays and Functions doubt

Arrays and Functions doubt
0

#1

Hey everyone, hope you guys are having a great day!
So I’m trying to make sense of js and have been experimenting with code, one of which was creating an array inside a function, now I saved that array in a variable, and then when I called the variable outside of the function, it returns undefined. I can’t understand what I’m doing wrong, any help would be appreciated!

Here’s the code:

var x;
function test(){
    x = [{name:'a', age:20},{name:'b', age:21},{name:'c', age:22}];
}

console.log(x);

#2

You must call the function named test, in order for the code inside it to execute.


#3

Declaring a function in itself won’t run the code inside it. If you want the code in a function to run, you’ll need to call it:

var x;
function test() {
  // ...
}

test(); // I'm calling `test`; the code in that function runs.
console.log(x);