Get the first and last item in an Array - JS

I've modified your code :

var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];

function firstAndLast(array) {

var firstItem = myArray[0];
var lastItem = myArray[myArray.length-1];

 var objOutput = {
   first : firstItem,
   last : lastItem
  };

return objOutput;
}

var display = firstAndLast(myArray);

console.log(display);

UPDATE: New Modification

var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];

function firstAndLast(array) {

var firstItem = myArray[0];
var lastItem = myArray[myArray.length-1];

var objOutput = {};
objOutput[firstItem]=lastItem

return objOutput;
}

var display = firstAndLast(myArray);

console.log(display);

ES6

var objOutput = { [myArray[0]]: [...myArray].pop() }

var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];

var objOutput = { [myArray[0]]: [...myArray].pop() }

console.log(objOutput);

As of 2021, you can use Array.prototype.at()

let colors = ['red',  'green', 'blue']

let first = colors.at(0) // red
let last = colors.at(-1) // blue

To read more about Array.prototype.at()


With ES6 and destructuring:

const myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];

const { 0: first, length, [length -1]: last } = myArray //getting first and last el from array
const obj = { first, last }

console.log(obj) // {  first: "Rodel",  last: "Betus" }