Data Types

Objectives

  • Describe the concept of a "data type" and how it relates to variables.
  • Declare, assign to, and manipulate data stored in a variable.
  • Create arrays and access values in them.
  • Iterate over and manipulate values in an array.

Review

  • Be comfortable navigating between folders on the command line.
  • Run JavaScript on the command line using Node.js and use basic variables.

What is a Data Type?

In programming, a data type is a classification identifying one of various types of data.

 

Using data types, we can determine

  • Possible values for that type;
  • Operations that can be performed on values of that type;
  • Meaning of the data; and
  • Ways values of that type can be stored.

Strings

Single words or sentences surrounded by double or single quotes

"Kittens Are Awesome!!!"

"Cute"

"45"

"dfasdfsadjflsakdfj"

Integers

Whole numbers, with no delimiter

42

109

23423423

Floats

Decimals, with no delimiter

42.42

109.23423424

23423423.23423424234234

Note about Numbers

All numbers in JavaScript are "double-precision 64-bit format IEEE 754 values" ==> there's really no such thing as an integer in JavaScript.

Be a careful with your arithmetic if you're used to math in other programming languages.

0.1 + 0.2
=> 0.30000000000000004

Booleans

Represents either true or false

true

false

Array

Ordered Collections of Data

goldenGirls = ["Dorothy", "Blanch", "Sofia", "Rose"]

Object

Key/value paired Collections of Data


bestHero = {
   name: 'Aquaman',
   power: ['swimming','being fabulous', 'lots of sea friends'],
   hairGame: true,
}

Operators

Operators are build in symbols to be referenced in JavaScript – often are math mathematical symbols or used for checking if something is equal, more than, less than ect

Math Operators

2 + 2 // returns 4
4 - 2 // returns 2
4 / 2 // returns 2
4 * 2 // returns 8

// What does the following 
// statement return?
"hello" + "world" 

typeof()

checks the data type of whatever you pass it

typeof(37) === 'number';
=> true

typeof({}) === 'object';
=> true

typeof('hi there') === 'string';
=> true

Math.pow()

// 3^2 becomes
Math.pow(3,2)
=> 9
// 2^4 becomes
Math.pow(2,4)
=> 16

number to nth power

Math.sqrt()

// √(4) becomes
Math.sqrt(4)
=> 2

square root

Math.random()

// The following only returns a random decimal
Math.random()
=> 0.229375290430
/**
  The following will return a
  random number between 0 and 10
*/
Math.random()*10

get a random number

Math.random()

// Remove the decimal
Math.floor(3.14)
=> 3
Math.floor(3.9999)
=> 3

turn a float to a number

Variables

Think of variables as named buckets in which we can place one item

Start a Variable and assign a value to it

var a = 2;

var b = "kittens are cute";

var myArray = ['one', 'two'];

Once your variable is assigned, call it!

a ;
//returns 2

b;
// returns "kittens are cute"

myArray
// returns ['one', 'two']

Making a Variable checklist

  • Instantiate with the keyword 'var'
  • Use '=' to assign a value to it
  • Call the variable AFTER it's assigned
  • camelCase your variable names

reassigning

adding one using +=

Updating a variable

var a = 5;
a = 6;

a;
// returns 6
var a = 5;
a +=;

a;
// returns 6

++, --, -= can also
be used!

Arrays

Arrays are great for:

  • Storing data

  • Enumerating data (i.e., using an index to find them)

  • Quickly reordering data In essence, arrays compose a data structure that is similar in concept to a list. Each item in an array is called an element, and the collection can contain data of the same or different types. In JavaScript, arrays can dynamically grow and shrink in size.

var friends = ['Moe', 'Larry', 'Curly'];
=> ['Moe', 'Larry', 'Curly']

Arrays keep track of the positions of it's contents

// First friend
var firstFriend = friends[0];
 => 'Moe'
// Get the last friend
var lastFriend = friends[2]
=> 'Curly

array.length

var a = ["dog", "cat", "hen"];

a.length;
=> 3

get the length of your array

Arrays are zero indexed

var a =  ['one', 'two', 'three'];

a[0];
// return 'one'

a[1];
// return 'two'

a[2];
// return 'three'

a.length;
// return 3
var a = new Array();
=> undefined

