JS Data Types
JavaScript variables are loosely typed, that is the data type of a variable can be changed at anytime. This is an important distinction from other strongly typed languages such as C, C++ and Java.
var
Keyword
Since JS is loosely typed there is only one variable declaration type --
using the var
keyword (as opposed to a language like C, which has
int
, float
, char
and other variable types).
typeof
Operator
Even though there is only one type of variable declaration, JS does have
different data types. Loose typing allows for the same variable (think
of it as a container for values) to be reassigned to different data types.
The typeof
operator allows us to inspect the datatype of the
variable.
var x;
typeof x; // undefined
x = 1;
typeof x; // number
x = "a string";
typeof x; // string
Undefined
A variable that is yet to be assigned a value is of the type
Undefined. It holds the value undefined
.
Note that the Undefined data type has only one value undefined
.
Numbers
When a varible is assigned a number (whether a whole number of a decimal it is now holds the data type Number.
var x = 9/0; // Infinity
typeof x; // number
x = -x // - Infinity
typeof x; // number
x = 0/0 // NaN -- not a number
typeof x; // number
Number Methods
Number is not an object (objects will be discussed in detail later), but a variable with typeof "number" has some methods associated with it.
toString()
A number can be converted to its string representation by the
toString()
method.
var x = 10;
y = x.toString();
typeof y; // string
x = 3.142;
y = x.toString();
typeof y; // string
This method also allows for conversion from one base to another.
var x = 13;
y = x.toString(2); // 1101
z = x.toString(16); // d
toFixed()
This function allows convertion to different precision strings
var x = 13;
y = x.toFixed(2); // 13.00
z = x.toFixed(1); // 13.0
toExponential()
This function converts numbers into its scientific notation string.
var x = 13;
y = x.toExponential(2); // 1.30e+1
z = x.toExponential(1); // 1.3e+1
a = x.toExponential(0); // 1e+1
parseInt()
This function converts strings to respective integers.
parseInt("13"); // 13
parseInt("3.142"); // 3
parseInt("3slndv"); // 3
parseInt("3.14slndv"); // 3
parseFloat()
parseFloat("13"); // 13
parseFloat("3.142"); // 3.142
parseFloat("3slndv"); // 3
parseFloat("3.14slndv"); // 3.14
String
String is a built in data-type in all JS interpreters. A String can be
assigned to any variable by the assignment (=
) operator. A string
literal can be enclosed with either single or double quotes.
var st = "a string"; // string assignment
var st1 = 'another string'; // string literals can use either single or
double quotes
Each element (character) of the string can be indexed by using its
index, or the position. Remember strings are zero-indexed i.e.
indexing starts with zero. Therfore st[0]
refers to the first
character in a string, st[1]
refers to the second character and so on.
The total number of characters can be accessed by the length
property.
var st = "a string";
var len = st.length; // 8
A string is also an object and has built-in methods. Let is look at a few of them in action.
var st = "a string";
var x = st.indexOf("s"); // 2
var words = st.split(" "); // [ "a", "string" ]
var aChar = st.charAt(6); // "n"
var charCode = st.charCodeAt(6); // 110
A full list of String methods are listed below.
String Methods
[ Ref.]
Method | Description |
---|---|
charAt() |
Returns the character at the specified index (position) |
charCodeAt() |
Returns the Unicode of the character at the specified index |
concat() |
Joins two or more strings, and returns a new joined strings |
endsWith() |
Checks whether a string ends with specified string/characters |
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 |
lastIndexOf() |
Returns the position of the last found occurrence of a specified value in a 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, or a regular expression, and returns a new string where the specified values are replaced |
search() |
Searches a string for a specified value, or regular expression, and returns the position of the match |
slice() |
Extracts a part of a string and returns a new string |
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 character |
substring() |
Extracts the characters from a string, between two specified indices |
toLocaleLowerCase() |
Converts a string to lowercase letters, according to the host's locale |
toLocaleUpperCase() |
Converts a string to uppercase letters, according to the host's locale |
toLowerCase() |
Converts a string to lowercase letters |
toString() |
Returns the value of a String object |
toUpperCase() |
Converts a string to uppercase letters |
trim() |
Removes whitespace from both ends of a string |
valueOf() |
Returns the primitive value of a String object |
Arrays
Arrays are another built in data-type that allows the programmer to
manage lists. Unlike strings, which only allows characters to be part of
the list, arrays can have any valid JS value(variable/literal) as members.
Similar to string, the number of list members can be accessed via the
length
property.
var arr = ["a", 1, "a string", 3.14];
var len = arr.length; // 4
Array Methods
[ Ref.]
Method | Description |
---|---|
concat() |
Joins two or more arrays, and returns a copy of the joined arrays |
copyWithin() |
Copies array elements within the array, to and from specified positions |
entries() |
Returns a key/value pair Array Iteration Object |
every() |
Checks if every element in an array pass a test |
fill() |
Fill the elements in an array with a static value |
filter() |
Creates a new array with every element in an array that pass a test |
find() |
Returns the value of the first element in an array that pass a test |
findIndex() |
Returns the index of the first element in an array that pass a test |
forEach() |
Calls a function for each array element |
from() |
Creates an array from an object |
includes() |
Check if an array contains the specified element |
indexOf() |
Search the array for an element and returns its position |
isArray() |
Checks whether an object is an array |
join() |
Joins all elements of an array into a string |
keys() |
Returns a Array Iteration Object, containing the keys of the original array |
lastIndexOf() |
Search the array for an element, starting at the end, and returns its position |
map() |
Creates a new array with the result of calling a function for each array element |
pop() |
Removes the last element of an array, and returns that element |
push() |
Adds new elements to the end of an array, and returns the new length |
reduce() |
Reduce the values of an array to a single value (going left-to-right) |
reduceRight() |
Reduce the values of an array to a single value (going right-to-left) |
reverse() |
Reverses the order of the elements in an array |
shift() |
Removes the first element of an array, and returns that element |
slice() |
Selects a part of an array, and returns the new array |
some() |
Checks if any of the elements in an array pass a test |
sort() |
Sorts the elements of an array |
splice() |
Adds/Removes elements from an array |
toString() |
Converts an array to a string, and returns the result |
unshift() |
Adds new elements to the beginning of an array, and returns the new length |
valueOf() |
Returns the primitive value of an array |
Boolean
The Boolean data type contains 2 values true
and false
;
var x = true;
typeof x // boolean
x = false;
typeof x // boolean
Before continuing with more complex data-types (objects) and functions we will now look at more operators and programming constructs used in JavaScript.