Any information you want to use in JavaScript has a type. The type describes what kind of data is stored in memory and what operations apply to it.
Let's draw an analogy. Types can be understood by looking at animal species or other common attributes of a group of objects. All kittens and tomcats are cats, but each is a separate object. Thinking of cats as a type, you can assume some operations are available; for example, a cat can purr.
In this topic, we will consider two simple data types popular in programming.
Strings
You will have to use strings when working with textual information in your program. This type of data is widespread in JavaScript. Strings are written in single or double quotes.
Examples of strings in double quotes:
console.log(""); // the empty string
console.log("string"); // one word
console.log("Hello, world"); // a phraseExamples of strings in single quotes:
console.log('a'); // a single character
console.log('1234'); // a sequence of digitsNote that any digits in quotes are also considered a string.
As you can see, strings are easy to use!
Numbers
Numbers are the most important data type for any programmer. You can't write a serious program without numbers, so let's see how to output a number to the console:
console.log(12);
console.log(0);
console.log(-11);
console.log(-1.04); You can use positive, negative numbers, and zero. There are no additional difficulties in recording floating-point numbers.
Integer numbers can count physical objects, while floating-point numbers are good for statistical and scientific calculations.
The typeof operator
We can easily recognize a data type using the typeof operator. Let's look at two examples where we output the data type to the console.
There are two ways to use the typeof operator.
With parentheses:
console.log(typeof(9)); // numberWithout parentheses:
console.log(typeof 9); // numberThe result of these two code samples is the same. We want to find out what type of data 9 is, and it turns out to be a number.
This operator is handy when working with different data types since JavaScript can automatically convert data types to each other. We will discuss this feature in the following topics.
Read more on this topic in String Along with JavaScript Strings on the Hyperskill Blog.
Conclusion
A data type describes how to store data in memory and which operations apply to the data. In this topic, we've looked at two simple data types: strings and numbers. Strings store textual information in a program, while numbers are used for numeric values. We have also explored the typeof operator, which you can use to check the data type of a variable.