The code you have written isn't executed top to bottom, waiting for functions to be executed that are defined - the function assigned to window.onload
is deferred until that event is satisfied, that is the, window has loaded.
Any post-processing of that value needs to happen in that callback too.
window.onload = function() {
var width = parseInt(document.body.clientWidth);
// Now do your work with `width` here.
}
Further reading
Also, the brace style you're using isn't recommended in JavaScript, as some parts of the language don't function as you may intend if you use it to return an object literal, for example.
return
{
prop: 'value'
}
The grammar says there can't be a line terminator after return
, so you would get the standard return undefined
behaviour, with an orphaned object literal.