YDKJS Types & Grammar

Chapter 2 “Values”

Javascript has some interesting aspects to arrays, strings and numbers! In this chapter we explore them in a little more detail.

Arrays

Javascript arrays are not type-enforced. They can contain strings, numbers, objects, even other arrays aka multi-dimensional array.

var myArray = [ 1, "1", {1:"One"}, ["Juan"] ];

 

Arrays also do not need to have their size predefined. You can just declare and add willy nilly. There is some care when using delete on an array because it will remove the slot, but even if that slot is the last element it does not update the length property of that array. Also watch out for “sparse” arrays by creating empty or missing slots. This can lead to some unintended consequences when dealing with the array values.

Another odd thing is that since arrays are also objects you can have string key/property values added to them, but this does not change the value of the length of that array, unless that value can be coerced into a base-10 number!

var myArray = [ ];
myArray[0] = 1;
myArray["crazytown"] = 42;

myArray.length == 1; //true
myArray["crazytown"] == 42; //true
myArray.crazytown; //42

//watch out for numbers!

var myOtherArray = [ ];
myOtherArray["42"] = "crazytown";
myOtherArray.length == 43; //true 

 

Interesting ES6 built-in called Array.from(…) It can do more that I will have to learn about!

var arr = Array.from( arguments );

 

Strings

At first glance one might think that strings are just arrays of characters. Strings have a length property, an indexOf method and even a concat method. So they are the same right? Not so fast! JavaScript strings are immutable, while arrays are! Look at the following:

myString = "ramen";
myArray = [ "r", "a", "m", "e", "n" ];

myString.length == myArray.length; //true

myString.indexOf( "e" ) == myArray.indexOf("e"); //true

//however watch this

myString[1] = "X";
myArray[1] = "X";

myString; // "ramen"
myArray; // myArray = [ "r", "X", "m", "e", "n" ];

 

If you find yourself treating strings as arrays, consider using just an array. You can always join the array back up if you need to use it as a string.

Numbers

Unlike many other programming languages javascript has only one flavor of numeric datatype. number. This number contains integer(ish) numbers and fractional decimal numbers. The ish above is because the integers are just not exactly as you would expect. Google has a ton of examples, here is one. Trailing and leading 0’s are removed from decimals 0.42 becomes .42 and 4.200 becomes 4.2 etc.

Another interesting thing is that numbers get access to the Number.prototype methods, like toPrecision() and and toString(). Some caveats when using them. If you tried 42.toString() returns invalid because the initial . is considered to be a part of the 42, you can get around this by using parentheses (42).toString() or 42..toString(). Things have changed a bit for octal literals in ES6 and/or strict mode so that 0363 no longer equates to 243 instead you would use 0o363… very fun.

You can also get whonky stuff like 0.1 + 0.2 === 0.3 returning false… There are ways around this, ES6 has some specific tools for this (see Number.EPSILON). ES6 also has Number.MAX_SAFE_INTEGER (9007199254740991) and Number.MIN_SAFE_INTEGER (-9007199254740991) it also has an isInteger test that you can polyfill by checking typeof num is “number” and its % 1 is 0. It gets deeper with ES6 as you can use .isSafeInteger

Numbers are strange, mmmkay.

Special Values

I like these. They are special! They are null, undefined, and void . null being an empty value and undefined being a missing value. null is a keyword making it have a sort of protection field around it so you can assign null to something. undefined can be, at least in non-strict mode, you can do bad things like setting undefined to equal something! Just don’t do it!

Void is an interesting one, I have dug around and I don’t think I know why I would use this. I am sure as I get deeper into javascript I will figure it out.

Special Numbers

NaN, not a number… even though the typeof for a NaN is a number… mmm bad naming conventions. I have learned to think of it as just being a bad number. It happens when you try a mathematical expression using something that is not a number. Another interesting quirk about NaN is that it is not equal to itself! so NaN !== NaN… kooky. Using this we can create an interesting polyfill to check to see if something is NaN.

