'How to add if statement in arrow function
i'm a beginner in JS and was wondering what is the syntax of an arrow function with an if statement with a regular function such as function
getStringLength(string){
let stringLength;
if (string.length === 1){
stringLength = `La chaîne contient qu'un seul caractère`;
} else {
stringLength = `La chaîne contient ${string.length} caractères`;
}
return stringLength;
}
Solution 1:[1]
That would be
const getStringLength = (string) => {
let stringLength;
if (string.length === 1){
stringLength = `La chaîne contient qu'un seul caractère`;
} else {
stringLength = `La chaîne contient ${string.length} caractères`;
}
return stringLength;
}
Solution 2:[2]
With ternary this would look like this using an arrow function.
Note that with arrow functions you can avoid using the return keyword
const getStringLength = (string) => string.length === 1 ? `La chaîne contient qu'un seul caractère` : `La chaîne contient ${string.length} caractères`
console.log(getStringLength('a'))
console.log(getStringLength('abcdef'))
Solution 3:[3]
You can also do it in one line
const getStringLength = (string) =>
string.length === 1 ?
`La chaîne contient qu'un seul caractère` :
`La chaîne contient ${string.length} caractères`
console.log(getStringLength('a'))
console.log(getStringLength('ab'))
Solution 4:[4]
Like this
const getStringLength = (string) => {
let stringLength;
string.length === 1 ? ( stringLength = `La chaîne contient qu'un seul caractère`) : ( stringLength = `La chaîne contient ${string.length} caractères`);
}
return stringLength;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nick |
| Solution 2 | RenaudC5 |
| Solution 3 | R4ncid |
| Solution 4 | Mohit Maroliya B17CS036 |
