Category: Tiffany’s Posts

ES6 modules allows us to have reusable code, in separate files. We do this to eliminate initially massive js files, like app.js in a Node and Express project. Modules allow us to spread code over relevant files.

As you may have seen in my last post, I have some *ridiculous* conditional statement blocks going on to show/hide the Skycons and for switching up the background photos based on your current weather conditions.

As I step through The Web Developer Bootcamp, I am beginning to realize just how much I’ve learned the last two years and how it is beginning to codify in my brain.

I am coming from a Humanities background but I have always had technical chops, working with circuits was a thing I liked to do; improvising is fun.

I was, a long time ago, a Computer Networking major but decided that I wanted to build computers instead of administering them. Before class started I chose Electronics Engineering Tech at my local 2 year. I did very well. I got an A in my first class, being the only black person as well, by the middle of the semester, the only female. This was the early 2000s.

I’ve always had technical chops. In fact, I taught myself electronics over the course of two years and was competent enough that my physical science professor wanted me to help her teach the electronics section. She was a physicist and my hero.

I prefer being an autodidact, if you haven’t guessed by now.

Translating Hardware Chops into Software Chops

I just played around with circuits and diagrams of those circuits with basic logic structure knowledge. I had and have the ability to learn logically complex things. The fact that it has taken me two years and 5 CS classes as well as learning on my own makes me feel really silly. I have always been the smartest person in the room. It is quite humbling to struggle with something that you feel you should get right away.

Sometimes I look at other newbies and see they struggle with simpler concepts than I did. It makes me feel better 1 but I also want to help them become competent.

The Web Developer Bootcamp and Leveling Up

I have been studying for two weeks practically non-stop. I am seeing so much progress that it encourages me to keep going. I can ask relevant questions of the material, when I get stuck instead of running to Stack Overflow or Slack/Gitter first thing, I open up Dash Docs and read the MDN, which is beginning to make a lot more sense to me.

I can write simple algorithms much more easily than just a few months ago. I don’t know what happened or what switch flipped but I am really, really happy.

Being Happy For Other Developers Success, However…

I see developers all around me getting jobs. I am happy. I am really happy for them. This isn’t a fake happy. It is how things should work. You never begrudge another’s success.

I do, however, feel a pang of longing when I see the tweets and YouTube videos. I am waiting for my turn.

The helpful thing for me right now is knowing I am about a little over a half a year from being ready to apply for developer jobs. It is the solace I need to not get discouraged.

This will be a series on working with arrays. Not sure how long it will be but there is so much rich information about arrays in JavaScript that I don’t think I could fit it all into one post. It may not be a series after all; I may just revisit the topic every now and again.

Arrays

An array is an object in JavaScript. It is a global object set out in a list between two brackets []. Elements in an array are separated by a comma. An array can have any type of data, in any order, inside of the brackets.

For instance:

var myArray = ["John", 39, "Tiffany", 37, false];

is a typical array. Usually we can get the index, or position, of a piece of data in an array by bracket or dot notation.

Arrays in JavaScript can have a mixture of data types; in my example above I mix strings, numbers, and a boolean data type in one array.

Initializing an Array

You can initialize an array as follows:

var myArray = [10];

You can also initalize an empty array such as:

var emptyArray = [];

This is useful for having a place to hold values that will be initialized later in your code.

Accessing Array Elements

You can access array elements by their index in the console. JavaScript arrays are zero-indexed, much like Java and other languages. An example of the syntax:

var indexOfArray = ["Jerri", 69, "Tiffany" 37, false];
console.log(indexOfArray[4]); // This would return the boolean value 'false'
console.log(indexOfArray.[2]); // This is accessing an array with dot notation.
// This would return 'Tiffany'
console.log(indexOfArray.1); // This isn't proper syntax as properties that begin with
// a number can't be accessed using dot notation
console.log(indexOfArray.0); // This is okay as it is a string

The .length Property

You can see how many items are in an array with the .length property. The syntax is similar to accessing an index with dot notation:

