A note on JavaScript arrays creation & initialization

I use PHP a lot in my projects and it happens that sometimes I combine PHP with another language and write completely useless code.

PHP arrays can be created and initialized with like this:

  $cities[] = "mecca";
  $cities[] = "medina";

I thought that the same would apply to javascript… Yes, it can work, but only if the array already exists, otherwise you will get an error, Your browser will tell you that it can’t find that array, pretty simple… maybe…

var cities = []// we create the array first
  cities[0] = "mecca";
  cities[1] = "medina";

Note that JavaScript doesn’t automatically assign table indexes, you have to set them automatically. +1 for PHP (on most other languages)

Leave a Reply

Your email address will not be published. Required fields are marked *