Home > Blockchain >  How to add if statement in arrow function
How to add if statement in arrow function

Time:04-29

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;
    }

CodePudding user response:

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;
}

CodePudding user response:

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'))

CodePudding user response:

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'))
  

CodePudding user response:

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;
    }
  • Related