Synchronous vs Asynchronous functions
- xmlhttp.send ($.ajax / $.get / $.post in jQuery)
Lets take a look at two quick examples to see why how syncrhonysity effects code execution.
Why does it matter
Angular uses a technique called “dirty checking” to determine when data has updated. However, dirty checking only works if code executes in a single thread. As soon as you start a new thread, dirty checking becomes unpredictable.
How do we use asynchronous functions with Angular? The short answer is that angular provides alternatives which allow dirty checking to work even for asyncrhnous functions. Those alternatives are
The long answer requires a deeper understanding of how angular works, so we’ll ignore it for now.
We called a
toString function which returns a string version of the object, however we did not define any
toString function. So who defined this function and how are we able to access it?
We are able to call
toString because it exists on the Object prototype. Each object you create inherits all the properties of the Object prototype. If you’re using chrome’s inspector can take a peek at the prototype of any object (or primitive such as number or string) by looking at the
__proto__ property and letting chrome autosuggest the properties for you. First lets create some test variables so we can check their prototype:
The object prototype
The string prototype
The number prototype
Why does it matter
Sometimes you need to pass a function as an argument. Here are some examples of times where we pass a function as an argument
When we pass a function as a argument, our function might expect arguments that it needs to interact with.
forEach is an example of that - it gets passed
index as arguments. However, these arguments need to be declared in the correct order. For example the following two
forEach functions below will do different things, just because the names of the arguments are switched.
Wouldn’t it be nice if the order of our arguments didn’t matter? If a function uses named parameters - then it doesn’t. All that matters is that the name of the argument is correct.
Let’s assume there is an function
namedForEach which gets passed a function we define and utilizes named parameters. In this case,
namedForEach will log the same text in both of the following functions, even though the parameters are switched.
If we only wanted one of the arguments we could simply list the argument we need and ignore the other.
Why it matters
Angular utilizes a concept called “dependency injection” to make our code more elegant. Imagine we have a function that requires a number of different libraries to work. We could pass those libraries as arguments to the function, but then we’d need to manage the logic of which functions need which variables. Named parameters rids us of this overhead - we simply list the libraries we need as arguiments.