In this lesson I show what a Clojure keyword is and why we prefer them as keys in maps; and the three ways we can look up a value in a map.
Instructor: [00:00] In this lesson, we'll learn how to look up a value in a Closure map. We'll also find out what Closure keywords and how they differ from symbols. We often need to deal with the JSON-formatted data in ClosureScript, and so we want to convert between JavaScript data structures and Closure data structures.
[00:19] We convert JavaScript arrays into closure vectors, and JavaScript objects into closure maps. A Closure map resembles an ES6 map in that the keys may be of any type, but most commonly we use keywords as keys.
[00:34] Keywords are a basic data type in Closure, just like strings, numbers, Booleans, or symbols. Symbols are what's often called identifiers in other languages. Keywords look like symbols except that they begin with a colon.
[00:49] For example, greeting would be a symbol whereas :greeting would be a keyword. Let's see how they differ. A JavaScript object is a set of key value pairs in which the keys are stings, but a string in closure is data. It's something we manipulate with our program.
[01:07] A keyword, however, is a part of our program. It's a marker or label that is significant in the context of the code. It's a bit like what ES6 calls a symbol. Let's open a Closure script wrapple to see how a keyword differs from a symbol. We start a wrapple by saying Lumo without any arguments. Here's the link to install Lumo if you need to.
[01:35] We can bind a value to a symbol with dev. If I say dev foo "123," I bind the value 123 to the symbol foo. The active binding is a side effect from the functional programing point of view. What dev returns is printed out below. It's Closure's way of representing the var foo. We won't talk about the differences between symbols and vars right now.
[02:03] Now, if I say foo, it evaluates to the string 123. What if I try to bind a value to a keyword? Ah! That did not go well. Let's not even look at the stack trays. In plain English, the fact is that just like a number or literal string, a keyword can evaluate only to itself. We cannot bind it to anything else.
[02:29] Let's see how we can retrieve a value from a map. First, we'll define a map m containing the key foo in the value var, the key moo and the value 10. You might think you could say something like get, and you'd be right. You can also say m foo. M, the map, is being invoked as a function.
[02:52] A map is of course a function. It's the purest expression of what inputs the keys return what outputs the values. What about colon foo m invoking the keyword as a function? Huh, that works too. A keyword can act as a function and look itself up in a map.
[03:12] You can use whichever form best expresses your intent.