Ellatronic
Design Portfolio

Blog

JavaScript: Understanding the Weird Parts (Part 3)

Coercion

  • coercion - converting a value from one type to another
    • This happens quite often in JavaScript because it's dynamically typed.
    var a = 1 + 2;
    console.log(a); // 12
  • 1 is being coerced into '1' so the two strings can concatenate.

Comparison Operators

console.log(3 < 2 < 1);
console.log(false < 1); //coercion!! false to 0
console.log(0 < 1); //true
  • Avoid coercion by using strict equality ===.

Existence and Booleans

  • The Boolean of:
    • undefined is false
    • null is false
    • "" is false
var a; //initially set as undefined
            //goes to Internet and looks for a value
if (a) {
    console.log('something is there.');
}
  • a gets coerced, use a || a === 0 if a might be 0.
  • Since a is undefined (false), console.log will not happen.

Default Values

function greet(name) {
    console.log('Hello' + name);
}
greet();
  • JS doesn't care if there is no parameter, it uses undefined for name.
name = name || '<Your name here>'; //default value
  • || returns the value that can be coerced to true.
  • framework - a grouping of JS code that performs a task and is intended to be reusable

window.libraryName = window.libraryName || "Lib 2";

  • The above code checks to see if there is already a variable called libraryName; if not, it sets libraryName to "Lib 2".
JavaScript: Understanding the Weird Parts (Part 2)

Types and JavaScript

  • dynamic typing - you do not specify the data type of the variable to the JavaScript engine; it figures it out while the code is running
  • variables can hold different types of values because the types are determined during execution
  • static typing - specify what data type you intend to hold inside a variable

Primitive Types

  • six primitive types in JavaScript
  • primitive type - data type that represents a single value, aka not an object

    • an object is a collection of name/value pairs
  • undefined - represents a lack of existence. Do not set variables to undefined.

  • null - also represents a lack of existence. Use when you want to say something doesn't exist. Can set variables to null.
  • boolean - true or false
  • number - floating point number, essentially there is always a decimal attached to it. JavaScript only has one numeric type.
  • string - a sequence of characters, both ' and " can be used
  • symbol - new, used in ES6

Operators

  • operator - a special function that is syntactically (written) differently; generally takes two parameters and returns one result
    • infix notation: 3 + 4
    • prefix notation: + 3 4
    • postfix notation: 3 4 +
  • an operator is essentially a function call passing two parameters and returning a value

Operator Precedence and Associativity

  • operator precedence - which operator gets called first if there's more than one on the same line of executable code
  • associativity - what order operator functions get called in: left-to-right or right-to-left when functions have the same precedence
    • higher precedence gets called first, ex: multiplication before addition
var a = 3 + 4 *5;
         // 3 + 20;
         // 23;
         
var a = 2, b = 3, c =4;
  a = b = c; // same associativity
console.log(a); //4
console.log(b); //4
console.log(c); //4

='s associativity is right-to-left, so a = b sets b to c then a to b.

  • grouping with parens () - anything in the () gets executed first since grouping has the highest possible precedence (19).
JavaScript: Understanding the Weird Parts (Part 1)

I started my first Udemy.com course this week. I bought JavaScript: Understanding the Weird Parts since it came highly recommended on Newbie Coder Warehouse and it is an intermediate JavaScript course. I believe I am ready for that.

Conceptual Aside

  • syntax parsers - a program that reads your code and determines what it does and if the syntax (think grammar) is valid
    • When you write code, another program (compiler, interpreter written by someone else) converts your code into a set of instructions the computer can understand
    • This intermediate program that translates your code can also include extra stuff. This is an important element of understanding JavaScript.
  • execution contexts - a wrapper to help manage the code that is running
  • lexical environments - where something physically sits in the code you write; where the code is written and what surrounds it
    • lexical - having to do with words or grammar
    • In a programming language, the location where something is written is important.

Name/Value Pairs and Objects

  • name/value pair - a name which maps to a unique value
    • name may be defined more than once but can only have one value in any given contex
    • however, that value may be more name/value pairs
  • object - a collection of name/value pairs
Address: 
  {
    street: 'Main',
    number: 20,
    apartment: 
      {
        floor: 10,
        number: 1001,
      }
}

