In order to understand some more advanced Javascript topics – or even some beginner topics – it’s important to know the primitive different data types in Javascript.
I’d like to get a shoutout to https://www.programiz.com/javascript/data-types . I used that page – and a few others – while putting this article together;
Javascript has five primitive types. These are:
- String
- Number
- Boolean
- Undefined
- Null
Let’s take a look at these data types one at a time, starting with String.
Javascript String
You’re probably used to using strings all the time. Strings can be contained in single quotes, double quotes, or backticks like so.
console.log(“This is a string.”);
console.log(‘This is a string.’);
console.log(`This is a string.`);
Both single and double quotes are pretty much the same. You may need to use one or the other depending on the text inside the string.
console.log(“It’s cool to use strings.”);
console.log(‘They are called “strings.”’);
Backticks, on the other hand, have another feature that’s very useful. You can use expressions or variables between ${} inside backticks.
This means you can do things like:
console.log(`Five plus six is ${5 + 6}`);
let name = “Josh”;
console.log(`Hello ${name}`);
This looks much cleaner than using “+” like so:
let name = “Josh”;
console.log(“Hello ” + name + “.”);
In the near future, I’m writing an article about working with strings in Javascript.
That’s it for the String type for right now. Let’s look at the next type – Number.
Javascript Number
Numbers are useful for all sorts of things in Javascript. It’s important to note that Javascript does not have an Integer or Float type – they are both Number in Javascript.
Numbers in Javascript look like the following.
let number = 1234;
let number = 12.34;
let number = 10e2;
Numbers can also be Infinity, -Infinity, and NaN (not a number). I’ll talk more about NaN later in another article.
let number1 = 3 / 0; // Infinity
let number2 = -3 / 0; // -Infinity
let number3 = “cat” / 3 //NaN
Boolean
The concept of booleans in Javascript is pretty straightforward. You can think of booleans like a light switch with two states like on and off, but instead, the values are true and false;
If (true) {
console.log(“This will run”);
else if (false) {
console.log(“This will not run”);
}
You will often see boolean values as return values when comparing things.
‘string’ === ‘string’
> true
50 > 300
> false
Undefined
Undefined means that the value hasn’t been set yet. Actually, you can set something to the value of undefined. If you don’t explicitly return something from a function in Javascript, you get undefined.
console.log(‘hi mom’);
> undefined
let something;
> undefined
Null
Null is similar to undefined. The major difference is undefined may popup when writing code. For example, when trying to access a value that hasn’t been defined. Null, on the other hand, must be explicitly used.
let something = null;
Leave a Reply