Simple Data Types
The five simple data types we'll be covering include:
- 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.
- Floating point numbers:
- Scientific notation:
- Hexadecimal notation:
Conversion from strings
To convert a number to a string, you can either use the
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.
These methods can be used with any number value.
- Rounds to a specified number of decimal places.
- Formats number to x length.
- Returns a string representation of the number in exponential notation.
- Converts a number to a string.
- Returns the largest number possible.
- Returns the smallest number possible.
- Represents negative 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:
- Returns PI (3.14).
- Returns Euler's number.
- Returns natural logarithm of 2.
Furthermore, the Math object contains a number of functions for complex calculations.
- Returns absolute value of 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.
- Returns nearest integer value of x.
- Returns sine of x.
- Returns square root of 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);
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.
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.
- Form feed
- Carriage Return
- Vertical tab
document.write("\tHello\nWorld!"); // Hello // World!
String concatenationTo concatenate two strings together simply use the
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.
- Number of characters in string.
- Substring from m to the end.
- Substring from m to but not including n.
- Changes all casing to upper case.
- Changes all casing to lower case.
- 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
Strange data types
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
Usually you don't declare a variable, but you rather use an expression that evaluates to a boolean value - true or false.
nullsimply 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 means a variable that hasn't yet contained a value.
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 = "Bananas"; groceryList = "Pasta"; groceryList = "Pumpkin"; groceryList = "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
groceryList; // 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
groceryList = '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
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
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"]
To sort elements, use the
var groceryList = ["Tomatoes", "Lemons", "Apples", "Bananas"]; groceryList.sort(); // ["Apples", "Bananas", "Lemons", "Tomatoes"]
To access the length of an array, access the
var numGroceryItems = groceryList.length; // 4
Concatenating two arrays
To add two arrays together, use the
var arrayOne = [1, 2, 3]; var arrayTwo = [4, 5, 6]; var concatArray = arrayOne.concat(arrayTwo); // [1, 2, 3, 4, 5, 6]
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
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."
In the case you want to change from a number to a string or vice versa, you can do so explicitly.
var numString = "100"; var num = Number(numString); // 100
var numString = String(100); // '100' Next section: Control Flow