Arrays and Functions doubt

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);

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);
1 Like