Sharepoint - REST API call in SharePoint gets result, but when returns result becomes undefined

You have to learn all about the async nature of REST calls.

It is like when you order someone to get you a coffee:

the request is Asynchronous; you do not get an immediate response

Your function getItems can not have a return value, as the Ajax request is still fetching your coffee.
That is why your getItems Function returns undefined

And your return in the success callback is not the return for getItems,
that return value goes nowhere, Callbacks can not return values

You have to learn the difference between (oldskool) CallBacks and (more powerfull) Promises
(Note: in future JavaScript versions you will learn to use Generators/Async/Await)

If you go with the Promises pattern you will do something like:

function getItems(url) {    
    return $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        }
    });
}

getItems( "/_api/Web/Lists/GetByTitle('Tasks')/Items" ).done(function(data){
     data.d.results.forEach(function(item){  // no need for oldskool for loops
        console.log( item.ID, item.Title );
     });
});

also read: REST call to get list not working

iREST


There is one more way to implement. Please refer below code:

var url = "/_api/Web/Lists/GetByTitle('LISTNAME')/Items?$select=ID,FIELD1,FIELD2,FIELD3";

getItems(url).then(getItemsSuccess, getItemsFail);

function getItems(url){
    return $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        }
    });
}

function getItemsSuccess(data){
    if(data.d.results.length > 0){
        console.log(data.d.results);
        var result = data.d.results; // set value of result variable 
    }
}

function getItemsFail(err){
    // error callback
}

Try in this way:

function getItems(url,success) {    
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {
            console.log(data.d.results);
            success(data.d.results);
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}

and then just call the function like:

getItems('YOUR URL',function(data){
var result = data;
// Use 'result' variable
});

Callback function always works.