Learning JavaScript the right way™, part 2

Click here for part 1

JavaScript only has two types of data structures, called Objects and Arrays. Neither is really what the name implies. Many other languages – Java comes to mind – come loaded with a whole list of trees, lists, maps, etc. JavaScript manages to cover all use cases with only two, at the cost of efficiency. They’re both always passed by reference.

Arrays

They should be used to store sets of identical elements. They can contain any type of elements and even mix types inside of the same array, but don’t mix types because it defeats the entire points of arrays. “Real arrays”, as in C, are contiguous blocks of memory. JavaScript “Arrays” aren’t really arrays, instead they’re a specializtion of the JavaScript Object type (more on that in part 3) and they work like lists. JavaScript provides a handy built-in literal notation using square brackets.

var arr1 = [1,2,3,4,5]; //Declares an array with 5 elements
console.log(arr1[0]); //Outputs 1
console.log(arr1.length); //Ouputs 5

Continue reading

A more functional split function

The split function is a major part of modern languages and string processing. It transforms a string (or an array or a list) into a list of sub-elements by splitting on every occurrence of the supplied separator. The best thing about split is that it fits right into modern programming paradigms: a split string can be mapped over and then joined, folded, filtered, etc.

Strictly speaking, split is a looping operation, but unlike a for/while loop, a map or a fold, split operates at a higher abstraction level. It’s an implicit loop. It’s about the WHAT, not the HOW. It’s about the result, not the process. There’s room for improvement, though. It can be made more generic and much more powerful.
Continue reading

Coffeescript: for key, value in array

I just found something really disappointing with Coffeescript.


obj = {a:1, b:2, c:3}
arr = [3,4,5]

# Prints: 3-0, 4-1, 5-2
for v,k in arr
    console.log v+"-"+k

# Prints: 1-a, 2-b, 3-c
for k,v of obj
    console.log v+"-"+k

Notice how I had to invert the key and value in the array loop? It’s annoying. It’s inconsistent. It’s amateurish.

I understand that 98% of the time, for … in is used without the need for a key reference, but sometimes you need to keep track of the loop counter and the coffeescript.org documentation is really not helpful in that regard.

I could make my own loop counter, but it’s even uglier than memorizing this gotcha, so I’m going to stick with the gotcha..