3

I want to write an algorithm into javascript and I am sure I wrote true . the algorithm gives a number from user and gives the user the result : 1+3+5+...+(2n+1) and "n" is var. the javascript gives me errors : calc() is not defined , unexpected token;

<html>
<head>
    <title>Algorithm</title>
    <script type="text/javascript">
        function calc(){
            var n = document.getElementById('value').value;
            var sum = 0, i = 1, k = 0;
            for(k=0,k<n,k++){
            sum = sum += i;
            i+=2;
            k++;
            }
            document.getElementById('answer').innerHTML = sum;
        }
    </script>
</head>
<body>
    <input type="text" id="value" placeholder="Enter your number"/>
    <button onclick="calc()">OK</button><br/>
    <h1 id="answer"></h1>
</body>

3
  • 1
    This line sum = sum += i; looks dodgy Commented Aug 3, 2014 at 8:03
  • 1
    In the for loop header, you should use ; instead of ,: for(k=0;k<n;k++){ Commented Aug 3, 2014 at 8:05
  • Possible duplicate of for loop causing "Unexpected token" error Commented Nov 20, 2017 at 22:37

5 Answers 5

4

The problem is your for loop syntax. You need to use a semi-colon ; to separate the statements:

for( k = 0; k < n; k++ ){
 ...
}

Taken from the MDN documentation:

Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.


The JavaScript engine can not parse your for loop and then it encounters the closing bracket of the loop (which it wasn't expecting as it was still trying to parse the conditions of the loop).

Sign up to request clarification or add additional context in comments.

Comments

2

The for() statement needs semicolons (;) instead of commas (,).

for (var k=0; k < n; k++) { 

The "jshint" tool can be very helpful in catching mistakes in javascript. There's a web version of it on jshint.com

Comments

1

for(k=0,k<n,k++){

You're using commas instead of semicolons.

Comments

1

That is because you should have ; instead of , in for syntax.

for(k=0;k<n;k++){...}

Comments

0

Your for statement is using commas instead of semi-colons. Change it to use ;.

for(k=0,k<n,k++){
    sum = sum += i;
    i+=2;
    k++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.