The Global Environment and the Global Object

  • whenever code is run in JavaScript, it is run inside and execution context
  • global execution context - the base execution context
    • global - accessible everywhere and to everything in your code; not inside a function
  • JS engine creates global execution context and 'this'
    • the window is the browser's global object
    • a separate tab is a separate window, each window is its own execution context

The Execution Context: Creation and 'Hoisting'

  • the execution context is created in two phases

  • Creation Phase

  • global object - 'this' - outer environment

  • set up memory space for variables and functions

  • "Hoisting" - not actually moving code to the top of the page

  • before your code is executed line by line, the JS engine has already set up memory space for the variables and functions you've created in your entire code
  • all variables are intitially set as undefined and functions sit in memory in their entirety
    • this is why it is a bad idea to rely on hoisting in any way

JavaScript and 'undefined'

  • "not defined" and "undefined" are not the same thing
    • undefined is a special value that means the variable has not been set
  • never set a variable to undefined
  • it is better to let undefined mean "I, the programmer, never set the value"
    • this will help with debugging

The Execution Context: Code Execution

  • code runs line by line
    • interpreting it, converting it, compiling it, executing it on the computer into something the computer can understand

Single Threaded, Synchronous Execution

  • single threaded - one command is being executed at a time
  • in the browser, JS may not be the only thing running but from a programmer's perspective, JS behaves in a single threaded manner
  • synchronous - one at a time and in order

Function Invocation and the Execution Stack

  • invocation - running a function, calling a function
    • in JS, using parenthesis ()
  • whenever you invoke a function, you create and execute that code
  • when the function is finished, the computer resumes the code where it left off

Functions, Context, and Variable Environments

  • variable environment - where the variables live and how they relate to each other in memory
function b() { //execution context b()
        var myVar; //myVar is undefined
}
    
function a () { //execution context a()
        var myVar = 2; //myVar = 2
        b();
}
    
var myVar = 1; // global execution context, myVar = 1
a();
  • myVar exists 3 times but each time is distinct and they do not touch each other

The Scope Chain

  • when we request or do something with a variable, JS does more than just look in the variable environment of the currently executing context
  • it also references variable's outer environment, this is the scope chain
  • b() and a() both reference the outer environment, global context
  • all sections of the above code are in the same lexical environment - the global environment
  • JS cares about the lexical environment when it comes to the outer reference that every execution context gets

Since all 3 pieces of code are in the same global lexical environment, when we call myVar in b(), we pull the global myVar since b() does not have a myVar.

Scope, ES6, and let

  • scope - where the variable can be accessed; where a variable is available in the code and if it's truly the same variable or a new copy
  • let - allows the JS engine to use block scoping; used or can be used instead of var
if (a > b) {
    let c = true;
}
  • during the execution phase, the variable is still placed in memory and set as undefined but the variable cannot be used until the line of code is run during the execution phase that actually declares that variable
  • using c before running let c = true; would produce an error
  • let is declared inside a block and is only available in that block at that period of time
  • block - curly braces {} running the code
    • if a loop has a let statement inside, a different variable will be produced in memory each time the loop is run
    • this concept allows for block scoping

Asynchronous Callbacks

  • asynchronous - more than one at a time
  • since JS is synchronous, how does it handle asynchronous events like click events and callbacks?
  • there are other engines running besides the JS engine when you load it in the browser
    • these include the rendering engine and the HTTP request
    • different engines can run asynchronously
    • code inside the JS engine can only run synchronously
  • event queue - stuff like click events get placed here
    • the event queue gets looked at by JS when the execution stack is empty
  • the browser is asynchronously putting things into the event queue but the JS code is still run line by line
This Week I Learned | Git Basics II, Github, Front End Optimization

Git Basics Part II

Cloning

  • The first step is cloning a repository to your computer
    • remote repository - a repo on another computer with access to it over a network
    • Remote can simply mean somewhere else

git clone ~/[name] [name_of_new_clone]

  • Cloning creates a copy of the repo without changing it in any way
  • Set up remotes to talk to each other by using:

git remote add our_clone ~/our_clone_project/

Pushing and Pulling

git pull origin new_feature

  • origin is the remote to pull from
  • new_feature is what branch we want to get the history from

