3.7. Understanding Language Differences

There's one difference I want to talk about in how programming languages approach the idea of data types. Now make no mistake, they all consider it important, but there's a difference in where and when they most focus on this question of what type of data do I have right now.

In many languages like Swift and C++, when you declare a variable, you're both naming it and giving it a type. Even before you've provided a value for it, you have attached type information. In the example shown in Fig 3.7.1, an integer is attached to the container.

Image

Fig 3.7.1: How to declare a variable in a statically typed or type safe language

So whatever value goes in here, it must be an integer but is one specific type. Now, if a language enforces this idea, that is, if it makes you write code that says that every variable must be all of a specific type. This is often referred to as a statically typed or type safe language, but a few other languages have a different perspective from this.

In Python and JavaScript, for example, when you declare a variable, you're doing it without providing the type information. It's just a container. You can put anything in it and then at some point you will give it a value.

Now that value might be an integer, a string, or a boolean, but the data type belongs to the value, not the variable container. So, in those languages you can code like I've got in Fig 3.7.2: you can declare a variable, set it to an integer, then change it to a string, and then change it to a Boolean or a float.

Image

Fig 3.7.2: How to declare a variable in a dynamically typed language

This would not be allowed in a language like Swift or C++. You wouldn't even be able to compile your code. When a language favors this approach, it's usually referred to as a dynamically typed language, meaning you don't actually know for sure what the type of a variable it is until you look at the value inside it, and it could be different the next time you run the program.

There are benefits and downsides to each approach. It's something that can almost cause a religious war between programmers as to which approach is better, but it's not a war we need to have. So, in the next chapter, we're going to explore an area where languages are really significantly alike, where we must manage the flow of our program, control how our code runs and the choices that we're going to make inside of it.