to make data layer variable and Custom java script variable work the same in GTM

You need to write code for a javascript variable in GTM that will work similarly to a data layer variable. My current code doesn’t work in GSM, what’s wrong with it?

function() {    
  var res = null

  if (dataLayer[dataLayer.length - 1] == undefined) {
    res = 'undefined'
  } else {
      res = dataLayer[dataLayer.length - 1]['eventCategory']
  }
  return res
}

Task: to make data layer variable and Custom java script variable work the same in GTM

enter image description here

enter image description here