First of all we will learn about two properties:
Return Value: Returns the language your Browser is using.
Return Value: Returns an array containing the user’s favorite languages.
Use a conditional statement
We can use the IF conditional statement to check if the navigator.languages property is an empty string. Otherwise, we can get your Browser’s preferred languages from which to get the language, are used by taking the first value of the return array. If any, we will run and call the navigator.language property to get the user language.
if (navigator.languages != undefined) console.log(navigator.languages); // navigator.languages = ['en', 'vi', 'vi-VN', 'fr-FR', 'fr', 'en-US'] else console.log(navigator.language); //'en'
In this example, when we take the first element out, its value is equivalent to the return value of the navigator.language property. Because the first value of the array will be the language used by the Browser.
Use Conditional (Ternary) Operator
We use the Conditional (Ternary) Operator to do the same things as the conditional statement.
(condition) ? x : y
- x: is the code to be called when the previous condition is true.
- y: is the code to be called when the previous condition is false.
navigator.languages != undefined ? console.log(navigator.languages): console.log(navigator.languages);
Because they run in a browser, the result of the ternary operator is the same as the conditional statement. So the navigator returns the navigator.languages property is also an array of 6 elements.
The reason we prefer using the
navigator.languages property over the
navigator.language property is because it contains a list of languages by priority which will be more precise than the navigator.language. The navigator.languages property can return undefined or is an empty array, so we have to use conditions to prevent this from happening and avoid outputting an unsatisfactory value.
Maybe you are interested:
Name of the university: UTC