var howMany = ["Jerri", 69, "Tiffany" 37, false];
console.log(howMany.length); // this will return 5 as there are 5 items in the array.
// Not to be confused with *indeces*

These are some basic facts about JavaScript arrays. Stay tuned for more.

What is the Execution Stack? Before I answer that question, we’ll first have to take a look at the Global Execution Context

The Global Execution Context, in general terms, is the environment in which the function gets invoked, or the variable’s scope. The Global Execution Context, creates global object, a window object, and a this variable in its creation phase as well as storing any variables you’ve made stored in memory.

The first function gets created on the global execution context called an, as you probably guessed, execution context and has its own space for variables and functions. The global execution context reads line by line until it comes to the next function. Every function creates a new execution context. Once there are no more functions to execute the top function on the execution context gets popped off. Whatever is at the top is currently running.

The Global Execution Context, then, is the outer portion of the Execution Stack or Call Stack. The functions that are invoked in the Execution Stack are lexically sitting on top of one another and being called from top to bottom. JavaScript is a synchronous language, which means the code you write gets executed line by line, from top to bottom.

Talking About the Scope Chain

So how do the execution stack and the scope chain come together? It depends on where the function sits lexically. Take a look at this code:

The execution stack has to search for the variables you defined and where you defined them, making references to the outer lexical environment. This is called the scope chain.

When this code is executed, since the scope chain can’t find myVar in function yourFunction() because it isn’t lexically in the local scope (remember your scopes) and the outer reference is in the global execution context, the console.log will display 37.

If we were to change where function yourFunction() sits lexically in the execution stack, for instance:

Everything is created along the same lines. The global execution context is created, myFunction() sits on top of the global execution context, yourFunction() sits on top of it. But when the scope chain looks for its outer reference lexical environment this time, yourFunction()’s outer reference lexical environment is myFunction() because yourFunction() sits lexically inside of it.

This is how, under the hood, local and global scope function. For further information see: ECMAScript Docs

In JavaScript, lexical scope deals with where your variables are defined, and how they will be accessible — or not accessible — to the rest of your code.

There are two terms to think about when talking about scope: local and global. These two terms are important to understand, because one can be more dangerous than the other when declaring variables and executing your code.

A variable is globally scoped if you declare it outside of all of your functions. For example:

When a variable is in the global scope, it can be accessed by all the code in the same JavaScript file. In this example, I’m accessing the variable a in my console.log statement, inside the myFunction function.

Local Scope

Local variables only exist inside functions. They are scoped to that individual function.
You can think of local variables as as any variables that fall between an opening and closing curly brace.
These local variables can’t be accessed by code outside of the function to which they belong.

Different Languages, Different Paradigms

When you are working with different languages at the same time, it is important to note that while most languages are based on C, each langauge has its own set of rules and paradigms associated with it that makes similar conventions different.

Java and JavaScript, while having Java in common, are completely different languages1. As such, the way they deal with primitive values2, functions and methods, arguments and parameters, differ as well.

Dealing With Objects and Methods in Java

Java is an Object Oriented Programming language which basically means creating objects as part of a class, instantiating the object and adding methods to the object to actually do things with the newly created objects. You can then make your code more modular by adding and calling functions that manipulate the code in some way.3

Here we have a class and a constructor, a new object Dog with a few getter and setter methods on the Dog object.

This is standard Java OOP stuff. JavaScript isn’t an OOP language, it is a prototypal language which creates object prototypes in order to extend objects through prototypal inheritance instead of classical inheritance, like Java.4

Dealing with Objects and Methods in JavaScript

Objects in JavaScript are not created the same way as in Java. At least not technically, and this:

Pass by Value in JavaScript

The only thing you can pass by value in JavaScript are primitive data types.

Passing by value means that you have two variables in memory that are assigned to one another. For instance:

var a;
var b = 8;
var a = b;
console.log(b); // will return 8

