Understanding data types is essential for writing reliable, efficient JavaScript. Everything you work with, from numbers and strings to complex objects, has a type. JavaScript can behave differently depending on what type its handling.
Scope
Data Types in JavaScript
Operators
JavaScript includes a range of operators, and understanding their precedence is crucial; they follow the PEMDAS order. These are used to join strings together or do any number of mathematical calculations.
| Operator | Description | Example |
|---|---|---|
=
|
Assignment. |
let x = 5;
|
++
|
Increment by 1. X++ will return a value after logging x. ++X will return a value and then log it. |
x++;
|
--
|
Decrease by 1. |
x--;
|
+=
|
Addition assignment. It adds a value to the variable and assigns the result back to the variable. |
x += 3;The value of x is now 3 more than it was. |
-=
|
Subtraction assignment. |
x-=3;
|
*=
|
Multiplication assignment. |
x*=2;
|
/=
|
Division assignment. |
x/=3;
|
**=
|
Exponential assignment. |
x**=2;
|
&=
|
Bitwise AND assignment. |
x&=3;
|
|=
|
Bitwise OR assignment. |
x|=3;
|
^=
|
Bitwise XOR assignment. |
x^=3;
|
>>=
|
Bitwise right shift assignment. |
x>>=3;
|
<<=
|
Bitwise left shift assignment. |
x<<=3;
|
>>>=
|
Bitwise unsigned right shift assignment. |
x>>>=3;
|
==
|
Equal to. |
console.log(1 == 1);
|
===
|
Equal to using comparison of data types. |
console.log(1 === "1");
|
!=
|
Not equal to. |
console.log(1 != 1);
|
!==
|
Not equal to with comparison of data types. |
console.log(1 !== "1");
|
>
|
Greater than. |
console.log(2>1);
|
<
|
Less than. |
console.log(1<2);
|
>=
|
Greater than or equal to. |
console.log(2 >= 1);
|
<=
|
Less than or equal to. |
console.log(2<=1;)
|
There are also logical operators.
-
A && B: A and B -
A || B>: A or B -
!A: Not A -
is: checks whether two objects are the same object
Number
Number (capital N) represents any numerical value covering both integers and decimals. A weird quirk of JavaScript is that under the hood it works with double precise floating point numbers. That means a simple sum like 0.1 + 0.2 could come out as 0.30000000000004. A fix for this is scale the numbers up to integers first ( by multiplying by 10 in our example) and then dividing the answer by 10 at the end.
There are special numbers; Infinity and -Infinity which represent any number larger than 1.8x10^308 and below -1.8x10^308 respectively.
There is also a special number called
NaN.
It occurs when the browser is expecting a number but it finds a string or some other data type. A NaN cannot
equal anything, even itself (NaN !== NaN). You can check your values using
isNaN(value) that will return true if it is not a number and false if it is a
number.
Methods are built in functions that you can apply to your objects. In this case; these methods will apply to numbers. To set it up, define your number as a variable and then simply using dot notation to apply the number method. You may want to save these values as other variables or print them to the console.
let numberVariable = 1.01;
console.log(numberVariable.toFixed(1)); // Prints 1.0 to the console
let numberVariableOneDecimalPlace = numberVariable.toFixed(1); // The value to 1 decimal place as a new variable
These functions are global number functions so take the form of
Number.isNaN(variable).
-
Number.isNaN(): Returns true if the passed value is the special value NaN. This is not a method on number variables, it's a static method on the Number object. -
Number.isFinite(): Returns true if the value is a finite number (not Infinity, -Infinity, or NaN). -
Number.isInteger(): Returns true if the value is an integer. -
Number.parseFloat(): Converts a value to a floating point number. -
Number.parseInt(): Converts a value to an integer. Always include the radix (base), e.g. Number.parseInt("08", 10) returns 8, while omitting the radix might give unpredictable results.
The following are number methods.
-
toFixed(n): Returns a string representing the number with n digits after the decimal point. -
toPrecision(n): Returns a string with the number rounded to n significant digits. -
toString(): Converts the number to a string. You can optionally specify a radix:10.toString(2) → "1010".
BigInt
BigInt represents any number >= 2^53 or <=2^53. These numbers cannot be mixed with Number types directly.
String
Strings are sequences of characters define by single or double quotation marks such as
'example string'
or
"example string 2".
JavaScript considers these to be arrays of characters, so the 0 index rule will apply here, with the first
character having an index value of 0.
Strings are immutable. Changing a string actually creates a new one.
You can embed variables into strings using template literals that use backticks and ${}.
let variableOne = 'Adam';
let templateLiteral = `Hello ${variableOne}`;
console.log(templateLiteral); // Logs 'Hello Adam' to the console.
Some characters will mess with your JavaScript code, such as having double quotes in a string that is defined with double quotes. To minimise these, try to use single quotes for quotations if you define your string with double quotes and vice versa. For others you can use \ as an escape character.
-
\ttab -
\nnewline -
\\backslash -
\'single quote -
\"double quote
String Methods
Methods are built in functions that you can apply to your objects. In this case; these methods will apply to strings. To set it up, define your string as a variable and then simply using dot notation to apply the string method. You may want to save these values as other variables or print them to the console.
let stringVariable = “This is a string”;
console.log(stringVariable.length); // This will log the length of the string to the console
let stringVariableLength = stringVariable.length; // This will store the string length in a new numeric variable
| String Method | Description |
|---|---|
charAt()
|
Returns the character at the specified index. |
concat()
|
Joins two or more strings and returns a new string. |
endsWith()
|
Checks whether a string ends with specified string/characters (returns true/false). |
fromCharCode()
|
Converts Unicode values to characters. |
includes()
|
Checks whether a string contains the specified string/characters. |
indexOf()
|
Returns the position of the first found occurrence of a specified value in a string, it can take a second parameter indicating the starting index point. |
lastIndexOf()
|
Returns the position of the last found occurrence of a specified value in a string. |
length
|
Returns the length of the string. |
localeCompare()
|
Compares two strings in the current locale. |
match()
|
Searches a string for a match against a regular expression and returns the matches. |
repeat()
|
Returns a new string with a specified number of copies of an existing string. |
replace()
|
Searches a string for a specified value and returns a new string with the values replaced. |
search()
|
Searches a string for a specified value and returns the position. |
slice()
|
Extracts a part of a string and returns a new string. If an ending index is supplied, it is
excluded, so +1 to the last index you want to include.
string.slice(starting index, ending index)
or
string.slice(starting index).
|
split()
|
Splits a string into an array of substrings. |
startsWith()
|
Checks whether a string begins with specified characters. |
substr()
|
Extracts the characters from a string, beginning at a specified start position and through the specified number of characters. |
toLocaleLowerCase()
|
Converts a string to lowercase according to the hosts locale. |
toLocaleUpperCase()
|
Converts a string to uppercase according to hosts locale. |
toLowerCase()
|
Converts a string to lower case. |
toString()
|
Returns the value of a String object. |
toUpperCase()
|
Converts a string to upper case. |
trim()
|
Removes whitespace from both ends of a string. |
valueOf()
|
Returns the primitive value of a String object |
Boolean
Booleans represent true or false values. When setting values, they do not use a capital letter (Python does, but JavaScript does not).
let variableOne = true;
let variableTwo = false;
Some values are falsy, meaning that they are not defined as false, but will return false in most scenarios. The values that are not falsy are considered truthy. The falsy values are:
- 0
- '' (empty string)
- null
- undefined
- NaN
Object
Objects are collections of key-value pairs. Objects are extremely versatile and are the foundation for most JavaScript structures (arrays, functions, etc. are also objects). Objects can be created from other objects, making a secret link between them. If an attempt to access a name fails, the secret linked object will be used.
let person = {
name: "Adam",
age: 30
};
Null
null is an intentional absence of any value. It's often used when you want to indicate that something is intentionally "nothing."
let empty = null;
Undefined
undefined means a variable has been declared but no value has been assigned.
let x;
console.log(x); // undefined
Converting Between Types
JavaScript can sometimes automatically convert one data type into another, this is known as type coercion. A main example of this is when you add numbers and strings together, it will automatically convert the number into a string and concatenate them.
console.log(1 + "1"); // "11"
console.log(1 == "1"); // true
It is often useful to convert between values. Perhaps you want you add a value into a string, so will need to
convert it from a number to a string first. Or vice versa, perhaps the user inputs a number, which will, by
default be logged as a string. Then you will need to convert to a number to use it in any mathematical
equations. To see the type of a value you can use
typeof.
typeof 42; // "number"
typeof "hello"; // "string"
typeof undefined; // "undefined"
typeof null; // "object" (weird!)
typeof []; // "object" (arrays are objects)
typeof {}; // "object"
Note that a long running bug in JavaScript (that persists due to the quirks of the foundations of the language).
That
typeof null
returns "object".
To convert between types you can use:
Boolean(): Converts any value to its Boolean equivalent.parseInt(): Converts a string into an integer. You can specify base as an optional value (e.g. you may want to convert it to base 2 to use in binary) that would look like parseInt(variable, 2).parseFloat(): Converts a string into a floating point number (decimal).Number(): Converts any value into a number.String(): Converts any value into a string.