JavaScript: Swap the first and last elements of a given array of integers
JavaScript Basic: Exercise-80 with Solution
Swap First and Last Elements in Array
Write a JavaScript program to swap the first and last elements of a given array of integers. The array length should be at least 1.
Visual Presentation:

Sample Solution:
JavaScript Code:
Output:
[4,2,3,1] [1,2,0] [3]
Live Demo:
Flowchart:

ES6 Version:
For more Practice: Solve these Related Problems:
- Write a JavaScript program that swaps the first and last elements of an array and returns the updated array.
- Write a JavaScript function that performs an in-place swap of an array’s first and last elements, handling arrays with a single element correctly.
- Write a JavaScript program that checks if an array has at least one element before swapping its first and last items without using a temporary variable.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript program to test if a given array of integers contains 30 and 40 twice.
Next: Write a JavaScript program to add two digits of a given positive integer of length two.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics