Learning Javascript

an introduction

Course CONTENT

  • Setup coding environment
  • Variables
  • Objects
  • Arrays
  • Functions
  • OOP
  • Functional Programming
  • Homework

SEtup coding environment

Setup coding environment

> npm install -g eslint nodemon node-inspector

Install tools using npm

Verify development Environment

console.log("Hello world")
  • touch helloworld.js
  • nodemon helloworld.js
  • atom helloworld.js

Variables

  • Declare JavaScript Variables
  • Storing Values with the Assignment Operator
  • Initializing Variables with the Assignment Operator
  • Understanding Uninitialized Variables

  Declare JavaScript Variables

// Example
var ourName;

// Define myName below this line
ourName = "Nick";

// Example
var ourVar = 19;

JavaScript provides seven data types:

undefined, null, Boolean, string, symbol, number, and object.

declared variables have an initial value of undefined

Math

var product = 8 * 0;

var quotient = 66 / 0;

JavaScript uses the * symbol for multiplication and / symbol for division.

Arrays

  • Create & empty an array
  • Access  & Modify Array Data with Indexes
  • Push, pop, shift, unshift

Create & empty an array

// Example
var array = ["John", 23];

// Initialize an empty array
var myArray = [];

// Empty existing array
array = []

Access and modify array elements

// Example
var ourArray = [1,2,3];
var ourData = ourArray[0]; // equals 1

ourArray[1] = 3; // ourArray now equals [1,3,3].

Push, pop, shift, unshift

// Example
var ourArray = ["Stimpson", "J", "cat"];

ourArray.push(["happy", "joy"]); 
// ourArray now equals ["Stimpson", "J", "cat", ["happy", "joy"]]

var removedArray = ourArray.pop(); 
// removedArray now equals ["happy", "joy"], and ourArray now equals ["Stimpson", "J", "cat"]

removedArray = ourArray.shift();
// removedArray now equals "Stimpson" and ourArray now equals ["J", "cat"].

ourArray.unshift("Happy"); 
// ourArray now equals ["Happy", "Stimpson", "J", "cat"]

Functions

  • Named & Anonymous functions
  • Global Scope and Functions
  • Local Scope and Functions
  • Global vs. Local Scope in Functions
  • Determine total number of arguments
  • Exercise: Write a multiply function

named and Anonymous functions

In JavaScript, we can divide up our code into reusable parts called functions.

function functionName() {
  console.log("Hello World");
}

var array = [1,2,3]

array.map(function(num) {
    return {value: num}
});
// [{value: 1}, {value: 2}, {value: 3}]

VARIABLES SCOPED TO FUNCTIONS

In JavaScript, scope refers to the visibility of variables. Variables which are defined outside of a function block have Global scope. This means, they can be seen everywhere in your JavaScript code.

var foo = 'Canadian Developer Connection';
console.log(foo); // Prints 'Canadian Developer Connection'
if(true){
  var foo = 'BAR';
  console.log(foo); // Prints 'BAR'
}
console.log(foo); // Prints 'BAR'

Local scope

Variables which are declared within a function, as well as the function parameters have local scope. That means, they are only visible within that function.

function myTest() {
  var loc = "foo";
  console.log(loc); // "foo"
}
myTest(); // "foo"
console.log(loc); // "undefined"

Global vs. Local Scope in Functions

It is possible to have both local and global variables with the same name. When you do this, the local variable takes precedence over the global variable.

var someVar = "Hat";
function myFun() {
  var someVar = "Head";
  return someVar;
}

console.log(myFun()); // Head
console.log(someVar); // Hat

Determine total number of arguments

function func(x){
   console.log(typeof x, arguments.length);
}
func();                //==> "undefined", 0
func(1);               //==> "number", 1
func("1", "2", "3");   //==> "string", 3

Using arguments.length property, we can get the total number of arguments passed to a function.

Multiply function

Write a mul function which will produce the following outputs when invoked:

console.log(mul3(2)(3)(4)); // output : 24 
console.log(mul3(4)(3)(4)); // output : 48

Objects

  • Creation
  • Reading and setting properties
  • Access object properties with variables
  • Adding and setting properties
  • Using Objects for Lookups
  • Exercise: Record Collection

Object Creation

var ourDog = {
  name: "Camper",
  legs: 4,
  tails: 1,
  friends: ["everything!"]
};

Reading & setting Object properties

var myObj = {
  prop1: "val1",
  prop2: "val2"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2

// setting object property
myObj.prop1 = "Happy Camper";

Access object properties with variables

var myDog = "Hunter";
var dogs = {
  Fido: "Mutt",
  Hunter: "Doberman",
  Snoopie: "Beagle"
}
var breed = dogs[myDog]; // "Hunter"
console.log(breed)// "Doberman"

Adding & deleting Object properties

// Example
var ourDog = {
  "name": "Camper",
  "legs": 4,
  "tails": 1,
  "friends": ["everything!"]
};

// adding property
ourDog.bark = "bow-wow";

// deleting property
delete ourDog.tails;

Using objects for lookup

var alpha = {
  1:"Z",
  2:"Y",
  3:"X",
  4:"W",
  ...
  24:"C",
  25:"B",
  26:"A"
};
alpha[2]; // "Y"
alpha[24]; // "C"

var value = 2;
alpha[value]; // "Y"

Objects can be thought of as a a dictionary.  If you have tabular data, you can use an object to "lookup" values rather than a switch statement or an if/else chain.

record collection

You are given a JSON object representing (a small part of) your record collection. Each album is identified by a unique id number and has several properties. Not all albums have complete information.

Write a function which takes an id, a property (prop), and a value.

For the given id in collection:

  • If value is non-blank (value !== "") and prop is not "tracks" then update or set the value for the prop.
  • If the prop is "tracks" and value is non-blank, push the value onto the end of the tracks array.
  • If value is blank, delete that prop.

Always return the entire collection object.

Record Collection

// Setup
var collection = {
    2548: {
      album: "Slippery When Wet",
      artist: "Bon Jovi",
      tracks: ["Let It Rock", "You Give Love a Bad Name"]
    },
    2468: {
      album: "1999",
      artist: "Prince",
      tracks: ["1999", "Little Red Corvette"]
    },
    1245: {
      artist: "Robert Palmer",
      tracks: [ ]
    },
    5439: {
      album: "ABBA Gold"
    }
};
function update(id, prop, value) {

  return collection;
}

console.log(update(5439, "artist", "ABBA")[5439].artist) // ABBA
console.log(update(1245, "tracks", "Addicted to Love")[1245].tracks[0]) // Addicted to Love

OOP

  • Construct JavaScript Objects with Functions
  • Make Instances of Objects with a Constructor Function
  • Make Unique Objects by Passing Parameters to our Constructor
  • Understanding This and scope
  • Exercise: Fee Deductor

Construct JavaScript Objects with Functions

We are also able to create objects using constructor functions.

A constructor function is given a capitalized name to make it clear that it is a constructor.

var Car = function() {
  this.wheels = 4;
  this.engines = 1;
  this.seats = 1;
};

var myCar = new Car();
console.log(myCar.wheels); // 4
 

Make Unique Objects 

The constructor we have is great, but what if we don't always want to create the same object?

To solve this we can add parameters to our constructor. We do this like the following example:

var Car = function(wheels, seats, engines) {
  this.wheels = wheels;
  this.seats = seats;
  this.engines = engines;
};

var myCar = new Car(6, 3, 1);
console.log(myCar.wheels); // 6
 

Make object properties private

We can also create private properties and private methods, which aren't accessible from outside the object.

var Car = function() {
  // this is a private variable
  var speed = 10;

  // these are public methods
  this.accelerate = function(change) {
    speed += change;
  };

  this.decelerate = function() {
    speed -= 5;
  };

  this.getSpeed = function() {
    return speed;
  };
};

Understanding This and scope

  • The this keyword’s value has nothing to do with the function itself, how the function is called determines the this value
  • It can be dynamic, based on how the function is called
  • You can change the this context through .call(), .apply() and .bind()

Understanding This and scope

// create an object
var myObject = {};

// create a method on our object
myObject.someMethod = function () {
  console.log(this);
};

// call our method
myObject.someMethod();

Object invoked the function, so this will refer to the Object that called it:

Understanding This and scope

// let's assume .elem is <div class="elem"></div>
var element = document.querySelector('.elem');

// our function
var someMethod = function () {
  console.log(this);
};

// when clicked, `this` will become the element
element.addEventListener('click', someMethod, false); // <div>

// if we just invoke the function, `this` becomes the window object
someMethod(); // [object Window]

This is dynamic, which means the value could change. Here’s a real simple example to show that:

Understanding This and scope

someMethod.call(anotherScope, arg1, arg1); // commas
someMethod.apply(anotherScope, [arg1, arg1]); // array

We can change context of a function with a few methods, .call(), .apply() and .bind().

Understanding This and scope

var obj = {};
var element = document.querySelector('.elem');
var someMethod = function () {
  console.log(this);
};
element.addEventListener('click', someMethod.bind(obj), false); // bind

Using bind

Fee deductor

var monica = {
  name: 'Monica Geller',
  total: 400,
  deductMontlyFee: function(fee){
     this.total = this.total - fee;
     return this.name + ' remaining balance is '+ this.total; 
  }
}

console.log(rachelDeductor(400)); //"Rachel Green remaining balance is 1300"

Given the code below.  Add the necessary code to output the following to the console:

Rachel Green remaining balance is 1300

Functional Programming

  • Description
  • Iterate & filter Arrays with .map & .filter
  • Condense arrays with .reduce
  • Sort Arrays with .sort
  • Iterate an Arrays with .forEach
  • Concatenate Arrays with .concat
  • Exercise: ToDo list

Description

  • Pure functions
  • Avoid side-effects
  • Simple function composition
  • Higher order functions
    • Functions as arguments
    • Returns functions
  • Functions as arguments / values
  • Examples of functional languages: Lisp, Haskell, Erlang, Clojure, Elm, F Sharp, etc...

Map and Filter

var oldArray = [1,2,4]
var timesFour = oldArray.map(function(val){
  return val * 4;
}); // [4,8,16]


array = timesFour.filter(function(val) {
  return val !== 8;
}); // [4,16]

Reduce

The array method reduce is used to iterate through an array and condense it into one value.

var array = [8,6,4,2]
var singleVal = array.reduce(function(prevVal, curVal) {
  return prevVal + curVal;
}, 0);

console.log(singleVal); // 20

Sort

sort can be passed a compare function as a callback. The compare function should return a negative number if a should be before b, a positive number if a should be after b, or 0 if they are equal.

var array = [1, 12, 21, 2];
array.sort(function(a, b) {
  return a - b;
});

console.dir(array); // [1,2,12,21]

Foreach

use for each to iterate over an array with a callback function

var array = [1, 12, 21, 2];
array.forEach(function(x) {
  console.log(x);
});

Concatenate Arrays

concat can be used to merge the contents of two arrays into one.

newArray = oldArray.concat(otherArray);

Todo list

Given the following array of todo items, use functional programming to:

  • Filter out the completed items
  • Sorted by due date
  • Group the items by user
  • Return only subject & due date
var data = [
  {
    username: "batman",
    subject: "Read about functional programming",
    dueDate: "01/15/2016",
    complete: false
  },
  {
    username: "batman",
    subject: "Try out the Node Stream Adventure",
    dueDate: "01/01/2016",
    complete: false
  },
  {
    username: "robin",
    subject: "Build Todo app based on Highland js",
    dueDate: "02/01/2016",
    complete: true
  },
  {
    username: "robin",
    subject: "Build GraphQL server for Star Wars API",
    dueDate: "03/01/2016",
    complete: false
  }
]

Todo list

Results should look like

{ robin:
   [ { subject: 'Build GraphQL server for Star Wars API',
       dueDate: '03/01/2016' } ],
  batman:
   [ { subject: 'Read about functional programming',
       dueDate: '01/15/2016' },
     { subject: 'Try out the Node Stream Adventure',
       dueDate: '01/01/2016' } ] }

Homework

  • ES2015

  • Lodash

ES2015

  • Classes

  • Arrow functions

  • const, let, var

  • enhanced object literals

  • template strings

  • modules

  • promises

Lodash

JavaScript utility library

http://lodash.com

Learning JavaScript

By Nick Nance

Learning JavaScript

an introduction

  • 1,046