Programming with JavaScript

⌘K
  1. Home
  2. Docs
  3. Programming with JavaScri...
  4. Example Programs
  5. Swap two numbers

Swap two numbers

Example 24:

Write a function expression to swap two numbers

Code

const prompt = require("prompt-sync")();
var SN = (a, b) => [b, a];

let n1 = parseInt(prompt("Enter first number : "));
let n2 = parseInt(prompt("Enter second number : "));

console.log(`Before Swapping : n1 = ${n1} and n2 = ${n2}`);
[n1, n2] = SN(n1, n2);
console.log(`After Swapping : n1 = ${n1} and n2 = ${n2}`);

Output

Example 25:

Write an arrow function to swap two numbers

const prompt = require("prompt-sync")();
var SN = function (a, b) {
  var temp;
  temp = a;
  a = b;
  b = temp;
  return [a, b];
};

let n1 = parseInt(prompt("Enter first number : "));
let n2 = parseInt(prompt("Enter second number : "));

console.log(`Before Swapping : n1 = ${n1} and n2 = ${n2}`);
[n1, n2] = SN(n1, n2);
console.log(`After Swapping : n1 = ${n1} and n2 = ${n2}`);

Output

Loading

Views: 103

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments