sf-wdi-31 / js-data-types

[javascript, data types, arrays, objects]

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

JavaScript Data Types

Why is this important?

This workshop is important because:

JavaScript is the most complete, capable language usable across browsers. It lets us change the content of a page programmatically (on the fly) instead of being stuck with just what's written in the HTML code. It enables complex user interactions.

The need to process information drives programming languages. JavaScript's data types define how it can store and manipulate information. They're the building blocks of everything that can be done in JavaScript.

For web developers, it's critically important to be able to work with JavaScript objects. JavaScript's features are mostly built into objects like Date, Math, and document. We'll also see that JavaScript objects and arrays form the basis of JSON, a very popular format for transferring application data across the web.

What are the objectives?

After this workshop, developers will be able to:

  • Identify JavaScript data types.
  • Declare variables in the Chrome developer tools.
  • Get and set the values of variables.
  • Use built-in methods to manipulate strings and arrays.

Where should we be now?

Before this workshop, developers should already be able to:

  • Open the Chrome developer tools (for example, with Command Option J).

Primitives

A primitive value is represented at the lowest level of implementation of a programming language. All primitives are immutable, meaning they can't be changed.

JavaScript has 6 primitive data types:

  • string: words or phrases (in quotes)
  • number: integer, floating point number (decimal), NaN
  • boolean: true or false
  • null: non-existent object (used for blanking out variables)
  • undefined: empty variable
  • symbol: reusable identifier for object properties (only in ES6)

One of JavaScript's quirks is having both null and undefined. As a rule of thumb, you should let JavaScript decide when something is undefined. You should use null wherever you want to "blank out" a variable so that it has no value.

+NaN is a special global value meaning "Not A Number". NaN is the returned value when numerical evaluations fail, e.g. 8/"hello".

Expressions and Operations

An expression is code that evaluates to some value.

Expressions can include data (like 4 or true) and operators (like =, *, !), object and array lookup, and function calls.

Expressions let us process data in useful ways.

1 + 1;
//=> 2

2 - 1;
//=> 1

Another commonly used operation in coding is the modulo operator, %. It finds the remainder after diving left side by right side.

18 % 100;
//=> 18

5 % 2;
//=> 1

In JavaScript, you can also use a + operation on strings. This is called string concatenation. In JavaScript, it changes non-strings that you add into strings.

"Hello, " + "world!";
//=> "Hello, world!"

"WDI " + 31;
//=> "WDI 31"

These are fairly standard features across high-level programming languages.

Variables

Variables are labeled locations for storing data. You can create a variable with the reserved word var, with or without giving it an initial value:

var numForks;
var lunchTime = 1215;

Instead of writing 1215 over and over in code, a program can access the information by variable name:

lunchTime
//=> 1215

If the value needs to change, the variable can be updated using the assignment operator =.

lunchTime = '12:15!!!!';

Note that you can also freely change the type of data a variable is storing.

Objects

Primitive data types are not enough for most programming purposes. Objects are reference data types that allow us to group primitives together.

Instead of storing a value, variables holding objects store a reference to a location in memory, and the computer looks it up when needed.

var shirt = { size: "L", color: 'green', clean: false };

Objects store information in key-value pairs. The key acts like a label, and the value is the data or behavior associated with that label.

Object is the most basic reference type in JavaScript. Every other non-primitive we'll use -- Array, Function, Date -- is actually built out from the basic Object type.

Object Manipulation

Creating an object literal:

var person = { name: 'Bill', height: '5 feet, 9 inches', age: 34 };

Getting the value associated with a key:

// this is called bracket notation:
person['age']; //=> 34
// this is called dot notation:
person.age;    //=> 34

// what if key doesn't exist?
person['hasGlasses']; //=> undefined

Adding a key-value pair:

person['hairColor'] = 'blonde';
person.hairColor = 'blonde';
//=> { name: 'Bill', height: '5 feet, 9 inches', age: 34, hairColor: 'blonde' }

Setting the value for a key:

person['hairColor'] = 'green';
person.hairColor = 'green';
//=> { name: 'Bill', height: '5 feet, 9 inches', age: 34, hairColor: 'green' }

Semi-removing a value:

Use null as a marker for an empty value.

person.hairColor = null;

Fully removing a key-value pair (rare):

delete person.height;
//=> { name: 'Bill', age: 34, hairColor: 'green' }

Finding keys in the object (rare):

var keys = Object.keys(person);
//=> ['name', 'age', 'hairColor']

Looping through Objects (rare):

One way to loop through objects in JavaScript is to use for ... in loops:

for (key in person){
  // this next condition is required because of the prototype chain, which we haven't talked about quite yet
  if (person.hasOwnProperty(key)){  
    console.log(key, ": ", person[key]);
  }
}
// the order is not guaranteed, but this console logs:
//   'name': 'Bill'
//   'age': 34
//   'hairColor': null

Arrays

var friends = ["Moe", "Larry", "Curly"];
//=> ["Moe", "Larry", "Curly"]

Arrays are objects that store collections of data in sequential order. Arrays are great for:

  • Storing collections of one kind of data
  • Ordered lists
  • Enumerating data, i.e. using an index to find items
  • Quickly reordering data

####Array Manipulation

Creating an array (literal):

var fruits = ["Apple", "Banana", "Cherry", "Durian", "Elderberry",
"Fig", "Guava", "Huckleberry", "Ice plant", "Jackfruit"];

Getting an element by index:

fruits[0]; //=> "Apple"
fruits[3]; //=> "Durian"

Setting the value at an index:

fruits[3] = "Grape";

Noticing a pattern? Arrays are a kind of object, and indices are just the keys. Arrays don't allow dot notation, though.

Looping through Arrays:

  for (var i=10; i>0; i--){
    console.log(i);
  }
  console.log('Blastoff!');

Array Properties and Methods

Finding the number of elements, in the length property:

fruits.length; //=> 10

Note that length is a property, NOT a method, for JavaScript arrays!

Adding an element to the front:

fruits.unshift("Apricot"); //=> 11

Adding an element to the end:

fruits.push("Kiwi"); //=> 12

Removing an element from the front:

fruits.shift(); //=> "Apricot"

Removing an element from the end:

fruits.pop(); //=> "Kiwi"

Finding the index of an element:

fruits.indexOf("Jackfruit"); // 9
fruits[9]; //=> "Jackfruit"

img

Check out MDN's Array documentation for more information on arrays. In particular, all of the methods listed in the Array instances section are available to use with JavaScript arrays. Commonly used array methods include join, sort, and reverse.

Other Object Types

String

JavaScript primitives can't have methods or attributes; they're just simple data. For convenience, JavaScript includes specialized global objects to "wrap" most of its primitives, providing handy built-in methods and properties.

String is the most commonly used of these objects.

MDN String Reference

Math

In order to perform certain number operations, JavaScript has a Math object with some very useful methods.

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

// returns a random decimal number between 0 and 1
Math.random();
//=> 0.229375290430

// rounds a floating point number to an integer
Math.round(2.5);
//=> 3

typeof

Use JavaScript's typeof method to check the type of a variable or value.

Independent Practice

Practice with this training.

Closing Thoughts

For web developers, it's critically important to be able to work with JavaScript objects. JavaScript's features are mostly built into objects like Date, Math, and document. We'll also see that JavaScript objects and arrays form the basis of JSON, a very popular format for transferring application data across the web.

The most important things to practice right now are:

  • getting and setting values from within complex structures that include nested arrays and objects.
  • learning to read documentation.

Resources

About

[javascript, data types, arrays, objects]