[ Web Proxy ]
URL:
Viewing: https://javascript.info/task/style-errors [Back]  [Original]

Bad style
EN

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

    Search on Javascript.info:
    Search in the tutorial:
    Light themeDark theme
    DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek
    back to the lesson

    Bad style

    importance: 4

    Whats wrong with the code style below?

    function pow(x,n)
    {
      let result=1;
      for(let i=0;i<n;i++) {result*=x;}
      return result;
    }
    
    let x=prompt("x?",''), n=prompt("n?",'')
    if (n<=0)
    {
      alert(`Power ${n} is not supported, please enter an integer number greater than zero`);
    }
    else
    {
      alert(pow(x,n))
    }

    Fix it.

    solution

    You could note the following:

    function pow(x,n)  // <- no space between arguments
    {  // <- curly brace on a separate line
      let result=1;   // <- no spaces before or after =
      for(let i=0;i<n;i++) {result*=x;}   // <- no spaces
      // the contents of { ... } should be on a new line
      return result;
    }
    
    let x=prompt("x?",''), n=prompt("n?",'') // <-- technically possible,
    // but better make it 2 lines, also there's no spaces and missing ;
    if (n<=0)  // <- no spaces inside (n <= 0), and should be extra line above it
    {   // <- curly brace on a separate line
      // below - long lines can be split into multiple lines for improved readability
      alert(`Power ${n} is not supported, please enter an integer number greater than zero`);
    }
    else // <- could write it on a single line like "} else {"
    {
      alert(pow(x,n))  // no spaces and missing ;
    }

    The fixed variant:

    function pow(x, n) {
      let result = 1;
    
      for (let i = 0; i < n; i++) {
        result *= x;
      }
    
      return result;
    }
    
    let x = prompt("x?", "");
    let n = prompt("n?", "");
    
    if (n <= 0) {
      alert(`Power ${n} is not supported,
        please enter an integer number greater than zero`);
    } else {
      alert( pow(x, n) );
    }

    Web Proxy Viewer  |  New URL  |  Original Page