JavaScript/Primitive data types
Primitive types use a fixed format; some can contain only a limited number of certain values. In contrast, objects are more complex, especially including methods and properties.
With the exception of null
and undefined
, primitive types have a corresponding object wrapper with data type specific methods. Therefore you will find on this page descriptions of some methods.
String
[edit | edit source]String is a datatype to hold text of arbitrary length. String variables are created by assigning a string literal to them. String literals can be enclosed in " "
or ' '
.
"use strict";constmyName_1="Mike";// double quoteconstmyName_2='Monica';// apostropheconstmyName_3="naɺ̠ɯçito";// non-latin characters
If your string literal contains a "
or '
, you can use the other one as the outer delimiter, or you escape them with a \
.
"use strict";constbook_1="Mike's book";constmonica_1='Here name is "Monica".';constbook_2='Mike\'s book';constmonica_2="Here name is \"Monica\".";
If your string literal is computed out of some fixed text plus some dynamic parts, you can use the template literal technique. Here, the literal is enclosed in backticks ` `
and contains variables and expressions.
"use strict";consta=1;constb=2;constresultMessage=`The sum of ${a} and ${b} is: ${a+b}.`;// same as:'The sum of '+a+' and '+b+' is: '+(a+b);alert(resultMessage);
The +
operator concatenates two strings, e.g. alert("Hello " + "world!");
. Additionally, there are a lot of methods for strings.
Hint: JavaScript doesn't have something like a 'character' or 'byte' data type.
Properties and methods for strings
[edit | edit source]We show some methods which are often used. For a complete list, please refer to MDN.
length
[edit | edit source]length
is a property, not a method. Hence there are no parenthesizes ()
. It returns the length of the string as a whole number.
constfoo="Hello!";alert(foo.length);// 6
includes(searchText)
[edit | edit source]The method returns true
if the string contains a specified string, otherwise it returns false
.
lettext="Hello world, hello Wikiversity!";document.write(text.includes("Hello"));//true
concat(text)
[edit | edit source]The method returns a string where 'text' is appended to the original string.
constfoo="Hello";constbar=foo.concat(" World!");alert(bar);// Hello World!
indexOf(searchText)
[edit | edit source]The method returns the position of the first occurrence of 'searchText', starting with 0. If 'searchText' cannot be found, -1 is returned. The method acts case sensitive.
constfoo="Hello, World! How do you do?";alert(foo.indexOf(" "));// 6consthello="Hello world, welcome to the universe.";alert(hello.indexOf("welcome"));// 13
search(regularExpression)
[edit | edit source]The method compares the string with a regular expression (=pattern), returning the index of the first match in the string. It is similar to indexOf()
, but much more powerful. E.g.: it can be made case insensitive by replacing the quotation marks in "hello"
with forward slashes and an i
at the end.
lettext="Hello world, hello Wikiversity!";document.write(text.search(/hello/i));// 0
lastIndexOf(searchText)
[edit | edit source]The method returns the position of the last occurrence of 'searchText'. If 'searchText' cannot be found, -1 is returned. The method acts case sensitive.
constfoo="Hello, World! How do you do?";alert(foo.lastIndexOf(' '));// 24
replace(text, newtext)
[edit | edit source]The method returns a string where 'text' is replaced by 'NewText' on the original string. Only the first occurrence is replaced. The method acts case sensitive.
constfoo="foo bar foo bar foo";constnewString=foo.replace("bar","NEW"):alert(foo);// foo bar foo bar fooalert(newString);// foo NEW foo bar foo
As you can see, the replace
method only returns the new content and does not modify the origin string in 'foo'.
slice(start [, end])
[edit | edit source]The method returns a substring beginning at the 'start' position.
"hello".slice(1);// "ello"
When the 'end' is provided, they are extracted up to, but not including the end position.
"hello".slice(1,3);// "el"
slice
allows extracting text referenced from the end of the string by using negative indexing.
"hello".slice(-4,-2);// "el"
Unlike substring
, the slice method never swaps the 'start' and 'end' positions. If the 'start' is after the 'end', slice
will attempt to extract the content as presented, but will most likely provide unexpected results.
"hello".slice(3,1);// ""
substr(start [, number of characters])
[edit | edit source]The method is deprecated. Use substring
or slice
instead.
substring(start [, end])
[edit | edit source]The method extracts a substring starting at the 'start' position.
"hello".substring(1);// "ello"
When the 'end' is provided, they are extracted up to, but not including the end position.
"hello".substring(1,3);// "el"
substring
always works from left to right. If the 'start' position is larger than the 'end' position, substring
will swap the values; although sometimes useful, this is not always what you want; different behavior is provided by slice.
"hello".substring(3,1);// "el"
toLowerCase()
[edit | edit source]The method returns the current string in lower case.
constfoo="Hello!";alert(foo.toLowerCase());// hello!
toUpperCase()
[edit | edit source]The method returns the current string in upper case.
constfoo="Hello!";alert(foo.toUpperCase());// HELLO!
Number
[edit | edit source]Number is one of the two numeric types (the other one is BigInt). Number stores integer values as well as floating point values in a unified 64-bit format defined by IEEE 754. That means, that JavaScript doesn't have different data types for integers and float like some other languages.
The possible range for such values is approximate -10300 to +10300 with different precision depending on the distance to 0.
In the range from -(253 − 1) to +253 − 1 there is no uncertainness for integer operations. 253 = 9,007,199,254,740,992 which is a little smaller than 1016.
"use strict";letcounter=20;// no decimal pointalert(counter+" "+typeofcounter);letdegree=12.1;// with decimal pointalert(degree+" "+typeofdegree);
For Number the usual arithmetic operators ('power' is **
and 'modulo' is %
), comparison operators (<
, >
, ...), and bitwise operators are available.
In opposite to some other languages, the division of two whole numbers can result in a number with decimal places, e.g. alert(1/3);
.
Properties and methods for numbers
[edit | edit source]Working with numbers is supported by many properties and methods. Internally, they are implemented at different areas:
- The built-in object
Math
provides properties that represent common mathematical constants like π or e. Syntax:Math.xyz
(no parenthesis) - The build-in object
Math
provides common mathematical functions like sin or log. Syntax:Math.xyz()
(with parenthesis) - The object
Number
provides properties that characterize the implementation of the data type number, like MAX_VALUE or NEGATIVE_INFINITY. Syntax:Number.xyz
(no parenthesis) - The object
Number
provides static methods that check the relation between numbers and other data types, e.g., isInteger or parseFloat. Syntax:Number.xyz()
(with parenthesis) - The object
Number
provides instance methods that act on concrete number values or variables, e.g., toExponential or toFixed. Syntax:value.xyz()
(with parenthesis)
// some examples"use strict";constvar_1=Math.PI;alert(var_1);alert(var_1.toFixed(2));constvar_2=Math.sqrt(3);alert(var_2);alert(Number.MAX_VALUE);alert(Number.isInteger(123));// truealert(Number.isInteger(12.3));// false
We show some properties and methods which are often used. For a complete list, please refer to MDN Math and MDN Numbers.
Properties
[edit | edit source]Most commonly used constants:
Math.E
Returns the constant e.Math.PI
Returns the constant pi.Math.LN10
Returns the natural logarithm of 10.Math.LN2
Returns the natural logarithm of 2.Math.SQRT2
Returns the square root of 2.
Math.ceil(number)
[edit | edit source]Returns the smallest integer greater than the number passed as an argument.
constmyInt=Math.ceil(90.8);alert(myInt);// 91alert(Math.ceil(-90.8));// -90
Math.floor(number)
[edit | edit source]Returns the greatest integer less than the number passed as an argument.
constmyInt=Math.floor(90.8);alert(myInt);// 90alert(Math.floor(-90.8));// -91
Math.round(number)
[edit | edit source]Returns the closest integer to the number passed as an argument.
alert(Math.round(90.8));// 91alert(Math.round(-90.8));// -91alert(Math.round(90.3));// 90alert(Math.round(-90.3));// -90
Math.max(number_1, number_2)
[edit | edit source]Returns the higher number from the two numbers passed as arguments.
alert(Math.max(8.3,9));// 9alert(Math.max(8.3,-9));// 8.3
Math.min(number_1, number_2)
[edit | edit source]Returns the lower number from the two numbers passed as arguments.
alert(Math.min(8.3,9));// 8.3alert(Math.min(8.3,-9));// -9
Math.random()
[edit | edit source]Generates a pseudo-random number between 0 and 1.
alert(Math.random());
Number.parseInt(string)
[edit | edit source]Number.parseFloat(string)
[edit | edit source]The two methods parseInt
and parseFloat
convert strings into numbers. They scan the given string from left to right. When they recognize a character distinct from 0 - 9, they finish scanning and return the converted numbers read so far (parseFloat accepts the decimal point). If the first character is distinct from 0 - 9, they return Math.NaN, meaning Not a Number.
Hint: It's not necessary to specify 'Number.' in the source code.
constx=parseInt("7.5");alert(x);// 7consty=parseInt("Five");alert(y);// NaNconstz=parseFloat("2.8")+3;alert(z);// 5.8// scientific notation is acceptedalert(parseFloat("123.456e6"));// 123456000
BigInt
[edit | edit source]BigInt is a data type that represents integers of arbitrary length. Hence, it's a variable-length format (conceptually) delimited only by the available RAM.
BigInts are created either by adding a 'n' to the end of an integer literal or by using the BigInt()
function.
"use strict";lethugeNumber_1=12345678901234567890n;// 'n' at the endalert(typeofhugeNumber_1);lethugeNumber_2=BigInt("12345678901234567890");// no 'n'alert(typeofhugeNumber_2);// a 'small' BigInt can be created out of an integer valuelethugeNumber_3=BigInt(123);alert(typeofhugeNumber_3);
BigInt supports the arithmetic operators + - * / **
, comparison operators, and most of the bitwise operators.
Boolean
[edit | edit source]Boolean variables can contain one of two possible values, true
or false
. JavaScript represents false
by either a Boolean false, the number 0, NaN, an empty string, or the built-in types undefined or null. Any other values are treated as true
.
"use strict";letfirstLoop=true;alert(typeoffirstLoop);
Undefined
[edit | edit source]Variables that have just been declared but not initialized with any value have the data type undefined.
"use strict";letx;// ...alert(typeofx);if(x==undefined){// remedy the missing initializationx=0;}alert(typeofx);// ...
Null
[edit | edit source]In JavaScript, null is marked as one of the primitive values, because its behavior is seemingly primitive. However, when using the typeof
operator, it returns "object". This is considered a bug, but one which cannot be fixed because it will break too many scripts.[1]
Symbol
[edit | edit source]Symbol represents a unique identifier. Symbols may have a descriptor that is given as a string to its constructor.
"use strict";// 'person' is a symbol with the description "Olaf"constperson=Symbol("Olaf");alert(person.description);// Olaf
Symbols are used as keys in objects (embedded in [ ]
) to guarantee uniqueness.
See also
[edit | edit source]ECMAScript definitions on data types