JavaScript/Primitive data types

From Wikibooks, open books for an open world
(Redirected from JavaScript/Numbers)
Jump to navigation Jump to search


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";
const myName_1 = "Mike";      // double quote
const myName_2 = 'Monica';    // apostrophe
const myName_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";
const book_1 = "Mike's book";
const monica_1 = 'Here name is "Monica".';
const book_2 = 'Mike\'s book';
const monica_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";
const a = 1;
const b = 2;
const resultMessage = `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.

const foo = "Hello!";
alert(foo.length);    // 6

concat(text)[edit | edit source]

The method returns a string where 'text' is appended to the original string.

const foo = "Hello";
const bar = 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 is case sensitive.

const foo = "Hello, World! How do you do?";
alert(foo.indexOf(" "));	// 6

const hello = "Hello world, welcome to the universe.";
alert(hello.indexOf("welcome"));      // 13

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 is case sensitive.

const foo = "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 is case sensitive.

const foo = "foo bar foo bar foo";
const newString = foo.replace("bar", "NEW"):
alert(foo);		    // foo bar foo bar foo
alert(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.

const foo = "Hello!";
alert(foo.toLowerCase());	// hello!

toUpperCase()[edit | edit source]

The method returns the current string in upper case.

const foo = "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";
let counter = 20;   // no decimal point
alert(counter + " " + typeof counter);
let degree = 12.1;  // with decimal point
alert(degree + " " + typeof degree);

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";

const var_1 = Math.PI;
alert(var_1);
alert(var_1.toFixed(2));

const var_2 = Math.sqrt(3);
alert(var_2);

alert(Number.MAX_VALUE);

alert(Number.isInteger(123));
alert(Number.isInteger(12.3));

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(float)[edit | edit source]

Returns the least integer greater than the number passed as an argument.

const myInt = Math.ceil(90.8);
alert(myInt); // 91;

Math.floor(float)[edit | edit source]

Returns the greatest integer less than the number passed as an argument.

const myInt = Math.floor(90.8);
alert(myInt); // 90;

Math.max(int1, int2)[edit | edit source]

Returns the highest number from the two numbers passed as arguments.

const myInt = Math.max(8, 9);
alert(myInt); // 9

Math.min(int1, int2)[edit | edit source]

Returns the lowest number from the two numbers passed as arguments.

const myInt = Math.min(8, 9);
alert(myInt); // 8

Math.random()[edit | edit source]

Generates a pseudo-random number.

const myInt = Math.random();

Math.round(float)[edit | edit source]

Returns the closest integer to the number passed as an argument.

const myInt = Math.round(90.8);
alert(myInt); // 91;

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.

const x = parseInt("7.5");
alert(x);  // 7

const y = parseInt("Five");
alert(y); // NaN

const z = parseFloat("2.8") + 3;
alert(z); // 2.8 + 3 = 5.8.

// scientific notation is accepted
alert(parseFloat("123.456e6"));

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";
let hugeNumber_1 = 12345678901234567890n;        // 'n' at the end
alert(typeof hugeNumber_1);
let hugeNumber_2 = BigInt("12345678901234567890"); // no 'n'
alert(typeof hugeNumber_2);
// a 'small' BigInt can be created out of an integer value
let hugeNumber_3 = BigInt(123);
alert(typeof hugeNumber_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";
let firstLoop = true;
alert(typeof firstLoop);

Undefined[edit | edit source]

Variables that have just been declared but not initialized with any value have the data type undefined.

"use strict";
let x;
// ...
alert(typeof x);
if (x == undefined) {
  // remedy the missing initialization
  x = 0; 
}
alert(typeof x);
// ...

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"
const person = 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

Exercises[edit | edit source]

... are available on another page (click here).

References[edit | edit source]

  1. MDN: Null