Values and Types
Explore the fundamental concepts of values and types in JavaScript. Understand how numbers and strings work, how to perform operations like addition and concatenation, and grasp the basics crucial for programming with JavaScript.
A value is a piece of information used in a computer program. Values exist in different forms called types. The type of a value determines its role and operations available to it. Every computer language has its own types and values. Let’s look at two of the types available in JavaScript.
Number
A number is a numerical value. Let’s go beyond that though! Like mathematics, you can use integer values (or whole numbers) such as 0, 1, 2, 3, etc, or real numbers with decimals for greater accuracy. Numbers are mainly used for counting. The main operations you can use on numbers are summarized in the following table. All of them produce a numeric result.
| Operator | Role |
|---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
String
A string in JavaScript is text surrounded by quotation marks, such as "This is a string". You can also define strings with a pair of single quotes: 'This is another string'. The best practice for single or double quotes is a whole political thing. Use whichever you like, but don’t mix the two in the same program!
Always remember to close a string with the same type of quotation marks you started it with.
To include special characters in a string, use the \ character (backslash) before the character. For example, type \n to add a new line within a string: "This is\na multiline string".
You cannot add or subtract string values like you’d do with numbers. However, the + operator has a special meaning when applied to two string values. It will join the two chains together, and this operation is called a concatenation. For example, "Hel" + "lo" produces the result "Hello".