14 KiB
id | title | date | author | aliases | permalink | medium_post | dsq_thread_id | mf2_cite | tags | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
238 | Javascript Data Types | 2015-10-10T20:01:20+00:00 | Brandon Rozek |
|
/2015/10/javascript-data-types/ |
|
|
|
|
Javascript has multiple ways you can store your data. Each of these different ways is called a data type, and they each carry different “methods” which are helpful commands. Today, I’ll show you the different data types and methods that I use and how they’re useful.
This post is by far not a comprehenive list of all the Data types and their methods. If you want one of those, please check out MDN and/or WebPlatform{.broken_link}. This is the second lecture of the web development class I’m teaching for the newer folks over at Math I/O. Due to the nature of Math I/O (making math games and all), the next few posts will be Javascript centric. We’re getting ready to build a new game, so I want to prepare them as much as possible. *Excited* ^_^ Ilya Kantor does a good job of descibing Javascript data types and their many methods in Mastering Data Types which I made the recommended reading for this lecture.
String
A string is one or more characters.
var name = "Brandon";
You can access a character inside of a string by using [] notation. Inside the [] you put the index of the character you want. An index is the numeral location of the character starting from the left. It is important to note that Javascript starts counting from 0.
<td>
r
</td>
<td>
a
</td>
<td>
n
</td>
<td>
d
</td>
<td>
o
</td>
<td>
n
</td>
<td>
1
</td>
<td>
2
</td>
<td>
3
</td>
<td>
4
</td>
<td>
5
</td>
<td>
6
</td>
B |
var firstInitial = "Brandon"[0];
Now the value of firstInitial is the letter "B"
.
Some useful methods for strings
String.prototype.indexOf(); {#string.prototype.indexof();}
This can be used to find the index of any character(s) in a string. I primarily use it for when I need to check if something exists in a string. Do I have a ‘z’ in my name?
"Brandon".indexOf('z');
Nope, so Javascript will return a -1
. How about a ‘d’?
"Brandon".indexOf('d');
Yes, Javascript will return 5
which is the index of the letter ‘d’.
String.prototype.replace(); {#string.prototype.replace();}
The replace method can replace any character(s) with other character(s). For more complex replacing, look into Regular Expression and how you can use them in .replace(). Replace the first ‘n’ in my name with an ‘m’.
var modifiedName = "Brandon".replace('n', 'm');
console.log(modifiedName);
Logs "Bramdon"
.
String.prototype.toUpperCase(); {#string.prototype.touppercase();}
This method returns the string with all the lowercase characters converted to uppercase and can be useful for when you’re checking user input and you don’t want to worry about different cases.
"Brandon".toUpperCase();
Returns "BRANDON"
.
String.prototype.toLowerCase(); {#string.prototype.tolowercase();}
Same as above but instead of converting lowercase to uppercase, it converts uppercase to lowercase.
"Brandon".toLowerCase();
Returns "brandon"
.
A couple useful escape secquences
n
for newline.t
for tab character.
You can also use escape sequnces if you want to add “” or ‘’ to your strings.
var greeting = "Hello "Brandon"";
console.log(greeting);
Returns "Hello "Brandon""
.
Number
Any number between -(253 – 1) and (253 – 1).
Number Methods
Number methods are useful when trying to represent complex numbers.
Number.prototype.toExponential(); {#number.prototype.toexponential();}
Returns a string representing a number in exponential notation.
77.1234.toExponential(2);
Returns "7.71e+1"
.
Number.prototype.toFixed(); {#number.prototype.tofixed();}
Returns a string representing a number fixed to x amount of decimal places.
12345.6789.toFixed(1);
Returns "12345.7"
.
Number.prototype.toPrecision(); {#number.prototype.toprecision();}
Returns a string representing a number using x amount of significant figures.
5.123456.toPrecision(2);
Returns "5.1"
.
Math properties/methods {#math-properties/methods}
In Javascript there is a Math object which contains many properties and methods which are useful for mathmatical calculations.
Return Euler’s constant {#return-euler's-constant}
Math.E
which returns ~2.718.
Return the natural log of x
Math.log(x)
Rise x to the y power
Math.pow(x,y)
Return a psuedo random number [0,1) {#return-a-psuedo-random-number-[0,1)}
Math.random()
Round x to the nearest integer
Math.round(x)
Boolean
Booleans are either true
or false and
are typically used in conditional statements. You can either create them explicitly
var alive = true;
or by evaluating a comparison.
var dead = false;
var isAlive = !dead;
isAlive equals true
.
Array
An array is a list of items. In Javascript these items can be any data type, even arrays themselves.
var mixedBag = ['sword', 24, true, [Math.PI, Math.E], 'shield'];
To access an item in an array use [] notation with an index as mentioned over at strings.
['sword', 'shield', 'helmet'][1];
Returns 'shield'
. to figure out how many items are in the array.
var inventory = ['boots', 'gloves', 'pants', 'shirt'];
var inventoryAmt = inventory.length;
inventoryAmt is 4
since there are 4 items in inventory.
Array Methods
Array.prototype.push(); {#array.prototype.push();}
Adds whatever is inside the parenthesis to the end of the array. Great for adding items to a list. For example, test scores.
[100,92,95].push(80);
Returns [100,92,95,80]
.
Array.prototype.reverse(); {#array.prototype.reverse();}
Reverses the order of all the items in the array.
[1,2,3].reverse();
Returns [3,2,1]
.
Array.prototype.concat(); {#array.prototype.concat();}
Combines two arrays, putting the items from the array in the parenthesis to the end of the main array. This method is a lot faster than grabbing each item by their index and adding them using the .push() method.
['a','b','c'].concat([1,2,3]);
Returns ['a','b','c',1,2,3]
.
Array.prototype.join(); {#array.prototype.join();}
Converts the array into a string, with each item seperated by whatever is in the parenthesis. Useful for telling the user the items in their inventory, for example.
var inventory = ['books','apples','pencils'];
console.log("You have " + inventory.join(", ") + " in your inventory.");
Logs "You have books, apples, pencils in your inventory."
Array.prototype.indexOf(); {#array.prototype.indexof();}
Similar to String.prototype.indexOf(), it returns the index of the item inside the parenthesis.
['chicken','pizza','tacos'].indexOf('tacos');
Returns 2
.
Objects
Objects are like arrays, however they’re easier for establishing the relationship between properties and their values. You can store any data type as a property of an object.
var player = {};
player.name = "Brandon";
player.health = Number.POSITIVE_INFINITY;
console.log(player.name + " has " + player.health + " health.");
Logs "Brandon has Infinity health"
Yup that sounds about right.
Conclusion
All of the different data types in Javascript are tools for you to get the job done. When assigning a variable, think to yourself which tool you should use. I had fun doing this lecture. We finished earlier than expected, due to my extra preparations. (Still shuddering over my unpreparedness from last week). We had finished so early in fact, that I went ahead and started teaching next week’s material. Do not worry though, my lovely reader’s only get the most structured of lesson materials. So you’ll have to wait until next week to hear more. 🙂