Dynamically Typed JS
10 minute read
Posted by Ryan Large
December 21, 2023
Intro
Lets talk about data types in JavaScript.
We will go over two different data types in JS...
- Primitive Types
- Object Types
But before we talk about these we are going to first talk about the method JavaScript uses to define its types
Dynamically Typed Language
Javascript is a dynamically typed language. This is extremely important to understand so let me make it clear with examples of what I mean by a dynamically typed language and how it works. There are two different ways a language can determine its types of variables, objects, structs and more:
- Dynamically
- Statically
Statically Typed
Here is an example of a statically typed variable in a language like C++, C, Java, Go, Rust, etc.. etc.... etc.......
int myNumber = 24;
.c
What are you looking at here? Lets break it apart. We are going start by reading this code snippet backwards. I am using C in this example, and many languages such as JavaScript, C++ and more use the same conventions as in C where a ";" is used at the end of a statement for what they call a statement delimiter, helping a compiler determine the end of one statement of code to the next. This is where we will start.
- Just to the left of our semicolon we see a numeric value. Here we put the value 24.
- To the left of this we have our assignment operator "=", this will take out numeric value on the right side of the equal sign and place it within a variable name that we create.
- To the left of the assignment operator we give our value a name. We are going to name the value of 24 as the text "myNumber". The equal sign in going to place 24 inside of myNumber
- Finally we have the part of this statement that actually matters in this article. "int"..
So, what is int? Simple, int is out static type definition. We are telling the compiler that our variable myNumber is of a specific type. An integer type.
Incase you did not already realize int is short for integer, it is. As we can clearly determine as humans without much effort the value of our variable myNumber is a number (eg. 24) a computer needs to determine this as well. It needs to know what type our value will be that our variable holds. There are a few reasons we want to specify the type of a variable, but we will go over more of that later. For now, understand that before initializing a variable we need to define its type in a statically typed language like C.
Why is this? We tell the compiler what type our variables value is so knows exactly where and how to store our variable in memory.
Dynamically Typed
Here is an example of a dynamically typed variable in a language like JavaScript, Python, Ruby, PHP, Perl, ect. ect...
const myNumber = 24;
.js
So what is the difference here from the former code snippet? There is a minor difference right? Our type is different. This code snippet is written in JavaScript and the important thing to note here is that our type "const" is actually not a type at all.
So what is const? Const It is a reserve word in many languages and a way to say "hey, this variable myNumber is not allowed to be reassigned to any new value, EVER.". So we are no longer allowed to say myNumber = 10, or myNumber = 24, or perform any other reassigning operation ever again within the scope of this variable.
Anyway let's talk about what matters here. Since const is not a type, this means that in Javascript and many other dynamically types languages, our myNumber variable is not assigned to be of a certain type at all.
So how does our compiler, (or interpreter in the case with JavaScript) know what type our "myNumber" variable is?
You've guessed it correctly if you think that it is figured out on its own. For JavaScript there is a time and place for this operation to take place during compilation and interpreting. Normally for a typical Javascript Engine there is an optimization phase where the engine takes the time analyzing your variables and evaluate past and present implementations of them to better understand a variables evolution within the program and properly assign it a type.
It is extremely important to know that at the end of the day, before machine code and before being processed by the cpu, each variable must have a type. The JavaScript engine running in your browser will do this based on the values that you assign to your variables and how they are used within the context of the application or website you are building. This allows for dynamic type inference at runtime therefore creating a unique and user friendly way to write code. Is this good or bad? We will talk more on that later.
This approach therefore creates an environment where types do not need to be specified within the language itself because at compile time types will be assigned by the Javascript engine interpreter for us instead.
JavaScript Types
Now we have gone over some basic ideas on how JavaScript and other languages might handle types, let's dig into the grouping of the two major data types in JavaScript
Primitive Types
let's list out out Primitive Types after a brief definition
Primitive types are the basic building blocks of a programming language. They represent simple values such as integers, strings, booleans and are not composed of other data types such as a struct. We will go over the types of these variables and how a Javascript engine assigns these types. Essentially all examples will be in the context of Javascript. All JavaScript values are determined by literals and syntax.. Scary I would say
- Integers
- Floating point numbers
- Booleans
- Strings
- Undefined
- Null
- Symbols >= ES6
Integers
const myNumber = 24;
.js
Integers are interpreted as numeric literals. As the engine parses your program and comes across the value 2, the engine will tag this variable with the integer type by knowing that if there are no single or double quotes around the number and as long as it is a valid number and not a character of some sort the engine will be pretty confident you have assigned "myNumber" to equal a number and tag the variable with that type
Floating point numbers
const myFloat = 24.74356;
.js
As like integers, in JavaScript Engines will first look at the value you have stored in myFloat and check if it is surrounded by single or double quotes and if it is not a character. Additionally the engine will notice the period within the numeric literal indicating it should be of a floating point number
Strings
const myString = "Hey, I am a string";
.js
I JavaScript, strings can be wrapped in both single and double quotes. The engine will directly understand that the value assigned to your variable is a string by the double or single quotes around your value. Another great example of type inference by syntax
Booleans
const myNameIsRyan = true;
.js
const myNameIsRyan = false;
.js
Booleans are tagged with a type by the literal text of your value. true and false are reserve words unless wrapped in single or double quotes. So the JavaScript engine can quickly determine the type of a true or false Boolean value
Undefined
const uninitializedType = undefined;
.js
Undefined is a somewhat unique value in JavaScript. It means that the variable you create does not yet have a value. Such as initializing a variable with no predetermined value. If you attempt to access a variable that does not have a value in JavaScript "undefined" will be returned.
The JavaScript engine will tag your variable with undefined if you do not explicitly set a value, or use the key word undefined
Null
const whatIsThis = null;
.js
Null is designed to tell the JavaScript engine that your variable is meant to hold no value or that a function will return no value. Unlike undefined null must be explicitly set.
Object Types
let's list out out JavaScripts Object types and explain them after a brief definition
As in our primitive types section we will be covering object types in the context of JavaScript. Object types unlike primitive types are composed of other data types. They can be composed of other object types or primitive type data types and often times allow for a more dynamic approach to handling and manipulating data in a programming language. We will be discussing...
- Objects
- Arrays
- Functions
JavaScript Objects
const myNewObject = {
myName: "Ryan",
myAge: 24
};
.js
JavaScript Objects are an extremely convenient and special data type in JavaScript. There are multiple kinds of objects that can be created in JavaScript, to name a few..
- Object literals
- Classes
- And even Functions are treated like objects in JS
To simplify the definition of an object in JS we will first cover Object Literals.
Object literals are a data structure that can hold a collection of key value pairs. We can call these key value pairs as an objects properties. Each property can be looked up by its key and a value is returned for whatever you chose to assigned to that key. See the example above.
You can name a key whatever you please in the object as long as it follows the standard variable naming conventions in JavaScript. A key in an object, is like defining a variables name and the is whatever you decide to assign to that variable. Think of it as creating multiple variables inside of a block that can be of any other valid JavaScript type, including other object types
The values you assign to each key can be any valid data structure in the JavaScript language. In other words you can assign a key to be OR return virtually anything. This includes all primitive data types we went over in the previous section and includes all Object data types that we will cover more in depth in this section, such as arrays, other objects, functions or return values from functions.
As you can see, JS objects are pretty cool. And if we think about it a little longer we realize we can do some pretty cool things with this data structure. But lets continue to keep things simple. Here are some great examples and explanations on how these data structures work and how a JavaScript engine will evaluate these structures
Object Literals
const person1 = {
name: "Joe",
age: 45,
relations: []
};
const person2 = {
name: "Ryan",
age: 24,
relations: [person1]
};
.js
We have already briefly discussed object literals in JavaScript above, but we never discussed how they are interpreted and the true power behind them. So let us dive in.
As you can see in the code above we have defined two object literals. They are defined by opening and closing curly braces and for each key within the object literal we place a semi-colon instead of an equal sign to assign values to each key within the object.
Also note that each key within the object literal is of a different type. Notably the relations array. This is really neat. Not only are we storing an array within an object, but the array is storing references to another object. This is powerful!
Any programming language is capable of these features. But JavaScript and other high level languages have make it easy for us to create such data structures. We can easily access the first persons data if within our scope we only have access to person2's data. simply by dot or bracket notation or both. eg...
const person1Name = person1.relations[0].name;
.js
This is amazing on so many levels. We just accessed person1's name through our person2 object. But do not take my word for this. Try it out yourself.
So how is this working? How does this objects references array store the entire state of person1 in it? The short answer is that it doesn't.
How does a JavaScript engine type and create an object? Here is a simplified high level list of the steps an engine would take to type and define an object in JS