a[0] = "dog";
=> "dog"

a[1] = "cat";
=> "cat"

a[2] = "hen";
=> "hen"

a
=> ["dog", "cat", "hen"]

a.length;
=> 3

Making a new Array

var a =  ["dog", "cat", "hen"];

a;
//returns ["dog", "cat", "hen"]

a[2];
// "hen"
var goods = new Array("water", "coffee")

Array Literal 

'new' Keyword

var myArray = ['frogs','dogs','cats'];

myArray;
// returns ['frogs','dogs','cats']
var goods = new Array("water", "coffee")

goods;
//returns ['water', 'coffee']
var a = [],            // these are the same
    b = new Array(),   // a and b are arrays with length 0

    c = ['foo', 'bar'],           // these are the same
    d = new Array('foo', 'bar'),  // c and d are arrays with 2 strings

    // these are different:
    e = [3]             // e.length == 1, e[0] == 3
    f = new Array(3),   // f.length == 3, f[0] == undefined

Use bracket notation to add values to the one of the arrays; 
goods[2] = "beer"

use the .push() method for the other.
quantity.push(8)

Note on literal vs. 'new' array

 => 'Today, I consumed ' + quantity[0] + ' cups of ' + goods[0]
 => 'I am going to have ' + quantity[1] + ' cups of ' + goods[1] + ' tonight'

Accessing Elements from Arrays and Concatenating Them With Strings

Array Helper Methods

.push()

var message = []

message.push(8)
=> 1
message.push('r', 'e', 'b', 'm', 'u')
=> 6
message.push('n', 's', 'i', 'A', 'G', 'K')
=> 12

message
=> [ 8, 'r', 'e', 'b', 'm', 'u', 'n', 's', 'i', 'A', 'G', 'K' ]

.pop(), .shift(), & .unshift()

message.pop()
=> 'K'

message.shift()
=> 8

message.unshift(1)
=> 11

.reverse()

message.reverse()
=> [ 'G', 'A', 'i', 's', 'n', 'u', 'm', 'b', 'e', 'r', 1 ]

.join()

message.join()
=> 'G,A,i,s,n,u,m,b,e,r,1'

message.join(' ')
=> 'G A i s n u m b e r 1'

Iterating through an Array

For Loop

For every item in my array, do X action

var goldenGirls = ['Blanch', 'Dorothy', 'Rose', 'Sophia'];
for (var i = 0; i < goldenGirls.length; i++) {
	console.log(goldenGirls[i]);
}

.forEach()

var goldenGirls = ['Blanch', 'Dorothy', 'Rose', 'Sophia'];
goldenGirls.forEach(function(el) {
    console.log(el);
});

Other Array Iteration Methods

  • Array.every()
  • Array.some()
  • Array.filter()
  • Array.map()

Practicing Array Iteration

var evens = []
evens.push(2,4,6,8,10)
=> 5

var odds = []
odds.push(1,3,5,7,9)
=> 5

.every()

evens.every(function (num) {
  return num % 2 === 0
})

=> true

evens.every(function (num) {
  return num % 4 === 0
})

=> false
var odds = []
odds.push(1,3,5,7,9)
=> 5

.some( )

var array = [1, 2, 3, 4, 5];

var even = function(element) {
  // checks whether an element is even
  return element % 2 === 0;
};

console.log(array.some(even));
// expected output: true

.filter( )

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

.filter( )

var timesFive = evens.map(function (num) {
  return num * 5
})
=> undefined

timesFive
=> [10, 20, 30, 40, 50]

var timesTen = odds.map(function (num) {
  return num * 10
})
=> undefined

timesTen
=> [10, 30, 50, 70, 90]

Review

Review

  • What is a Data Type
  • Name the different Data Types
  • What does "Iterate over an Array mean?
  • What are some ways to iterate an array?

Homework

Madlibs
Due by Week 7

Homework: Madlibs

For this assignment, you'll create your own Startup Generator app. Open the files in the madlib with loops folder and start by reading the "instructions.md" file. You'll learn how to use helper methods and for loops. We have provided some starter code; while we haven't covered functions and DOM manipulation yet, this is a good chance for you to challenge yourself and get a head start on these topics.

July 23: Data Types

By Jessica Bell

July 23: Data Types

  • 112