Wanna see something cool? Check out Angular Spotify 🎧

JavaScript: Understanding the Weird Parts Notes

These are my notes from a Udemy course - JavaScript: Understanding the Weird Parts that I took about a years ago. Back then, I had a shallow understanding of how JavaScript worked. I only knew the basics:

  • var x to create a variable
  • How to write a function. Most beginners did not even know the difference between function declaration and function expression.
  • How to invoke a callback for asynchronous operations such as HTTP calls.
  • How to work with objects - {}
  • How to work with arrays and some basic manipulation - []
  • Some jQuery for DOM manipulation. Working with jQuery taught me useful patterns like the module pattern and the revealing module pattern, which led me to learn about Immediately Invoked Function Expressions (IIFE).

With just this basic knowledge and no deep understanding of JavaScript, I managed to build a mobile app on my own. It was live for years with many active users. Not my best work, but it gave me a real chance to work with AngularJS on something more meaningful than a simple Todo app.

Over time, I felt the need to learn JavaScript properly. That is why I started this course. It was genuinely helpful in shaping how I think about the language, and the foundation still holds up today.

Syntax Parser

A program that reads your code and determines what it does and if its grammar is valid.

  • The compiler translates the entire program before it is run.
  • The interpreters translate a line at a time while the program is being run.

Lexical Environment

In programming languages, where you write something matters. The location of code and what surrounds it affects how it behaves.

Execution Context

A wrapper to help manage the code that is running. There are lots of lexical environments. Which one is currently running is managed via execution contexts.

Single Threaded, Synchronous Execution

One command at a time, in order. Under the hood of the browser, maybe not.

Synchronous vs Asynchronous

Synchronous One at a time and in order that it appeared
Asynchronous More than one at a time.

Invocation

Running a function in JS by using parentheses ().

Variable Environment

Where the variable lives and how variables relate to each other in memory -> scope.

Execution Stack and Event Queue

Dynamic Typing

You do not tell the engine what type of data a variable holds. It figures it out while your code is running.

Primitive type

A type of data that represents a single value, not an object. They are case-sensitive.

  • Undefined: represents a lack of existence
  • Null
  • Boolean: true or false
  • Number: floating-point number (there are always some decimals)
  • String: a sequence of characters (both ” and "" can use)
  • Symbol

Operator

A special function that is written differently. Generally, it takes two parameters and returns one result. For example, the + operator: +(3, 4) = 3 + 4.

  • Operator Precedence: which operator function gets called first. If there is more than one operator, the one with the highest precedence runs first.

  • Associativity: the order operator functions get called in (left-to-right or right-to-left) when they have the same precedence.

let sum = 3 + 4 * 5
let a = 2,
  b = 3,
  c = 4

a = b = c = 4
//1. b = c <=> b = 4
//2. a = 4
//3. return 4

Type of Operator

  • Arithmetic Operator: + - * / ++ --
  • Comparison Operator: Not equal to (!=)
  • Logical Operator: &&, ||, !
  • String Operator: takes two strings as operands and creates a new string
  • Ternary Operator: let status = (age >= 18) ? 'adult' : 'minor'

Coercion

Converting a value from one type to another.

var a = 1 + '2' //'12'
let x = undefined || 'hello' //'hello' => return the first one that can be coerced to true

Statement

Performs an action. Loops and if statements are examples of statements.

Expression

A unit of code that results in a value. It does not have to be saved to a variable.

this

Invoking the function

this is assigned to window, even when sitting inside a function. The short version: a function invocation like fn(...args) is the same as fn.call(window [ES5-strict: undefined], ...args).

Invoking the method inside the object

this will be the object.

// But caution if you reference the method of obj without calling it
var obj = {
  fn1: function() {
    alert(this)
    //inner function
    var x = () => {
      //closure
      alert(this)
      return this
    }
    return x
  },
  fn2: function() {
    alert(this)
  },
}
let f1 = obj.fn1()
f1() //this === obj
let f2 = obj.fn2
f2() //this === window

Arguments

The parameters you pass to a function

Immediately Invoked Function Expressions (IIFE)

//function declaration
function greet(name) {
  console.log('Hello ' + name)
}

//function expression
var greetFunc = function(name) {
  console.log('Hello ' + name)
}

//immediately invoked function expression
var greetFunc = (function(name) {
  console.log('Hello ' + name)
})('John')

//create function and run it
;(function(name) {
  return 'Hello ' + name
})('World')

Closure

A function retains access to variables in its outer scope, regardless of whether the outer function has finished running.

function greet(hello) {
  return function(name) {
    console.log(hello + ' ' + name)
  }
}

var sayHi = greet('Hi')
sayHi('Trung')

Bind, apply, call

Bind Create a copy of function with different this variable
Apply, call Call attaches this into function and executes the function immediately
var person = {
  firstName: 'John',
  lastName: 'Doe',
  getFullName: function() {
    return this.firstName + ' ' + this.lastName
  },
}

var logName = function(lang) {
  console.log('Logged ' + this.getFullName())
}.bind(person)

var logPersonName = logName.bind(person)
logPersonName() //bind
logName.call(person, 'en') //call
logName
  .apply(person, ['en'])(
    //apply

    function(lang) {
      console.log('Logged ' + this.getFullName())
    }
  )
  .apply(person)

var person2 = {
  firstName: 'Trung',
  lastName: 'Tuan',
}

Reflection

An object can look at itself, listing and changing its properties and methods.

Function Constructor

A normal function that is used to construct objects. The this variable points to a new empty object, and that object is returned from the function automatically.

For methods, you only need one copy, so add them to the prototype.

Published 10 Apr 2015

Read more

 — Spinning button onSubmit form with jQuery and ASP.NET MVC
 — JavaScript naming convention
 — Shrinking Navigation Bar When Scrolling Down - Bootstrap 3 Navigation & jQuery
 — ES6 in my daily life
 — My new blog