Null
Lastly, let me introduce you to a new data type: null. This type only has one value: null
. It carries no information, cannot be changed, and has no functions you can call. So, what is it good for? It is a variable’s value when we don’t give it one from the start. Try out the following snippet of code:
var inventory print(inventory)
You’ll see that it will print out null
. Sometimes, you’ll want to do this to ensure a variable exists but don’t want to initiate it with a value yet. In the filing cabinet metaphor from Chapter 2, this would mean that we reserved a drawer and a name for the variable but haven’t filled it with data yet.
Using a variable in any way while it is null will result in an error. For example, the next two operations will result in an error while running the code:
var inventory inventory.append("Boots") var number_of_lives number_of_lives -= 2
So, it is best to check whether a variable is null
if...