JavaScript is a dynamically typed language, which means that it assigns the type based upon how it is used. The data type can change as values, and their types, change as the program executes. Without care of the data types, this can cause errors to occur.
Consider the following code:
let val = 5; // val is a number
val = "Hello"; // val is a string
val = []; // val is an object ... arrays are objects in JavaScript
val = true; // val is a boolean
We can test this theory with the typeof()
function which JavaScript lets us use.
JavaScript has both primitive data types and objects. Most things in JavaScript are objects.
Because JavaScript is dynamically typed, it will often try to do conversions for you.
For example, consider:
console.log(1);
console.log("1");
Both of these will display the number one in the console window, without showing a data type.
So, what do you think will happen here? Will it concatenate the two values, or add them?
console.log(1 + "1");
Do you think reversing the order of the items will change how it will be handled?
If you use the typeof()
function, you can see how the data is being stored internally.
console.log( typeof(1) ); // number
console.log( typeof("1") ); // string
console.log( typeof(1 + "1") ); // string
What about if they subtract? Well, in that case, JavaScript will convert them to numbers, since they cannot de-concatenate…
console.log(1 - "1"); // 0 - the number
Odd Primitives
In JavaScript, not all primitives behave the same, however. null
and undefined
are both considered primitives, but do not have wrapper classes, and might require special consideration when used in conditional operations, for example.
Wrapper Classes
Except for the above mentioned null
and undefined
, JavaScript provides classes to augment the primitives.
Depending upon the wrapper, you get access to different values. For example, Number has the min and max values possible, as well as NaN (Not a Number) in case there is an error in your math, or something JavaScript cannot figure out, such as dividing by zero.
JavaScript Data Types was originally found on Access 2 Learn
2 Comments
Comments are closed.