Register Login

Swapping fname and lname in JavaScript

Updated Jun 13, 2020

Introduction

A common operation in programming is swapping the values of two or more variables. You might need this for other operations such as adding or replacing values within the code. In JavaScript, swapping the values of two variables is fairly simple and easy.

Let us look at an example to get a better idea about this.

Example

<html>
<head>
<script>
function swapfnamelname(){
var fullname = document.getElementById("fullname").value;
var [fname, lname] = fullname.split(" ");
alert(lname+" "+fname);
}
</script>
</head>
<body>
<p>
  <label for="fullname">Full Name:</label>
  <input type="text" name="name" id="fullname">
</p>
<p><input type="button" name="button" id="button" value="Submit" onClick="swapfnamelname()"></p>
</body>
</html>

Explanation

In the example given above, you can see that the HTML code represents a page where you can enter your full name, including your first and last name. There is a button which you can click to interchange the values of the first and last name.

In the JavaScript function swapfnamelname(), you can observe that the value of the full name entered by the user is assigned to a variable called fullname. Then in the next line, this text value is separated using the split() method and is stored in variables fname and lname respectively. The last line of the code shows an alert box, where the value of the lname variable is shown first and then the value of the fname variable.

This way the values stored in the variables are swapped successfully.

Conclusion

The process of swapping the variable values of fname and lname is pretty straightforward using the split() method. But you can also use a temporary variable to swap values between two variables.


×