What’s happening when we pass these primitives by value, we are making a copy of the value of the variable b stored in memory, say at address 0x001 and assigning it to a stored at 0x002. Both a and `b mirror each other as they are just copies of one another. This is what is meant when we say we are passing by value in JavaScript.

The first line is followed to the Dog it points to, which is the Dog object at 0x001. That dog is asked to change names to Sparky, at the same address of 0x001.

In the second line, a new Dog is created at a different address, say, 0x006. We assign the yourDog param to the memory address 0x006.

In the last line, yourDog is followed to the new Dog it points to in 0x006. That Dog changes his name to Jeffie. Then it returns.

myDog didn’t change. myDog is a pointer in memory that points to the original address, 0x001, not an actual Dog.

You can pass references to parameters by value and not the actual references themselves.

Pass by Reference JavaScript

Passing by reference in JavaScript can only happen to objects. This includes functions as functions are first-class objects in JavaScript.6

Passing by reference involves having two references point to the same object in memory. This means you can mutate and object or function by assigning it to another object or passing it as a parameter to a function. Take this code:

Pass by Reference in Java?

Pass by reference mixes inputs and outputs of code. This is the fundamental problem with the technique. In Java, a programmer can assume that variables will not change their value when passed as parameters to a method. In languages with pass by reference semantics, this basic assumption cannot be made.

Pass by reference confuses the interface to a method. Methods written using pass-by-reference semantics can have extremely complex interfaces that are difficult for client programmers to learn and understand.

Excluding pass by reference was a design choice. It fills a need in some languages, like JavaScript but can present problems in others.

That Was Long

Sorry about the length! If you have anything to add, leave a comment down below. Let me know if I am wrong or off-base. I don’t mind.

UPDATE: I suppose you can’t redeclare a variable with let in the example of pass by value in JS. So I went to the console, did some console-fu and decided to use var though it is dated. Still learning ES6.

UPDATE 2: So I learned you cannot pass by reference in JavaScript though that is exactly what I was taught, albeit incorrectly. You can pass a reference to another object, but you cannot pass by reference in JavaScript.

What Is Meant by an Algorithm?

Algorithms are simple: they are a set of instructions broken down into simple steps in order to complete a larger task.

For example, if I want to make a recipe for stuffed peppers, I would usually follow steps such as:

Preheat oven to 350°F.

Cut out stem ends of bell peppers.

Discard stems.

Scoop out seeds.

Bring 8 cups water to a boil in a large pot and blanch the peppers until tender-crisp, about 1 minute.

Drain.

Cool under cold running water.

Set aside…

And so on.

This is a really simple example of an algorithm.

Using Algorithms in Java

In Computer Science, there are well established methods given to students to help them master algorithms. One of them is the speeding ticket scenario, where you are making a text-based system to calculate fines for speeding, speeding in a construction zone, DUI, and being under 21 with a DUI, etc.

Here, we step through getting the data with a few conditionals:

publicstaticvoidmain(Stringargs[]){// Create a scanner to read from keyboardScannerkbd=newScanner(System.in);// declare and assign values to variables that we can use laterStringfirstName="N/A",lastName="N/A";intage=0,speedLimit=0,actualSpeed=0,mphOverLimit=0;intbaseFine=0,underAgeFine=0,zoneFine=0,totalFine=0;//################ Input ######################// Here, the person calculating the fine would enter the data which is// read in by the scanner objectSystem.out.println("Enter your first name and last name. > ");firstName=kbd.next();lastName=kbd.next();System.out.println("Enter your age. > ");age=kbd.nextInt();System.out.println("Enter the speed limit. > ");speedLimit=kbd.nextInt();System.out.println("Enter your actual speed. > ");actualSpeed=kbd.nextInt();System.out.println("Did the violation occur in a construction zone? Enter yes or no. > ");StringinConstructionZone=kbd.next();//########### Speed Limit Fines #########// Algorithm, step by step, giving the computer instructions on how to calculate// the fine using conditionalsif(actualSpeed>speedLimit){mphOverLimit=actualSpeed-speedLimit;}else{mphOverLimit=0;}if(mphOverLimit<5){baseFine=0;}elseif(mphOverLimit<=20){baseFine=mphOverLimit/5*30;}elseif(mphOverLimit>20){baseFine=mphOverLimit/5*50;}//########### Zone Fines ############if(mphOverLimit<5){zoneFine=0;}elseif(inConstructionZone.equals("yes")||inConstructionZone.equals("y")||inConstructionZone.equals("Yes")||inConstructionZone.equals("YES")){zoneFine=baseFine*baseFine;}elseif(inConstructionZone.equals("no")||inConstructionZone.equals("n")||inConstructionZone.equals("No")||inConstructionZone.equals("NO")){zoneFine=0;}//############## Age Fines #############if(age<21&&mphOverLimit>20){underAgeFine=300;}else{underAgeFine=0;}//############# Total Charges ##############totalFine=baseFine+zoneFine+underAgeFine;// Telling the JVM to print out each formatted scanner input on a new lineSystem.out.println();System.out.format("name: %s, %sn",lastName,firstName);System.out.format("age: %d yrs.n",age);System.out.format("actual speed: %d mph.n",actualSpeed);System.out.format("speed limit: %d mph.n",speedLimit);System.out.format("mph over limit: %d mph.n",mphOverLimit);System.out.format("base fine: $%dn",baseFine);System.out.format("zone fine: $%dn",zoneFine);System.out.format("under age fine: $%dn",underAgeFine);System.out.format("total fine: $%dn",totalFine);}// END MAIN}// END CLASS

Some More Complex Algorithms

There are more complex, established algorithms that use data structures like arrays, dictionaries, and linked lists. Most algorithms are judged on their complexity and effieciency, where efficiency does not necessarily mean speed.

For example, the Bubble Sort algorithm sorts the values in an array from smallest to largest by assessing the first index and comparing it with the next. If the first value is larger than the second, the bubble sort algorithm swaps the two values.

Here is a version of the bubble sort algorithm in pseudocode:

procedure bubbleSort( list : array of items )
loop = list.count;
for i = 0 to loop-1 do:
swapped =false
for j = 0 to loop-1 do:
// compare the adjacent elements
if list[j] > list[j+1] then
// swap them
swap( list[j], list[j+1] )
swapped =true
end if
end for
// if no number was swapped that means
// array is sorted now, break the loop
if(not swapped)then
break
end if
end for
end procedure return list

This a simple algorithm yet if you’re new to algorithms and programming in general, it may seem a bit daunting.

Summary

I asked six users of various technical ability to test The Lens Cap’s UX: its responsiveness, its legibility, its resolution, and whether they were able to find what they needed in search, etc. I asked them to tell me which devices they used and asked for suggestions on how to make the site better, what surprised them, good or bad, about the site, and also if anything frustrated them while using it.

Here are the results:

Extended Questions

What were some areas that frustrated you when using the site?

User 1: “I didn’t understand how to filter by type”.

User 2: n/a

User 3: “There is a lack of vertical rhythm, making the site too colourless isn’t pleasant, there are no boundaries on main elements, there is no visual guidance, and the carousel isn’t really a good idea in terms of displaying content. Calls to action weren’t clearly defined.”

User 4: “There is no content hierarchy; it’s important on e-commerce sites.”

User 5: “The content looks like a bit unstructured.”

User 6: “The search function kind of fades into the design and it took me a moment to figure out where it was.”

Suggestions

Do you have any specific suggestions to improve the site?

User 1: “Make the search easier to find and perhaps give instructions to the user on how to filter by type?”

User 2: “contact and pricing sections need more UI/UX work”

User 3: “Use semantic guides and visual guides. Take a look at the modular scale to improve font sizes. Take a look at the material colour collections. And work with defined (xs, sm, md, lg) sizes, so that responsiveness isn’t an issue.”

User 4: “Content hierarchy is paramount in a site like this one.”

User 5: “nono, overall i liked the site… it’s not a production site but works as a prototype.”

User 6: “contact and pricing sections need more UI/UX work”

Observations

Devices

Most people used a PC or Mac when accessing The Lens Cap, some of the users using more than one device. I could have improved the testing by asking the load times for each device and what kind of connection on each. As I started the test, I was expecting to have less technical users but it turned out most of my users were tech savvy; all but one was a developer/designer.

Site Speed

The site loaded fairly quickly— there were no load times over 2s. Even so, I’d like to make sure each load time on each device is under 2s. Studies suggest that users will bounce off a site if it loads in >2s. I’d like to get the load speed down and can do so with minification of JavaScript, adding scripts to the bottom of the page, and eliminating unnecessary libraries.

I could also optimize the images further or serve them over a CDN.

Resolution

The resolution of the site was consistent across devices, without any elements becoming blurry.

Attractiveness

Five out of the 6 users found the site appealing with 3 finding it very visually appealing. The lone user who said it was less than appealing found the layout, use of the carousel, and lack of vibrant colors a turn off. I fretted over the use of color a lot during this project. In the end, I went with my preference instead of what my users may want. The use of material color design, etc was something I thought about and while this user was in the minority, I know the conventional wisdom is to have more than just the neutral brown, gray, black, etc.

Element Speed

The carousel loaded the slowest out of all the elements. Half of users had the carousel load quickly, between 0-1s, 2 had the carousel load between 1-2s, and one user answered that the carousel loaded in a very slow 2-3s.

To reduce speed, I’d probably have to add less features to the script’s object. Though some of the elements of the carousel weren’t rendering, I left them in the main object. Slick.js carousel optimization was tricky for me on such great connections.

Search

Most people could not find the search because it was so laid into the design. The amount of users who could find things easily and those who couldn’t were scattered evenly along the continuum of “1” being very easy and “5”being very hard.

Making the search part of the menu could have helped this instead of using the search as part of the pricing page.

Fonts/Copy

The font choice, Lato, was the correct one, with all users being able to read the text. It wasn’t too small or to light. I feel the color could be darker in some areas for older eyes.

Conclusion

For my first site built with a template and then overhauled, it was a moderate success. I am not a designer, and I don’t want to be a designer, and so my knowledge of color and harmony are limited. I am willing to learn through places like Treehouse, Sitepoint, etc.

I have gained enough knowledge from this test to know where I need to improve.

Up until ES6, you couldn’t achieve true block scoping in JavaScript. With the var keyword, the scope in a code block could be accessed in the global scope, as variable declarations are hoisted to the top of scope and the assignments are kept where they are.

For instance, take this code:

functionfoo(a){varb=2;// some codefunctionbar(){// ...}// more codevarc=3;}

The function foo sits in the global scope. Inside the foo function, we have the function bar as well as some variable assignments with var b = 2 and var c - 3 sitting in foo. Each of these identifiers and functions have access to the scopes outside of them, clouding the global namespace. We call these function scopes and typically, they aren’t a good idea.

Examples of Hoisting

One of the reasons it isn’t great to use var when declaring variable assignments is because of hoisting which I mentioned above. An example:

Instead of getting a reference error here, when bar() is executed, the alert(foo) function has access to var foo = 10; in the conditional block. So when the JavaScript compiler goes looking for foo it finds it because foo is not scoped solely to the conditional block.

let

With ES6 1 you can create a block scope, or a scope that is contained within its own code block, by using let instead of var. For instance:

if(a){b=a*2;leta=5;}console.log(b);// Reference Error! a is not defined.

Here, the console.log(b); method call is looking for a but console.log can’t access a as it is scoped to the if block. This is a very simplistic example of block scoping with let.

const

const also creates block scoping. It allows for the value the indentifier holds to be quasi immutable. The data can be mutated as const is only really immutable because it binds the value of the indentifier and should only be used when you want the value you’re using to be non-reassignable.

You can make a const value immutable by adding object.freeze() method to it.

What Should You Use?

let improves scoping options in JS, not replaces. var is still a useful signal for variables that are used throughout the function. Having both, and using both, means scoping intent is clearer to understand and maintain and enforce. That’s a big win!