if (!Number.isNaN) { //if the browser does not have access to this
    Number.isNaN = function (n) {
        return n !== n;
    }

 

Cool! I will have to make sure I start putting this in!

To Infinities and beyond! Okay not beyond, but right to them! Basically this means you can make a value that is just too big (or too small) for JS to deal with and it assigns it Infinity or -Infinity. This leads us to another special case in javascript…

Zero or 0 or -0?

Javascript has both a 0 and a -0. What makes it even more difficult is that 0 == -0. Another helper function pops up!

function isNegZero(n) {
    n = Number( n );
    return (n === 0) && (1 / n === -Infinity);
}

 

Again I think I need to get deeper into code to see why this would matter. For now I will just keep it in the back of my mind.

Special Equality

When we need to check for these special equalities ES6 gives us a tool to help. Object.is() to the rescue. So now Object.is( 0, -0); returns false! Wahoo! Save Object.is for special occasions where you might need to check this!

Value vs. Reference

A reference in javascript points to a space in memory so if you have multiple references to this space in memory they do not reference each other. Only the type of the value designates whether the value is assigned by copy or by reference.

Scalar Primitives are always assigned by copy: null, undefined, string, number, boolean and symbol.

Compound values such as objects and functions always create a reference copy on assignment or when passed.

 

This and That, mostly this.

The question of “What is this?” can be a tricky one. Even outside of programming context is required. Can I see it? Do I know who is asking me? Is it blue? Let’s focus in on what it means in computer science, even more specifically what does it mean in Javascript?

Mostly this has a value that is determined by how a function is called. We also know it can’t be set by assignment during execution. It can also be a different value each time the function is called. What have we learned so far? It is all about context. There are options such as bind
to set the value inside a function regardless of how it was called. There are also some ECMAScript 2015 ideas called arrow functions where this
is lexically scoped (it is set to the this value of the execution context closure).

Still not super clear. Time to dig a little deeper.

Starting with the global context.

Open the developer console and type this. You get a huge object. With so many properties that it is not easy to visually parse. Looking at a few of the more familiar ones what do we see?

this.Array === Array; // true

this === window; // true

this.a = 37;
this.a === window.a; // true

As we see the value of this in the above context is the global object (window in the case of a browser). How does this change in a function?

function thisFunction1() {
  return this;
}

thisFunction1() === window; //true

function thisFunction2(){
 "use strict";
  return this;
}

thisFunction2() === undefined; //true

Since in thisFunction1() this is not defined by the call AND because its not in strict mode the value of this defaults back to the window option. We see in the second example thisFunction2() the value of this remains at the value set when entering the execution context. If it is not defined we get… undefined!  It’s getting a bit more clear, I can still read through it though.

Arrow Functions? I have recently become a huge fan of arrow functions. They are clear to read, shorten my code and now I can more easily understand what this would be during function execution.

It looks like when you initially define the this value it will stick. It will also be set for any calls to functions that live as object methods if the object method is an arrow function. There is a great example on developer.mozilla.org Even functions within functions the this value stays tied to the outer execution context.

More on object methods, not just fat arrow style.

var objectWithMethods = {
  someValue: 42,
  usefulMethodName: function() {
    return this.someValue;
  }
};

console.log(objectWithMethods.usefulMethodName()); // logs 42

 

When making a function that will be used as a constructor with the new keyword its this will be bound to the new object.

More on this later!

addEventListener() and you!

Event Delegation

What is it? Well I can tell you it is great! Gone are the days of an onMouseOver event watcher on every list item or span on your page. Now you can tell the parents to pay attention to their kids by reminding them to listen to the conversations they little ones are having and reacting appropriately. We do this by using  addEventListener. This brilliant function does just what it says. This one is easier to explain by example, so here goes.

<div id="parent-div">
<span id="child-1">One</span>
<span id="child-2">Two</span>
<span id="child-3">Three</span>
</div>

<script>
// Get the element, add a click listener...
document.getElementById("parent-div").addEventListener("mouseover", function(e) {
// e.target is the moused over element!
// If it was a span item
if(e.target && e.target.nodeName == "SPAN") {
// SPAN item found! Output the ID!
console.log("List item ", e.target.id.replace("child-", ""), " was evented!", e);
}
});
</script>

It is really as simple as that. Now when any child span is moused over the id number for that child will be sent to the console. You can also use specific classes if you use .matches(“className”). Digging deeper into this has me going down the MouseEvent rabbit hole so I know what my next post will be about! I mean who wouldn’t want to learn about MouseEvent.bubbles! BUBBLES!

Final Days as Student at MakerSquare

I am on my last day as a Student at MakerSquare, I have been accepted as a Fellow (more on that later) but I thought it might be a good time to do some reflecting. First thing that strikes me is how long it seemed at the start and how quickly the time went by. I swear days turned to minutes and weeks to hours. I am amazed at how much I learned in such a short period of time. It has been exponential!

I am also aware that the bonds I have developed need attention if I want them to last a lifetime. I am making it a priority to stay in contact with those I have grown close to. This is easily my weakest area so I hope I can stay on top of it. I will never forget the late nights coding and watching TNG. Even the frustrating moments and mini-conflicts that popped up only seemed to draw me closer to my fellow learners.

Even though I am staying on for a bit longer I am still very excited to see what happens to them next. It will give me a hint as to my own future, more things to look forward too, more struggles, more life! I love you all and can’t wait to see the great things that I am sure you will all do!

Importance of Self Documenting Code

What is self documenting code?

Let’s first take a look at code that is not self documenting.

var x = 1;
if (y === true) {
  x += 1;
}

vs 

let count = 1;
if ( loggedInSuccessfully === true ) {
  count += 1;
}

Even though this is a very simple example you can see right away that in the first example it is unclear what x is used for. You may be able to figure it out in context of the rest of the program but you might not.  In the second example it’s much easier to deduce that we are incrementing count every time someone has logged in successfully is true.

Now imagine this was a more complex function in the code.

function z () {
  let x = [];
  let y = _.keys(s);
  tables = _.map(y, function (y) {
    return function () {
       return z(y);
     };
   });
 return sequence(x);
}

vs

function createTables () {
  let tables = [];
  let tableNames = _.keys(Schema);
  tables = _.map(tableNames, function (tableName) {
     return function () {
       return createTable(tableName);
     };
  });
 return sequence(tables);
}

In this slightly more complex example there is only one clue as to what you might be doing in that first function. It’s the keyword sequence and even that just gives you a hint that they might be using the when promise library. This would require that either you wrote the horrible code so you know what it does or a decent amount of time trying to use it with in the code base.

The second one, well it looks like it wants to create a table based off an array of tables using the a function called keys to read the table names from a Schema variable. Then it builds that array by using a function called map to go over the tableNames schema, returning a function that calls the createTable function on the passed in tableName. Then we return the sequence output on that array we just finished building.

Even if that second paragraph does not make complete sense it will let you discuss the function with other programmers or support forums in a more intelligent way. That is the main benefit of self-documenting code, however it will also help you remember what you were doing when you have to revisit the code later.

One of the side effects of self-documenting code are potentially very long variable names. I have seen things along the lines of thisWillBeWhereWeStoreTheResultsOfTableCreationErrors. A bit hard to swallow but I have a pretty good idea what type of data I should expect to retrieve or store there.

Breaking it down

Reasoning

  • Create readable and understandable source code
  • Make it easier on the next guy (or your memory)
  • Keep code cleaner with less comments
  • Keep the documentation inside the code

Practices

The main goal is to make it as human readable as possible. Instead of single word variables use a phrase that is more closely tied to the meaning. The other aspect is to use white space to keep the structure consistent and reduce obfuscation of the algorithm being used.

Gotchas

 

There are things to watch out for, if working with a team, is to maintain uniformity, consistency and to make sure it doesn’t get too far out that it becomes a novel to go through your code.

If you stick to these basic guidelines you will do better than many professional developers out there. If you want to learn more head over to the wiki page.

Maker Square Day 6

Data Structures

Linked List

Singly Linked List

Singly Linked List (see video)

What is a linked list? It is a list where each section of the list knows the name of the next section of the list. Something like a->b->c-X where X is null. If we look at a we know we can get the next value, so a.next would be b. This is interesting because without knowing what is third we can find it by going a.next.next = c because b knows about c. Then we can pull the information from that location a.next.next.info = 3000. You might be saying so what?

Here are some reasons for a linked list.

  • you need constant-time complexity for insertions and deletions from the list i.e. to increase time predictability
  • you don’t know how many items will be in the list. With arrays you might need to re-declare and copy memory if the array grows too large
  • you don’t need random access to any elements
  • you want to be able to insert items in the middle of the list such as a priority queue.

Though there is debate on almost every reason to use it vs another data structure. Hopefully I will learn more and make up my own mind on when I would like to use them and not. For now… just store it and move on.

Tree

Tree Data Structure

Tree Data Structure

A tree is a hierarchical structure with parents and descendants at the very minimum. Not super useful yet, but add in siblings and it gets a bit more exciting. There is a bunch. So I am going to put them in a list… hrmm.

  • Root – The top node in a tree.
  • Parent – The converse notion of a child.
  • Siblings – Nodes with the same parent.
  • Descendant – A node reachable by repeated proceeding from parent to child.
  • Ancestor – A node reachable by repeated proceeding from child to parent.
  • Leaf – A node with no children.
  • See the wikipedia entry for even more good stuff.

Once all of these things go together we can see that now it has some value. Thinking of the DOM right away, but also a great way to store data that has this type of relationship. Grape growers could track down to the grape if they wanted to in a production line. Builders working on a complex structure could be arranged this way with responsibilities being assigned to nodes.

Graph

Undirected Graph

Undirected Graph

We only looked at one type of graph, the undirected  graph.  This is a set of nodes that have a set of unordered pairs called edges linking them.  Think of a community. House A, House B and House C. House B is on the corner of two streets. House A is on one street and House C is on the other. House A and House B share an route, and House B and House C share another route.

So… House A has an edge to House B. House B has an edge to House A and House C. House C has an edge to House B. Clear? okay good. Also that network at the top is a graph.

Some common things to be done with graphs you say? Glad you asked. Add a node. Add/Remove edges. Get Neighbors? Sure list every node that has an edge to me.

Most of this day was spent on finishing up the sprint and going into the extra credit section a bit.

Maker Square Day 5

Test Driven Development
Write a failing test, then code to the test. Go from Red to Green to Refactor. Why test? It changes the way you think about code. Forces the MVP thought process. Once you have an error, write a test.
Types of Testing
Unit Test – normally focus on 1 single method or class. Unit testing uses faked data.
Integration Test – ensures different parts of system work together like creating a customer, logging in a customer etc.
End to End test – make sure it works in real world test most realistic form of test. Start to finish, whole system. Think about smarter, less tests.
Visual Test – does it look like what it should look like?

 

Maker Square Day 4

Video Lecture on Complexity Analysis. Space = memory. Time = when. How does time grow?

An algorithm is a plan that helps you solve problems.

To compare all numbers is n^2 is of quadratic time complexity.

Find largest by finding smallest? On

if sorted list, compare first and last is constant time. Gives an approximation of time, not an actual number. Note, highest order first. Think about it as LARGE(n).

Static analysis = analyse and reason through it with graphing.

Constant = array look up
O(log n) = binary search
linear O(n) = print array;
O(n^2) = find largest (nested for loops)
O(c^n) = guess password of (n) length

Binary Search?

var binarySearch = function(array, ele, start, end){
  var start = start || 0;
  var end = end || array.length-1;
  var midpoint = Math.floor((end + start) / 2);
  if (array[midpoint] > ele){
    return binarySearch(array, ele, start, midpoint-1);
  }
  else {
     return binarySearch(array, ele, midpoint+1, end);
  }
}

Protoypal Classes

Q: Can you think of a way to use prototype chains that might help? Removes extend loops, allows chaining of values and having them push out.

Talking about obj within constructor class is the same as talking about every instance. To create a function for making instances is a line in that function where you create a new instance object (object.create(car.methods)) an object as a prototype and some logic for augmenting the new object with properties that make it unique from other objects in the same class (obj.loc = loc).

Pseudo-classical Classes

new keyword = when new is used before a function it acts in a special mode called constructor mode. (var foo = func() {blah;}; var blah = new foo;) constructor mode sneaks in the this.object.create(car.prototype); and the return this; at the end of the function. Pseudo-class has two parts, the prototype properties to hold similarities  and the constructor function to hold the differences.

Open Source Lecture

Productivity Tip: Look at OctoTree for chrome and git access

To contribute to open source projects is a good thing! You don’t have to be a genius to help out. Look at the larger repos. Think about clarifying comments, adding tests, even making sure the style is consistent. These things are needed and appreciated.

Tips for success. Follow repo styles and conventions. Pay close attention to the commit message conventions. Changes should be a single commit. Well written merge comments will increase the chance of a successful pull request.

Data Structures

Quick review on scope and closure. Scope = set of rules to define value availability lexical scoping. Closure = if you instantiate an object the instantiated object has access to the original object.

Hash Tables

Very similar to an object. 2 components to a Hash table. The storage part and the hashing function.  The hashing function takes a key, and dresses it up so that its always the same dress for the same key. This hashed key equals the location in storage. We must watch for collisions, and distribute as evenly as possible to reduce collisions.

 

Makers Square Day 3

I don’t know about you but sleep has not been a close and personal friend of mine. Its a love/hate relationship at best tending towards the latter, or is it ladder? I must be tired. It was on Day 3 (dun, dun, dunnnn) that I noticed that I had forgotten to sleep much *cough* is that an owl? *harumph* I am fine, as I was saying an owl has three eyelids: one for blinking, one for sleeping and one for keeping the eye clean and healthy. Wait, I had a segue I was supposed to say, something about night owls…

To The Notes!!!

Best Practices

I have to preface this with a caveat. I really liked this lecture. It made me feel as though I could contribute if only because I enjoy clarity over cleverness. I usually stand in awe of cleverness, but strive for clarity. If that makes sense. Well on to the actual notes.

Save often! Use the auto-save feature of whatever IDE you are in. If it does not have one complain. Only commit to git when working.

Frameworks, when, where, why? (sometimes what?) – It’s a roll your own (smoking reference in this day and age?) vs others. If you really must I would say roll your own, but REALLY look for another solution or you are wasting your time. Let others solve the problems that have already been identified by the community, for now. (A Jedi must have patience)

Modularity

Keep parts together that are related. Avoid bad closure. use input var/let for dependencies, avoid mutating. avoid global. avoid side effects.

Decoupling

Keep unrelated things, unrelated. It sounds obvious but I have found it easy to want to ‘normalize‘ everything. This is the wrong use of normalize, hence the quotes and italics but you will hear it used this way in the real world. They really mean avoid mutating. I see decoupling as breaking the functions down to as small as possible. For the MASH fans out there:

I do one thing at a time, I do it well, and then I move on.
                                                                   –Charles Emerson Winchester III

Abstractions

Hide the guts. Show the usage. It really can be that simple. Think _.each(array, thingToDo); vs

function(collection, iterator) {
  if(Array.isArray(collection)){
    for (var i=0; i < collection.length; i++)
     iterator(collection[i], i, collection);
  } else {
    for (var key in collection) {
       iterator(collection[key], key, collection);
    }
  }
}

Style

Self describing code is better than comments, but comments are better than clever. Follow the company style. Aim for short, compact code. MVP first.

Embrace Failure!

Failure is inevitable, it also indicates you are doing something interesting. Simply put, what is the formula for success? Fail until you succeed.

Common Pitfalls

Failure to read instructions. Read them. Then re-read them. Then.. yeah. Think about the intention.

Formatting

Use 2 spaces instead of tab. White space is your friend. Be consistent. Keep blocks aligned. Avoid redundancy. Keep blocks aligned. Did I mention to avoid redundancy? No? Well do it.

‘use strict’

It was a great day!