Giter VIP home page Giter VIP logo

js-reference-types's Introduction

General Assembly Logo

JavaScript Reference Types

Exercising the JavaScript Reference Types.

Prerequisites

Objectives

By the end of this lesson, developers should be able to:

  • Identify array, object, and function literals
  • Create and invoke functions
  • Store, access, and update data values in objects and arrays
  • Iterate through an array or object and operate on its elements

Preparation

  1. Fork and clone this repository.

  2. Create a new branch, training, for your work and change into it.

  3. Install dependencies with npm install.

Reference Types

The following is true for all reference types In JavaScript: refVar instanceof Object === true.

These three reference type are ubiquitous in JavaScript.

  • Plain Object
  • Array
  • Function

The first two are used as collections. The last is encapsulated executable code. All three can be created using reference type literals.

The following shows the simplest examples of these types created with literal syntax:

let list;
let dictionary;
let code;

list = [];
dictionary = {};
code = function () {}; // or `code = () => {};`

And here is the equivalent using constructor function syntax (a topic we'll cover later):

list = new Array();
dictionary = new Object();
code = new Function();

The literal syntax is more common and allows for functionality unavailable with the constructor function syntax.

You can think of each reference type as storing values. You access the values stored in a function reference using invocation syntax, code(). You access the values stored in an array using index syntax, list[0]. And finally, you use member access to get the values from a plain object, dictionary.name or dictionary['name'].

A key difference between a reference and primitive type is best demonstrated with the following code:

let primitive;
let otherPrimitive;
let reference;
let otherReference;

primitive = 2;
otherPrimitive = primitive;
primitive = 7;

primitive;
otherPrimitive;

reference = {};
otherReference = reference;

reference.property = 'value';

reference;

otherReference;

Demo: Functions

In mathematics, a function maps one or more inputs to a single output.

JavaScript isn't that strict, allowing zero inputs or no specified output.

const five = function () {
  return 5;
};

const add = function (a, b) {
  a + b;
};

How do I access the value stored in the reference object referenced by the name five?

Does the value returned by accessing add change depending on the arguments used?

Strictly speaking, all JavaScript functions evaluate to a value, but that value is undefined if we do not provide a return (explicitly or implicitly).

What can we do with functions?

Functions provide important parts of the building blocks of programs, abstraction and encapsulation.

It is important to remember that console.log prints its argument to the console (the terminal using node, the console area of the debug tools using chrome) but does not return a value.

Code Along: Functions

const helloWorld = function () {
  return "Hello World!";
};

const hello = function (name) {
  return "Hello " + name;
};

Parameters and Arguments

When you create a function, you specify the parameters. When you call a function, you specify the arguments (which are the values that the parameters are set to when your function executes).

In JavaScript, functions can be defined as taking zero or more arguments.

const zero = function () {
  return 0;
};

// You call this function by writing: `zero();`

const one = function (param) {
  return param;
};

// You call this function by writing: `one('argumentExample');`

const three = function (param1, param2, param3) {
  return param2;
};

// You call this function by writing: `three(1, 'two', 'example');`

// What would happen if we called this function using only one argument?

three(1);

Demo: Arguments and Return Values

const addOne = (num) => num + 1;

What happens when we call a function with the wrong number of arguments?

How would you create a function with an optional argument?

Code-Along: Arguments and Return Values

const concat = function (wordOne, wordTwo) {
  return wordOne + wordTwo;
};
concat("Hello", "World");
> 'HelloWorld'

What's wrong with this output? What if we use numbers instead of strings when we invoke the function. We could modify this by writing the function invocation like this:

concat("Hello", " World");

This doesn't really seem like it's the way this function should work though, so let's go ahead and make the change to connect two words with a space.

const concatWithSpace = function (wordOne, wordTwo) {
  return wordOne + " " + wordTwo;
};

Collections

There are two general collection types. The list and the dictionary (aka hashmap, map, hash, ...).

  • Lists store lists of things.
  • Dictionaries store uniquely named values.

In JavaScript we use Array and Object respectively to implement these collection types.

What's in a name? Why call an array a list? Why not call a dictionary an associative array?

List (Array)

let fibonacci = [0, 1];
for (let i = 2; i < 10; i++) {
  fibonacci[i] = fibonacci[i-1] + fibonacci[i-2];
}

Dictionary (Object)

let seniorConsultant = {
  'given name':'Antony',
  surname:'Donovan',
  occupation: 'Senior Consultant',
};
let consultant = {};

Code-Along: Dictionary (Object)

Open up Node and type the following with me as we make an object that refers to our first car.

let car = {
  'make': 'Volvo',
  'model': '740 Turbo',
  year: 1990
};

Now try typing the following commands:

car['year']
car.make
car[make]

Code-Along: Analyze Text

We'll be using the file lib/collections.js as a starting point to:

  • create a list of normalized words from a paragraph of text.

  • count words in a string.

  • get the unique words from a string.

  • count the unique words.

  • find the word frequencies (how many times does each unique word appear in the string).

We won't get to methods in detail until later, but there are three on String we'll need to create a list of normalized words: split, which breaks a String into an Array; replace, which makes substitutions; and toUpperCase, which does the obvious. We'll annotate our code as we go so feel free to raise questions if you're not sure what a particular function's purpose is.

We'll also need two Regular expressions:

One or more whitespace characters: /\s+/

One or more non-word characters: /\W+/

grunt test

Lab

We'll use lib/lab.js to build functions to wrap some of the collection processing we've done before. This practice is meant to be challenging.

Additional Resources

Function information

Collection information

Regular expression information and utility

  1. All content is licensed under a CC­BY­NC­SA 4.0 license.
  2. All software code is licensed under GNU GPLv3. For commercial use or alternative licensing, please contact [email protected].

js-reference-types's People

Contributors

payne-chris-r avatar realweeks avatar jrhorn424 avatar raq929 avatar micfin avatar srhoulam avatar

Watchers

James Cloos avatar Dale Dobson avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.