The problem is the Javascript execution sequence.
In this your code, when the browser loads and processes your HTML, it puts on the screen the 2 inputs, and then processes the script tag and executes the code that is inside.
At this point, it already takes the content of the inputs and stores in the variables, but the page has just loaded and the user has not yet made any interaction, so the fields are empty, so it converts "empty" to integer and stores in the variables x and y.
When the user clicks on the button, it only recovers those values that are already fixed as invalid (because it was processed when loading the page) and the calculation goes wrong.
You can see this if you already assign an initial value to inputs:
var x = parseInt(document.getElementById('num1').value, 10);
var y = parseInt(document.getElementById('num2').value, 10);
function calpp(){
alert(x+y);
}
<form>
<input type="number" id="num1" value="5">
<input type="number" id="num2" value="3">
<input type="button" value="oi" onclick="calpp()">
</form>
With the initial values your code works, but if the user changes it will stay forever with the initial values because the lines that recovers the values of the inputs and saved in the variables was already executed when the page was loaded.
That’s why when you move into the function it works! When it is inside the function and you click on the button, the values are recovered at the time of the input, so the value that is typed there at that time.
It is important to understand this flow of HTML, Javascript and CSS execution to avoid this kind of situation.
Finally, your code with the correction:
// Podemos até declarar as variáveis fora da função
var x;
var y;
function calpp(){
// Mas devemos sempre recuperar os dados do estado atual da aplicação
x = parseInt(document.getElementById('num1').value, 10);
y = parseInt(document.getElementById('num2').value, 10);
// E por fim exibi-los
alert(x+y);
}
<form>
<input type="number" id="num1">
<input type="number" id="num2">
<input type="button" value="oi" onclick="calpp()">
</form>
Please rewrite your question in Portuguese, since here is the Portuguese stackoverflow.
– Wictor Chaves
And why you want to assign values outside the function?
– Wictor Chaves