When you define variables they are hoisted at top of its scope. Let me show you how your current code:
function test(){
var x = 30;
y = 40;
}
var x = 10;
var y = 20;
test();
Will run like this:
// global scope
var x; // x is undefined
var y; // y is undefined
function test() {
// function scope
var x; // x is undefined inside this scope
x = 30; // x is assigned with value 30
y = 40; // y is assigned with value 40
// the global scope y value is assigned
}
x = 10; // x is assigned with value 10
// the global scope x value is assigned
y = 20; // y is assigned with value 20
// the global scope y value is assigned
test();
// when calling test,
// you see x is assigned with its function scope
// and y is assigned with its global scope
// so, at this point
// x becomes 10
// y becomes 40
You can read more about var
here in the docs. Also, look in the scope, global scope and local scope.
Also, note that let and const works differently. They are scoped in the block. You can read them in the corresponding links which are linked here in.