Compare the given strings and display the string that comes alphabetically first. Need help with this question, anything I try ends up wrong.
var personName1 = "Ann"; // Code will be tested with different names
var personName2 = "Anthony";
You're looking for the sort feature.
Throw the items into an array, sort them, and return the first result.
var names = ['Bob', 'James', 'Billy'];
console.log (names.sort()[0])
Add those variable reference to an array after which you can use sort & localCompare method to get the sorted array
var personName1 = "Ann";
var personName2 = "Anthony";
var items = [personName1, personName2];
items.sort((a, b) => a.localeCompare(b));
console.log(items)
The basic thing you need to do is add the two variables you have provided in an array and apply the sort function on them. The sort function will sort the arry in your case in lexicographical order. After sorting the array the first element will return the alphabetically first element. The Code-
[personName1, personName2].sort()[0]
Hope it helps.
Basically you are storing the variables or names in an array and sorting it, when you sort it you will get an array returned and you are fetching it by index zero.
[personName1, personName2].sort()[0]
This is smaller code version of mdawsondev's answer.
var personName1 = "Ann"; // Code will be tested with different names
var personName2 = "Anthony"; // Code will be tested with different names
if (personName1 > personName2)
{
console.log (personName1);
}
else
{
console.log (personName2);
}
In this exercise that I take before, the logic is compared variables in JavaScript that's the purpose of the exercise.