Window.onload behaviour

Window.onload behaviour
0.0 0

#1

I’m trying to understand why console.log(B) is returning ‘undefined’. I cannot find the error. My understanding is that console.log(B) should be returning an object type. If it’s returning undefined, is because B wasn’t assigned what funcion A was supposed to assign.

window.onload = A;
var B;
function A(){
   B = document.getElementById('some_div');
}
console.log(B);

this is my html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="myJs.js">
        
    </script>
</head>
<body>
    <div id="some_div">
        <div></div>
    </div>
    
</body>
</html>

#2

I assume the by the time the window loads, the console.log(B) has already executed. You could test this theory by delaying the console.log(B) with a short delay (see below).

window.onload = A;
var B;
function A(){
   B = document.getElementById('some_div');
}
setTimeout(function() {
  console.log(B);
},1000);

#3

Yes, it was that. I included the console.log inside the function A, and now it returns the object. Thanks you.