0
var id = id++;
console.log(id);

I just wonder why this isn't work? I put it inside a function, I was expecting it start from 2, and then increment 1 by 1. But in the console what I see is NaN. Why?

1
  • var id = id++; (id++? before id is available ?,so id = undefined ) Commented Dec 7, 2013 at 12:06

6 Answers 6

3

Unless you initialize a variable (=assign some value to it), its value is undefined and undefined++ is not a number (NaN).

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

Comments

1

id is undefined, undefined++ is NaN.

You are using a variable which is not defined before, so NaN is the answer.

Comments

0

You are not assigning any value to id.

You need to initialize it.

Try:

var id = 1;
id++;
console.log(id);

Comments

0

Didn't you mean?

var id = 1;
id++;
console.log(id);

Comments

0

You can't increment something that isn't already defined. So undefined ++ is NaN.

Comments

0

The problem was that you didn't asign a value to "id" variable, so first you need to declare and initialize a variable, then you can manipulate it's value.

var id; //declare
id = 1; //initialize;
id += 1 or id++ //manipulate it(increment the value with 1);

or shorter:

var id = 1;
id++;

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.