Matchleader
Matchleader

Reputation: 77

unexpected token ( for javascript

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>

Upvotes: 3

Views: 11780

Answers (5)

Kyle Emmanuel
Kyle Emmanuel

Reputation: 2221

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

Upvotes: 0

Mritunjay
Mritunjay

Reputation: 25892

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

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

Upvotes: 1

Lix
Lix

Reputation: 47986

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

Upvotes: 4

Zaenille
Zaenille

Reputation: 1384

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

You're using commas instead of semicolons.

Upvotes: 1

Ask Bj&#248;rn Hansen
Ask Bj&#248;rn Hansen

Reputation: 6943

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

Upvotes: 2

Related Questions