Data Types
Depending on who you ask, JavaScript offers between four to six data types. These data types can be broken down into two categories - those that store literal values (simple data types; eg. boolean, number, string), and those that store a reference in memory (reference data types; eg. arrays and objects).
Simple Data Types
The five simple data types we'll be covering include:
- Boolean
- Number
- String
- Undefined (no value yet assigned)
- Null (no value)
Reference Data Types
Reference data types take up more space in memory, and are referenced by an address. These data types include objects like arrays and functions that you can call. We'lll look at arrays in this section, but since objects are so special, we'll save them for its own section.
Numbers
Declaration
There are several ways to declare a number in JavaScript
- Integer:
5
- Floating point numbers:
3.1415
- Scientific notation:
9e+4
- Hexadecimal notation:
0xfff
Operators
Furthermore, there are a handful of common arithmetic operators available in JavaScript.
- +
- Addition
- -
- Subtraction
- *
- Multiplication
- /
- Division
- %
- Modulo
- ++
- Increment
- --
- Decrement
Conversion from strings
To convert a number to a string, you can either use the parseInt()
or parseFloat()
method, depending on whether you want to truncate the decimal point.
parseInt('22') // 22
parseFloat('3.14'); // 3.14
parseFloat('23.4 hahahahahlololol'); // 23.4
In the last example, only the first number in the string is parsed. If there are no values at the beginning, you'll get a NaN
data type.
Number methods
These methods can be used with any number value.
- toFixed(x)
- Rounds to a specified number of decimal places.
- toPrecision(x)
- Formats number to x length.
- toExponential(x)
- Returns a string representation of the number in exponential notation.
- toString()
- Converts a number to a string.
- MAX_VALUE
- Returns the largest number possible.
- MIN_VALUE
- Returns the smallest number possible.
- NEGATIVE_INFINITY
- Represents negative infinity.
- POSITIVE_INFINITY
- Represents infinity.
var sampleNum = 5;
sampleNum.toPrecision(4); // 4.000
sampleNum.MAX_VALUE; // 1.7976931348623157e+308
The Math object
The Math object contains a library of parameters and functions related to number generation and manipulation. To call it, call the Math variable, and either its attributes or a function.
Here are some common constants that are stored as attributes in the Math object:
- Math.PI
- Returns PI (3.14).
- Math.E
- Returns Euler's number.
- Math.LN2
- Returns natural logarithm of 2.
Furthermore, the Math object contains a number of functions for complex calculations.
- Math.abs(x)
- Returns absolute value of x.
- Math.floor(x)
- Returns floor of x.
- Math.max(x, y, z)
- Returns max value of x, y or z.
- Math.min(x, y, z)
- Returns min value of x, y or z.
- Math.round(x)
- Returns nearest integer value of x.
- Math.sin(x)
- Returns sine of x.
- Math.sqrt(x)
- Returns square root of x.
- Math.isNaN(x)
- Returns true if x is not a number.
Math.min(1, 4, 5); // 1
Math.floor(1.242); // 1
Math.isNaN(21); // false
We'll soon cover objects, but for now just use this notation to access Math's attributes and functions.
Generating random numbers
To generate random numbers, use the Math.random()
function. This will return a value from 0 up to 1.
Thus we can get a random number between 1 and 100 with the following code:
var randomNum;
randomNum = Math.floor((Math.random() * 100) + 1);
Dot notation
The dot notation is called so because it uses the period (or the dot) to access an object's methods and properties. As you will (or have) seen in many other programming languages, the dot notation provides a clean way to access the members of an object.
Strings
Declaring Strings
You can use either double or single quotes to declare a string.
"Hello world!" // declaring with double quotes
'Hello world!' // with single quotes
'She said, "she said"' // Using double quotes within single quotes
"She said, \"Hello darling\"" // Escaping quotes with a backslash
As you can see in the above example, you can use the backslash key \"
to escape the quote.
Escape characters
JavaScript provides a list of other escape characters as well.
\b
- Backspace
\f
- Form feed
\n
- Newline
\r
- Carriage Return
\t
- Tab
\v
- Vertical tab
\\
- Backslash
document.write("\tHello\nWorld!");
// Hello
// World!
String concatenation
To concatenate two strings together simply use the+
operator.var greeting = "Hello" + "world!";
Mixing numbers and strings
When adding numbers and strings together, you will get a string back, with the two values concatenated.
var cost = '8' + 9; // cost = '89';
String properties and methods
The String object comes with a number of member attributes.
- length
- Number of characters in string.
- substring(m)
- Substring from m to the end.
- substring(m,n)
- Substring from m to but not including n.
- toUpperCase()
- Changes all casing to upper case.
- toLowerCase()
- Changes all casing to lower case.
- trim()
- Takes away whitespace away from both ends of a Stirng.
var sample = "Hello there."
sample.length; // 12 characters
sample.substring(0,5); // "Hello"
sample.toUpperCase(); // "HELLO THERE."
Capturing user input
To get input from your user, use the prompt()
method. This will display a dialog box to the user, displaying the string passed in as an parameter to prompt()
.
var age = prompt("How old are you?");
// User is prompt for his age, which then gets placed in the age variable.
console.log(age); // outputs user's inputted age to the javascript console.
Strange data types
Booleans
The boolean type variable is used in control-flow, which we will get to in the next section.
The two types it may hold are true
and false
.
Usually you don't declare a variable, but you rather use an expression that evaluates to a boolean value - true or false.
Null
null
simply means nothing. It represents and evaluates to false. However, this does not mean it's empty.
var myVariable = ''; // myVariable is empty, but not null.
Undefined
undefined
means a variable that hasn't yet contained a value.
Arrays
An array is an object that stores data that can be accessed with a numerical index value. Just like most programming languages, JavaScript starts its array indices start at 0. However, unlike some programming languages, JavaScript does not require the data within each array slot to be of the same type.
Declaring arrays
There are a few ways to declare an array. The following code shows three ways to create the same exact array.
// Insert one item at a time
var groceryList = new Array();
groceryList[0] = "Bananas";
groceryList[1] = "Pasta";
groceryList[2] = "Pumpkin";
groceryList[3] = "Tomato sauce";
// Place an array within a variable
var groceryList = ["Bananas", "Pasta", "Pumpkin", "Tomato sauce"];
// Call the array constructor with arguments
var groceryList = new Array("Bananas", "Pasta", "Pumpkin", "Tomato sauce");
Declaring an array of a set size
If you already know what the size of an array ought to be, you can do so upon initialization.
var myArray = new Array(10);
Retrieving array values
To retrieve an array value, simply use brackets ([]
), with the index number placed inside.
To access the array items in a more object-oriented manner, you may use the dot notation, with the item(0)
method.
groceryList[0]; // Bananas
groceryList.item(0); // Bananas
Changing array values
Changing an array value is the same method as assigning. The following code change the 3rd item in the grocery
array to apples
.
groceryList[2] = 'apples';
Adding and removing elements
There are two sets of functions used to add and remove elements, depending on whether you want to add to the front of back.
Adding to the front - shift and unshift
To add or remove elements to the front, use the shift()
and unshift()
functions.
var groceryList = ["Bananas", "Pasta", "Pumpkin", "Tomato sauce"];
groceryList.unshift("Chicken breast");
// ["Chicken breast", "Bananas", "Pasta", "Pumpkin", "Tomato sauce"]
groceryList.shift(); // now remove the front
// ["Bananas", "Pasta", "Pumpkin", "Tomato sauce"]
Adding to the back - push and pop
To add or remove elements from the back, use the push()
and pop()
functions.
var groceryList = ["Bananas", "Pasta", "Pumpkin", "Tomato sauce"];
groceryList.push("Chicken breast");
// ["Bananas", "Pasta", "Pumpkin", "Tomato sauce", "Chicken breast"]
groceryList.pop(); // now remove the front
// ["Bananas", "Pasta", "Pumpkin", "Tomato sauce"]
Sorting
To sort elements, use the sort()
function.
var groceryList = ["Tomatoes", "Lemons", "Apples", "Bananas"];
groceryList.sort();
// ["Apples", "Bananas", "Lemons", "Tomatoes"]
Array attributes
To access the length of an array, access the length
property.
var numGroceryItems = groceryList.length; // 4
Concatenating two arrays
To add two arrays together, use the .concat
function.
var arrayOne = [1, 2, 3];
var arrayTwo = [4, 5, 6];
var concatArray = arrayOne.concat(arrayTwo); // [1, 2, 3, 4, 5, 6]
Type conversions
Because JavaScript is a loosely typed language, meaning that it's not necessary to predeclare a given variable's type.
This feature, although convenient, can be the source of many bugs. Particularly, you should watch for type conversions, which is when a value of one type turns into another.
In the example below, the string '1'
is converted into a number before the expression is evaluated.
'1' > 0 // true
Implicit conversions
An implicit conversion occurs without your explicit consent. For example, when a string and a number are added together with a +
operand, the result is a string.
var ageGreeting = "I am " + 9 + " years old." // "I am 9 years old."
Explicit conversions
In the case you want to change from a number to a string or vice versa, you can do so explicitly.
Number conversions
var numString = "100";
var num = Number(numString); // 100
String conversions
var numString = String(100); // '100'
Next section: Control Flow