0

I tried using the join() function in my array and tried to document.write it but the console says"birth.join() is not a function "

birthyear=[];

for(i=1800;i<2018;i++){
birthyear+=i
}

birth=birthyear.join();

document.write(birth);
2
  • console.log(birthyear); would’ve revealed the reason for the error. Commented Feb 24, 2018 at 5:59
  • Related: stackoverflow.com/q/3746725 Commented Feb 24, 2018 at 6:12

3 Answers 3

2

Array.prototype.join() works on array and to insert an element to array you should call .push() instead of +=, read more about += here.

Always use var before declaring variables, or you end up declaring global variables.

var birthyear = [];

for (i = 1800; i < 2018; i++) {
  birthyear.push(i);
}

var birth = birthyear.join(", ");

document.write(birth);

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

Comments

1

I your code your not appending data to array you are adding data to array variable which is wrong

1st Way

birthyear=[]; 
for(i=1800;i<2018;i++)
{ 
    birthyear.push(i); 
} 
birth=birthyear.join(); 
document.write(birth);

2nd Way

birthyear=[];
k=0;
for(i=1800;i<2018;i++){
birthyear[k++]=i;
}

birth=birthyear.join();

document.write(birth);

1 Comment

or you can use birthyear=[]; for(i=1800;i<2018;i++){ birthyear.push(i); } birth=birthyear.join(); document.write(birth);
0

You can't apply .push() to a primitive type but to an array type (Object type). You declared var birthyear = []; as an array but in the body of your loop you used it as a primitive: birthyear+=i;.

Here's a revision:

var birthyear=[];

for(let i=1800;i<2018;i++){
    birthyear[i]=i;  
   // careful here:   birthyear[i] += i; won't work 
   // since birthyear[i] is NaN
}

var birth = birthyear.join("\n");

document.write(birth);

Happy coding! ^_^

Comments

Your Answer

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