0
Briefly I would like to define limits where the square can walk, I send my code and I appreciate any help.
var topo=50;
var esq = 200;
 
function cima(){
   topo -= 5;
   document.getElementById("quadrado").style.top = topo + "px";
}                       
function baixo(){
   topo += 5;
   document.getElementById("quadrado").style.top = topo + "px";
}           
function esquerda(){
   esq -= 5;
   document.getElementById("quadrado").style.left = esq + "px";
}
function direita(){
   esq += 5;
   document.getElementById("quadrado").style.left = esq + "px";
}
function rosa(){
    document.body.style.backgroundColor = "pink";
}
function amarelo(){
    document.body.style.backgroundColor = "yellow";
}
function azul(){
    document.body.style.backgroundColor = "blue";
}   
#quadrado{
        position: absolute;
        top: 50px;
        left: 200px;
        width: 120px;
        height: 120px;
        background-color: red;
 }
 table{
        width: 200px;
        border: none;
 }
<h1>Quadrado móvel</h1>
<div id="quadrado"></div>
<table>
     <tr>
            <td></td>
            <td><button onclick="cima();">Cima</button></td>
            <td></td>
     </tr>
     <tr>
            <td><button onclick="esquerda();">Esquerda</button></td>
            <td></td>
            <td><button onclick="direita();">Direita</button></td>
     </tr>
     <tr>
            <td></td>
            <td><button onclick="baixo();">Baixo</button></td>
            <td></td>
     </tr>
     
     
     
</table>
<h1>cores de fundo</h1>
<table>
<tr>
            <td><button onclick="rosa();">pink</button></td>
            
     </tr>
     <tr>
            <td><button onclick="amarelo();">yelow</button></td>
            
     </tr>
     <tr>
            <td><button onclick="azul();">blue</button></td>
            
     </tr>
</table>
you can validate the value and if you are "outside" the return limits without changing, for example:
function cima(){ if (top < 0) return;
 topo -= 5;, and can do this with all positions, just put the limits. I edited your question to make it easier to understand how it works– Ricardo Pontual