Data types¶
JavaScript is a dynamic type language, which means that you don't need to define type of the variable because it is effectively used by the JavaScript engine. There are two types of data in JavaScript: primitive data type and non-primitive (reference) data type.
A variable in JavaScript contains any of these data types: strings, numbers, objects:
let length = 17; // Number
let lastName = "Jameson"; // String
let x = {firstName:"John", lastName:"Doe"}; // Object
Programming languages which allow this kind of things are called “dynamically typed”, when there are data types, but variables aren’t bound to any of them.
There are 7 primitive data types in JavaScript:
- Number
- Bigint
- String
- Boolean
- Null
- Undefined
- Symbol
- and Object is a non-primitive data type
Primitive values¶
All mentioned above types are incapable of being changed except objects. For example, Strings are unchangeable, so we call them "primitive values".
Number¶
The Number type are integer and floating point numbers.
There are many operations for numbers: addition +, subtraction -, multiplication*, division / and others.
let num1 = 32;
let num2 = +Infinity;
We can write numbers with or without a decimal point. They can also be +Infinity, -Infinity, and NaN (not a number).
Infinity represents the mathematical Infinity ∞, which is a special value that’s bigger than any number. We can get it dividing by zero:
console.log( 1 / 0 ); // Infinity
NaN is a computational error, which is a result of an incorrect or an undefined mathematical operation, for example:
console.log( "not a number" / 2 ); // NaN, such division is erroneous
Any operation on NaN returns NaN:
console.log( "not a number" / 2 + 5 ); // NaN
NaN in a mathematical expression can influences to the whole result.
More information about working with numbers you can find in Numbers.
BigInt¶
In JavaScript the BigInt type is a numeric primitive that can represent whole number with random exactness. BigInt gives you an opportunity safely store and operate on large integers even beyond the safe integer limit for Numbers.
In JavaScript, the “number” type can’t represent integer values, which are larger than 253 or less than -253 for negatives. It is a technical limitation caused by their internal representation. That’s about 16 decimal digits, but sometimes we need really big numbers, e.g. for cryptography or microsecond-precision timestamps.
const bigint = 8562323159475639012345678901234567890n;
const sameBigint = BigInt("8562323159475639012345678901234567890");
const bigintNumber = BigInt(10); // same as 10n
BigInt type was added to the language not long ago and it represents integers of arbitrary length. A BigInt is created by added n to the end of an integer literal:
const bigint = 8562323159475639012345678901234567890n;
console.log(bigint);
Click BigInt to find more information about working with BigInt.
String¶
We use strings for storing text. In JavaScript, strings can’t be changed, and they must be inside of either double or single quotes.
let str = "Hello";
let str2 = 'Welcome to W3Docs!';
let phrase = `${str} dear friend`;
console.log(str);
console.log(str2);
console.log(phrase);
There are 3 types of quotes in JavaScript:
- Double quotes:"Welcome".
- Single quotes: 'Welcome'.
- Backticks: `Welcome`.
Double and single quotes are “simple” quotes, practically there is no difference between them in JavaScript. Backticks are “extended functionality” quotes that allow us to embed variables and expressions into a string by wrapping them in ${…}, for instance:
Example of the embed a variable in string:¶
let name = "W3Docs";
// embed a variable
console.log( `Welcome to ${name}!` ); // Welcome to W3Docs!
Example of the embed an expression in string:¶
console.log( `the result is ${5 + 3}` ); // the result is 8
The expression inside ${…} is assessed, it’s result usually becomes a part of the string. We can put anything in there: name, an arithmetical expression or something more complex.
But it can only be done in backticks, other quotes don’t have this embedding functionality.
console.log( "the result is ${2 + 5}" );
This example returns string - “the result is ${2 + 5}” ,here you don’t need the double quotes.
We’ll see more about working with strings in the chapter Strings.
Boolean¶
Boolean is a datatype which has just two values: true or false. Boolean is used in JavaScript as a function for getting the value of an object, variables, expressions, conditions, etc. This type is used to store yes/no values, where true means “yes, correct”, and false means “no, incorrect”.
In the example x1 and x2 stores the boolean value i.e. true and false:
let x1 = true;
let x2 = false;
let x1 ="true"; // not boolean values, it’s a string
let x2 ="false"; // not boolean values, it’s a string
Boolean values also can be as a result of comparisons:
let isSmaller = 5 < 3;
console.log( isSmaller ); //false (the comparison result is "no")
We’ll cover strings more thoroughly in Boolean.
Null¶
It is one of JavaScript's primitive values which is treated as falsy for boolean operations. In JavaScript null means "nothing", “empty”. it’s something that doesn't exist.
But in JavaScript, the data type of null is an object, which you can empty by setting an object to null:
let price = null;
The code above declares that price is unknown or empty for some reason.
Undefined¶
The special value undefined makes a type of its own, just like null. In JavaScript, a variable without a value called undefined. It’s value and type are undefined, which means that the “value is not assigned”:
let x;
console.log(x); // shows "undefined"
Yet, technically, it is possible to assign undefined to any variable:
let x = 123;
x = undefined;
console.log(x); // "undefined"
But we don’t recommend doing that. Usually, we use null to assign an “unknown” or “empty” value to a variable, and we use undefined for checking if a variable has been assigned.
Symbol¶
A Symbol is an immutable primitive value that is unique and can be used as the key of an Object property. In some programming languages, Symbols are called "atoms".
A value which has the data type Symbol can be referred to as a "Symbol value". A symbol value is created in a JavaScript by invoking the function Symbol, which produces an unnamed, unique value. A symbol can be used as an object property.
A Symbol value represents a unique identifier. For example, two symbols with the same description:
let symbol1 = Symbol("symbol")
let symbol2 = Symbol("symbol")
console.log(symbol1 === symbol2) // returns "false"
In this example, console.log returns false.
Symbols have to be unique, even if we create a lot of symbols with the same description, they are different values.
You can find more information in Symbol.
Object¶
We use objects to store keyed collections of various data and more complicated entities. In JavaScript, objects pass through almost every aspect of the language. First, we must understand them, then just go into depth.
Object is not a primitive data type, it’s a collection of properties, which can reference any type of data, including objects and/or primitive values. Objects can be created with figure brackets {…} with a list of properties.
let obj = {
key1: 'value1',
key2: 'value2',
key3: true,
key4: 20,
key5: {}
}
Let’s imagine that the object is a cabinet with signed files, where is stored every piece of data by the key. It’s rather easy to find a file by its name, add or remove a file. An empty object (“cabinet”) can be created with the help of one of two syntaxes:
let obj = new Object(); // "object constructor" syntax
let obj = {}; // "object literal" syntax
In this case we usually use the figure brackets {...} and call that declaration an object literal.
The typeof operator¶
typeof operator helps us to see which type is stored in a variable. It supports 2 forms of syntax:
- As an operator: typeof x;
- As a function: typeof(x);
It can work with or without parentheses, the result will be the same. The example below shows, that the call to typeof x returns a string with the type name:
console.log(typeof undefined); // "undefined"
console.log(typeof 0); // "number"
console.log(typeof 15n); // "bigint"
console.log(typeof false); // "boolean"
console.log(typeof "foo"); // "string"
console.log(typeof Symbol("id")); // "symbol"
console.log(typeof Math); // "object"
console.log(typeof null); // "object"
console.log(typeof prompt); // "function"
- Math is a built-in object. Math provides mathematical operations.You can find more information about Math in Math.
- null is not an object, but the result of typeof null is "object", which is an error in typeof. null is a special value with a separate type of its own.
- The result of typeof prompt is "function", because prompt is a function. We’ll study functions in Functions. Functions are the part of the object type, but typeof returning "function".
Type Conversions¶
We can convert JavaScript variables to a new variable and another data type: using JavaScript function or automatically by JavaScript itself. For instance, alert automatically converts any value to a string to show it, mathematical operations convert values to numbers and so on.
Converting Numbers to Strings¶
The global method String() can convert numbers to strings and can be used on any type of numbers, literals, variables, or expressions:
String(a); // returns a string from a number variable a
String(100); // returns a string from a number literal 100
String(20 + 30); // returns a string from a number from an expression
We can also call the String(value) function to convert a value to a string:
let value = true;
console.log(typeof value); // boolean
value = String(value); // now value is a string "true"
console.log(typeof value); // string
Usually, string conversion is obvious: a false becomes "false", null becomes "null" and so on.
Converting Booleans to Strings¶
Boolean conversion is the most simple, which usually happens in logical operations but can also be performed with a call to Boolean(value). The global method String() has an ability to convert booleans to strings.
String(false); // returns "false"
String(true); // returns "true"
Here is some conversion rule:
The values which are intuitively “empty” (0, an empty string, null, undefined, and NaN) become false, other values become true. For example:
console.log( Boolean(1) ); // true
console.log( Boolean(0) ); // false
console.log( Boolean("hello") ); // true
console.log( Boolean("") ); // false
console.log( Boolean("0") ); // true
console.log( Boolean(" ") ); // spaces, also true (any non-empty string is true)
Converting Dates to Strings¶
The global method String() converts dates to strings.
console.log(String(Date())); // returns "Tue Jan 21 2020 10:48:16 GMT+0200 (W. Europe Daylight Time)"
Converting Strings to Numbers¶
The global method Number() converts strings to numbers. Strings containing numbers (like "5.20") convert to numbers (like 5.20). Empty strings convert to 0. Anything else converts to NaN.
Number("5.20"); // returns 5.20
Number(" "); // returns 0
Number(""); // returns 0
Number("99 88"); // returns NaN
We meet numeric conversion in mathematical functions and expressions automatically. Example can be a division (/), which is applied to non-numbers:
console.log( "6" / "2" ); // 3, strings are converted to numbers
Number(value) function helps us explicitly convert a value to a number:
let str = "123";
console.log(typeof str); // string
let num = Number(str); // becomes a number 123
console.log(typeof num); // number
Explicit conversion is required when we read a value from a string-based source as a text form which expects a number to be entered.