JavaScript Data Types
Data types are one of the things every JavaScript and developer, and web developer, should know. This page will help you learn all you need to know about the first two, strings and numbers. It will help you understand how these data types work and how you can use them.
Data types
Data types are fundamental blocks of every programming language. Data types are basically a classification, or an attribute, that says what kind of data specific value can have. In some cases, this applies not only to values but also to variables. In JavaScript, there are currently eight data types. Let’s take a look at each.
Strings
The first of data types is a string
. It is also one of the most commonly used data types. A string is something surrounded by either single or double quotes. Between the quotes can be almost anything, characters, numbers, etc. In some sense, string can contain any other data types.
Whatever is there between the quotes, JavaScript will treat it as a piece of text. This also applies to quotes themselves. If you create a string with single quotes you can use single quote characters inside the string only if you escape it with slash (\'
or (\"
)). Otherwise, JavaScript will think that quote ends the string.
You can also add (or concatenate) two or more strings together. In this case, it doesn’t matter if one string uses single quotes and the other(s) double. This is also useful when you want to include some expression in that string.
Length, characters, and cases
Now, what are some things you can do with data types such as strings
? When you want to check the size of the string
, you can use length
property. When you want to access some character, based on its index, you can use charAt()
method. For changing the case, there are toLowerCase()
and toUpperCase()
methods.
Searching strings
You can also search for a substring in a string
, or a piece of that string, using indexOf()
method. This method will return the index at which the first occurrence of the substring begins. If it doesn’t exist, it will return -1
. You can also add optional parameter to specify the index at which the method should begin its search.
Alternative to indexOf()
is lastIndexOf()
. While the indexOf()
starts at the beginning and go to the end, the lastIndexOf()
starts at the end and goes to the beginning. Remember that both, indexOf()
and lastIndexOf()
, will return index of only the first occurrence of the string you are looking for.
Another options for searching strings are includes()
, startsWith()
and endsWith()
methods. The names of these methods say pretty much everything you need to know about how they work. The includes()
returns true
if string includes the substring you are looking for. The startsWith()
returns true
if it starts with the substring.
The last one, endsWith()
, returns true
if the string ends with the substring. Remember that all these methods, including the indexOf()
and lastIndexOf()
are case sensitive. So, pay attention to use the correct case for all characters of the substring you are looking for.
Getting a substring
When you want to get a substring of a string, based on index, you can use substring
, substr
or slice
. The substring
returns a substring between the start and end indices. The slice
returns a substring from start to end, not including the end index. Lastly, the substr
returns a substring, from start, of a length you specified.
The last one, substr
, is not recommended to be used. It is still in JavaScript mainly for historical reasons. Out of these three, the best choice is probably the substring
since you don’t have to remember that it indeed includes the end index in the substring.
Template literals
With string literals you can embed expressions and even unicode codes and hexadecimal and octal literal in the string. You can also use create multi-line strings without the need to use special line-break characters. Template literal is created by using back-tick characters (), instead of quotes.
When you want to include some expression, you wrap the expression with ${}
, or ${some code}
. When you want to create multi-line string, just hit enter key when you need it. It looks almost like magic. Under the hood is JavaScript joining things, such as strings and variables and expressions, and returning strings.
From string to number
Numbers and strings are two different data types. However, that doesn’t mean you can’t play around with these data types. For example, by changing one into another. In JavaScript, there are built-in methods that will help you “convert” these data types. When you want to convert some string
that contains number into a number
there are some ways to do it.
First, you can use parseInt()
. This will convert the string
into an integer. On the other hand, parseFloat()
will convert the string
into a float (decimal). Next, you can use methods provided by Math
object, such as floor()
, round()
and ceil()
. All these method accept number in the form of a string
and return an integer.
The downside of these three is that it will round the number. If you have a decimal and it in that form, these three may not be as useful. Lastly, you can also use unary operator and multiplying the string
by 1. Or, you can simply use Number
object.
One thing to remember for parseInt()
and parseFloat()
. When you convert string to number, and that string contains some non-numerical characters, JavaScript will remove them. It will return only the integer or float.The floor()
, round()
and ceil()
will not work at all. JavaScript will return NaN
.
The same applies to unary operator, multiplication by 1 and Number
object. All these will NaN
. So, if you want to convert a string with numbers, and it contains non-numerical characters, use either parseInt()
and parseFloat()
. Otherwise, modify the string
.
Strings… arrays?
In some languages, such as C, strings are thought of as arrays
of characters. This is not exactly true in JavaScript. In JavaScript, strings
and arrays
might be similar, but they are not the same. For example, both, strings
and arrays
have length
property, indexOf()
and even concat()
methods.
Both, strings
and arrays
, also work with indices. In case of strings
, this was not always the case. For strings
, it is better to use charAt()
method. Another difference is that strings
are immutable while arrays
are mutable. Meaning, you can change the value of an array “in-place”.
In case of strings
, you have to create new string
, modify it and then return it. So, no strings
are not just arrays
of characters. Although similar in many ways, there are differences between strings
and arrays
.
Numbers
Next is a number
. This is another of wildly used data types. In JavaScript, the number
type represents both kinds of numbers, integers and floating point numbers. In other languages, such as C, there are multiple types for numbers, integers, shorts, longs, floats, doubles, etc. This makes working with numbers in JavaScript much easier.
In general, number are in JavaScript expressed as base-10 decimals. When you define some number with a leading zero, i.e. floating point number smaller than zero, the leading zero is optional. The same applies to trailing zero. It is also optional.
You can also end the floating point number with the floating point. However, this is neither recommended nor a good practice as it can confuse some people reading your code, even you yourself. There is one interesting thing in JavaScript. You can shorten the number by appending letter “e” to the number and specifying the zeroes count.
You can use the same also for decimal numbers. In this case, you need to add minus “-” after the letter “e” and specify the number of zeros. This includes the zero before the floating point.
From number to string
As you know, it is possible to “switch” between data types. Or, to convert one data type to another. When you’ve learned about strings
, you’ve learned how to convert strings to numbers. Now, let’s take a look at how to convert numbers to strings.
Third option is using template literals you learned about above, in the section about strings
. The fourth and last option is concatenating the number with an empty string.
Doing some Math
Every number supports standard arithmetic operations, such as addition (+
), subtraction (-
), multiplication (*
), division (/
), remainder (%
) and exponentiation (**
). The numbers
data type also includes hexadecimal and decimal literals as well as binary and octal literals. These were introduced later in ECMAScript 2015.
When you need to perform rounding operations, there is the previously mentioned Math
object with floor()
, round()
and ceil()
methods. The floor()
always rounds numbers down. Tip to remember: floor is down. The ceil()
always rounds numbers up. Tip to remember, ceil(ing) is up. The last, round()
, rounds to the nearest integer.
Aside to these, there is also toFixed()
method. This method rounds the number to number of digits you specify inside the parenthesis. The number of digits refers to digits after the floating point. One thing to keep in mind. The toFixed()
method return string
, not number
.
Testing for integers and floats
There are a couple of ways to test if some number, or anything, is an integer or a float. In case of integer, the best approach is using Number
object and its isInteger()
method. Another option is isSafeInteger()
. This method will check if the provided value is a number that is a safe integer.
Testing for floats is not that straightforward. There is no built-in way to test for this type of number. Here are two quick ways you can test for floats.
One gotcha
There are some gotchas even in data types. The number
data type, especially floats are a good example. This is not true only for JavaScript, but also for other programming languages. The problem is that not all decimal representations are exact. So, when you try to compare them, they will not be equal.
Conclusion: Understanding Basic JavaScript Data Types
In a recap, today, you’ve learned about the two first JavaScript data types, namely, strings and numbers. You’ve learned how these two data types work and how you can use them. Now, take some time to review and practice what you’ve learned here. Doing so will help you remember it better.
Last updated
Was this helpful?