Despite the similarity in name and the constant “warnings” of both Java and JavaScript’s unavoidable death, both are still popular languages. More than that, both Java and JavaScript are great segues into other languages. Learning one or the other before languages like Python gives you a certain “je ne sais quoi,” almost an “I-walked-uphill-both-ways-to-school” badge of honor. Suffice to say, they are widely used, and good to learn. With that said, there are some differences between the two. Let’s start with some of the basics.
Arrays: Types
Java
Arrays in Java must contain the same type elements. For instance, if you declare an array of type “int”, then every element in that array better be of type “int”.
The above code compiles just fine and returns as expected. But, what if we throw in some strings?
The code won’t compile, and returns an error telling us what we expected: that we can’t have Strings in an int array! But… what if we try putting chars in there instead of Strings? Things get a little interesting…
When 2 and 3 are chars, not only does the code compile and return properly, but also we get some unexpected (perhaps) results. Where did that 49 and 50 come from? In this case, the Java Compiler is interpreting our chars, ‘1’ and ‘2’, and returning their ASCII Codes.
JavaScript
In JavaScript, an array CAN contain elements of different types. For example:
Our array myArray has both Strings as well as ints. JavaScript compiles successfully, no errors or exceptions are thrown, and the world continues to spin.
Arrays: Indices
Java
In Java, there are limitations on what can and cannot be accessed in an array. For instance, in our previous array, “intArray”, we can access elements in indices 0–6 (remember, 0-indexing here!) with no problem, as our for-loop shows.
But, what happens if we try to access an element beyond what our array contains, index 6, say?
As you can see, we’re successfully able to change the value of the element at Index 3 from 3 to 5690. But when we try to change the value of the element at index 8 (in our array of only 6 indices), we throw an Out of Bounds Exception.
When we set our for-loop to increment i to one more than the length of our array, it prints out all of the elements that exist but throws an exception as soon as it tries to access an index that’s not there. What if we try this in JavaScript???
JavaScript
In JavaScript, when we try to add an element to an index that does not already exist, something very different happens:
In JavaScript, the new element is not only successfully added, it also creates indices for all of the elements in between! What if we try to insert an element into index 100 instead of index 10?
JavaScript STILL creates all of the new indices. Holy Smokes!
Questions, Comments, Concerns? Did I totally screw up somewhere or leave something out? Let me know!