git push our_clone

  • By default, Git asssumes pushing and pulling from the origin remote
    • Just use git push for default behavior
  • Since we are not pushing to the default, we must specify our clone

Github

  • pull request - what you do when you have code you want someone to pull into their project

Front End Optimization

  • Modification of HTML, CSS, JS, and sometimes server configuration for the purpose of improving page load times
  • performance budget - quantifiable target for how fast a website loads
    * Can be in the form of total HTTP requests, page weight, total response time, or any combination of these
    • page weight - total file size of all a site's assets

HTTP Requests

  • Pay attention to total number of HTTP requests on a web page
  • Even when no data is sent, like a 404 error, an HTTP request will still take up time
  • Each HTTP request is generally fast, but lots of little assets, including small ones like icons, can add up
  • sprite map - take small images like icons and put them together into one big image, then split it apart using HTML and CSS
    • Since a sprite map combines many small images into one big image, the result is one HTTP request instead of many
  • 404 errors indicate the server could not find the requested asset and are often caused by typos or file manipulations (files moved or deleted)

Optimize Images

  • Images use the most bandwidth
  • Use SVGs first - they are small in file size by covering large areas of the screen using just a few vector points rather than thousands or millions of individual pixels like JPEG or PNG
  • Resize/compress images
  • Using hosted services for assets like fonts is better for speed and reliability, additional parallel HTTP connections, and better caching
  • If possible, put JS on the bottom of the HTML page to make the page appear to load faster even though it might actually load in the same amount of time

Minify Assets

  • CSS and JS are often filled with spaces, line breaks, comments, and long variable names. A web browser does not need these to parse properly but they are still downloaded when a site visitor loads the page.
  • Minifying assets removes these extra bits and reduces overall page weight
This Week I Learned | Git Basics and JavaScript Basics

Git Basics

  • VCS - version control system
    • allows developers and designers to all work on the same code base
  • running git init without a name will create a repository in the folder you are currently working in
  • everything important about the repository is stored in the .git folder, so you can rename the folder holding your project files without causing any problems


git commit -a -m "message here"

-a adds all files. -m is the message flag.

The Staging Area

  • git status - shows us the current version control status of our project
  • git log to see past commits
  • check a version out using git checkout and the first 5-6 characters of the commit hash
    • get two commits and browse the differences between them

Branching Out

  • master is the default branch of any git repository
    • often thought of as the trunk
    • the version of code typically deployed in production
  • git branch [name] to create a new branch, use short and meaningful names
  • git checkout to switch branches
  • git checkout -b [name] to create and switch to a new branch
    • creating a new branch makes a copy of the branch you are currently in and uses it as a base for the new branch
  • git branch -D [name] to delete a branch

Merging

  • merging brings your branches back to master
  • makes a cohesive timeline of commits
  • merge conflict - happens when the same files have been changed in different branches
    • resolve the conflict by deciding which changes are most important to keep
  • in most cases, Git can and will automatically resolve merge conflicts for you
  • git checkout master to switch to master, then git marge [name_of_branch_to_merge]

Resolving Merge Conflicts

  • when automatic merging fails, you will need to resolve conflicts manually by
    • remove conflict markers to keep both sets of changes
    • delete one change
    • combine both changes
  • then git add [file] and git commit -m "message"

JavaScript Basics

  • string values are immutable - they cannot by altered once created. This means the individual characters of a string literal cannot be changed.

Cannot do:

var myStr = "Bob";
    myStr[0] = "J"; // -> "Job"

Can do:

var myStr = "Bob";
    myStr = "Job";

Can only change a string by completely replacing it.

  • if you assign a value to a variable that has not been declared (no var keyword), it will automatically become a global variable.
  • the lifetime of JavaScript variables begins when they are declared
    • local variables are deleted when the function is completed
    • global variables are deleted when you close the page

Global vs Local Scope in Functions

  • when both local and global variables have the same name, the local variable takes precedence
  • queue - an abstract data structure where items are kept in order
    • new items are added to the back of the queue
    • old items are taken off the front of the queue
Quick Update

      I did an update on the site. Now, there's a new Home page to better showcase the different parts of my site. I also decided to only maintain one blog (instead of both a personal and a professional one). Consistently writing for two was a larger workload than I wanted; consequently, I ended up writing for neither for a while.

A couple other items that were updated: