Javascript Functions, Closures, and the IIFE
June 29, 2018, 9:14 am

When writing code in Javascript or any programming language, one of the core concepts that a developer has to wrap their heads around is the function. If variables are values to be referred to at a later time, functions are whole sets of code to be referred to later.

Function

function myFunc() { // Do something }

You can also define a function as a value, or as an anonymous function. Normally functions are hoisted to the top of the code and run first, but an anonymous function is created inline with the rest of the code around it.

Anonymous Function

var myFunc = function() { // Do something }

There is value in both of these methods. It is important to know your options and explore their relevance. But there are even more options.

Sometimes it can be handy to define a function that defines it's own lexical scope. This allows local variables to be set up statically.

Closure

function foo(){ var id = 5; var bar = function() { console.log(id); } return bar; } var foobar = foo(); foobar();

This series of code has some very interesting implications for scope and how to create functions that have their own values. The id variable only exists inside the foo function, but the foo function returns the bar function as a value, and since the bar function was made inside foo, and after id, it also has access to the id value. Closures allow you to segregate your values and give unique scope to parts of your project. This becomes especially useful when you want to write code for libraries and larger repositories.

Immediately Invoked Function Expression

(function() { // Do something })()

Then there is this beast. A function with no name. No real declaration, but put inside of an expression syntax that fires it off immediately. What is the point? Why wouldn't the do something code simply be code, why does it need to be wrapped up like this?

Well, defining a function anonymously allows it to be passed around by value in a much more flippant manner. Most often anonymous functions are used for callback reasons. However, if it tries to access values that were created outside of it's scope it accesses them dynamically at their current value. This can be an unwanted effect, that is most often run into when defining a callback function inside of a loop.

If you make 3 buttons dynamically in a loop, and have them each print out the iterator value on click, all of them will print out the last value, because at the time of clicking, the iterator would have only its final value.

for(let i=0;i<3;i++){ $("body").append($("< button>").click(function() { console.log(i); })); }

This exact situation is when an anonymous function called immediately to provide closure to its scope is most effective. But it gets more complicated. Any method that is expecting a function to be passed into it must receive a function. And a closure that returns a function as a value is a goofy thing to look at.

Anonymous Closure Callback Immediately Invoked Function Expression

var i = 5; $("button").click( (function(id) { return function() { console.log(id); } })(i) ); i = 10;

Now, that's just weird to look at your first time. It will start to make sense the more you end up using it. The IIFE is being passed a variable in order to give closure to it's current value. The i variable gets passed in at the end of the closure, and then is referred to on the inside as id. This means that no matter what might happen to i in the future, when the click happens, the value of i has been stuck into the static value of 5 in id.

[edit] So um... turns out that loop example doesn't produce the result I said it would which means.... That's not actually a problem when you use the let declaration, instead of the var. But the final example still matters.

Don't hold onto hate
May 30, 2018, 5:48 pm

Today has been a disheartening day for me. The amount of people I've seen defend racism is staggering. But the worst is the casual ambivalence toward what people are referring to as "only a little racist" or "just racist that one time". As if that's how it works. I don't know what to do with this information, but I know that I compiled the data from numerous sources.

I'm not sure I'll ever have the answers. Maybe no one ever will. But I like to think I can at least see the forest when it comes to this kind of thing.

Keep examining yourself, folks. Cut out hate where you find it. Latch onto love if you can. I'm not talking about backing off of your principles. I'm not saying be a pushover. I'm saying choose to be kind rather than mean. Truly mean. You can be playful. Don't be cruel. Don't hold that in your heart.

Tags: self, journal

I finally found a reason to curry
April 25, 2018, 6:43 pm

Currying functions is not necessarily a hard concept to understand. It goes like this: You make a function that returns a function for something else to call as a function.

...

Hold on. Let me give you an example.

var a = function(num1) { return function(num2) { return num1 + num2; } } var b = a(3); var c = b(3); // output 6;

But here's the thing. That example really makes no sense. What's going on here? And why would I do this?

Well first of all, you wouldn't. That's a too simplistic bad example. I can see you saying "I would just make one function with two parameters" and you would be right of course. That's a much better use for that example.

But what if you needed a kind of a function that needed to do some things, and prepare some things, and then have a unique kitchen table prepared for a meal to be prepared again and again in the future?

What if you needed a table command that prepared a particular kind of bread. And then anyone could come along to the table they liked and make sandwiches out of the bread at that table. Sandwiches always get made the same way, but the bread needs to be prepared first.

var makeBread = function(breadtype){ return function(jamType,pbType) { return `${pbType} and ${jamType} on ${breadtype}`; } } var wheatSandwich = makeBread("wheat"); var sandwich1 = wheatSandwich("jelly","creamy pb"); var sandwich2 = wheatSandwich("marmalade","crunchy pb");

So now we don't have to define wheat anymore. It's part of the function. But using the original makeBread sandwich we could still define another style of sandwich if we wanted to.

I recently found currying useful while working on my drawtools library. Currying a tool for loading images into a canvas allows me to set up a function that caches a particular image into it's own memory to then draw onto a canvas.

Rapid Transit, a book coming soon
March 19, 2018, 10:14 pm

On March 26th I have a new book coming out.

A while ago, my friend and colleague Ryan approached me with an idea for a book of my drawings. I didn't originally want to relinquish control of my drawings to someone else to do something with them, but eventually I realized that I wasn't making a book any time soon, so someone else might as well.

People have been calling me the Bartist for a while now, and this book will be a collection of quite a few of my BART drawings from over the last few years. There are over 300 drawings and quotes and stories and ideas represented in this 200 page book. We really tried to do something fun with this book, and we're so excited about it.

You can go to the Rapid Transit Book site to sign up for a mailing list and to get more info as it becomes available.

BARTist
February 7, 2018, 9:30 am

Draw every day. Practice every day. Practice like you mean it.

Love this video portrait, made by my student Yingzi Zhang. Funny story, we shot footage for about an hour for this 2 minute video. If you ever want to fall asleep, just get me talking about a subject, and I'll keep going.

A Bitcoin and Crypto Primer: Part 2
January 8, 2018, 8:51 am

Read Part 1

So you have a vague idea of what Bitcoin and other Cryptocurrencies are. So now you want to buy some, but how?

What is an exchange?

Exchanges are the place to go to do one of two things. You can either place an order into or out of your fiat currency (government issued currencies), or you can trade cryptos between each other. Exchanges are the stock market of crypto.

Whereas Cryptocurrency creation and use is unregulated in the best way, exchanges are unregulated in the worst way. The exchanges are where trades happen, prices change, and the incredible volatility of Bitcoin is birthed. I'm sure that you've read or heard that Bitcoin is a volatile, speculative, market. And you're right, but not because of bitcoin itself. It is because on the crypto exchanges, the price is always moving. Because there is no regulation for these exchanges, sometimes big players can come in and splash the pot around, and sometimes a million average joes come in and make weird moves.

But exchanges are also the only way to move from currency to currency at the moment. So they are a necessary evil. Anyone can become a miner, and begin to slowly accrue a small amount of many coins. But for most people, the way to get in to crypto is to buy on an exchange.

What exchange should I use?

This question largely deals with personal need, personal use, and availability. There are quite a number of exchanges out there. There are whole sites dedicated to just listing exchanges. But generally, you might want to do those two main things, move fiat in and out, or exchange between cryptos. Actually, you'll probably find those two tasks happen on different exchanges.

Fair warning, many of the upcoming links are referral links. Sign up for what you want, and don't just take my word for it. Honestly, it's so hard to give suggestions to people without feeling a tiny bit responsible for their money. I'm honestly just trying to help, and if you sign up with these links, you help me back.

CoinBase.com is a major US exchange for USD to crypto. It has an easy interface, a nice design, and you can exchange USD for a few common cryptos. A couple things to know about this market; it takes about a week for any USD transfer to finalize on the exchange, so don't be surprised when you can't make any other moves for a while. Just hold tight and wait it out. Gdax.com is the more proper exchange for those coins, once you've purchased some from CoinBase. They are two sides of the same company.

Binance.com is a Chinese based exchange that is one of the most popular for trading a large amount of different cryptocurrencies between each other. As of this writing, Binance has limited new signups to random times throughout the day. Binance has a very good App on both iOS and Android, although because of the a number of things, you have to download their app directly and allow it as a trusted developer. It's up to you to make or not make this decision, but understand that a little trust is the price to pay for getting into these unregulated markets.

Kucoin.com is an exchange that looks nearly identically skinned from binance on their website, but their app is different in a number of ways and this exchange has different coins available.

Cryptopia.co.nz is a very large exchange with a huge amount of coins for trading, but they don't have a mobile app, and they are quite complicated as a starting point.

Gemini.com is another option for fiat conversion, but they can be quite slow in their approval process.

Which Crypto Coins should I buy?

I mean, this is definitely not a question with a good answer. Most people's first intro to this space is the coinbase interface, and upon opening that app, you'll be greeted, currently, by four different coins. Bitcoin, Bcash, Ethereum, and Litecoin. Which coin you want to buy is entirely up to you. Most investors would say that the key to long term success is diversification. So perhaps a small amount into each, or a couple, would be a good place to start.

Do I have to buy a whole Bitcoin?

Not at all. Bitcoins, and other cryptocurrencies can be broken down into smaller increments, just like dollars can be broken into cents. 1.0 BTC is one Bitcoin. 0.0001 BTC is one Bit. 0.00000001 BTC is known as one Satoshi. That's four and eight digits to the right of the decimal place.

Now some exchanges do require a minimum amount of exchange between any particular currency, often times equaling out to at least 10 USD worth. But you don't have to spend 15,000 USD to get into cryptocurrency. You can spend 100 USD to purchase about 0.006 BTC. You don't have to purchase in terms of whole coins, you can purchase in terms of initial investment.


To be continued....

Part 1

If you would like to tip me some Bitcoins, you can use this address.

1N37odPafRyrKRnKxEsPLFqiEgtoPbxE4S

A Bitcoin and Crypto Primer: Part 1
January 6, 2018, 10:11 am

So. Last year around this time, I went nuts for 3D Printing. I mean I bought and constructed about seven 3D Printers. I love it, and I learned a lot.

This year I've gone full bore into Cryptocurrency, and I would like to impart some knowledge onto anyone who reads this.

First off, let's get one thing straight. You may call them all bitcoins if you want, but there are a number of cryptocurrencies now, and you don't want to be your grandma calling all game systems Nintendos. Bitcoin is one of and the first cryptocurrency. It is also currently the most expensive of the cryptos. But what is its worth?

What is Bitcoin worth?

This is perhaps the most wrong question new people ask. As of this writing BTC (the identifier for bitcoins) are worth different things in a lot of different places. Bitcoin is a pure currency, like dollars. What are dollars worth? Nothing. That bill that you hold is worth nothing, except what someone is willing to trade it for. It's not worth anything in gold, or anything else, inherently.

Dollars don't have a value in gold. Dollars are worth nothing. Gold is worth something in Dollars, not the other way around. Dollars are worth nothing except your own trust in a system.

So what are Bitcoins and other Cryptocurrencies worth? Bitcoin can be given a worth in Dollars, because it can be traded into dollars, but it can also be given a worth in apples, a worth in Ethereum, a worth in Euro, and a worth in drugs. It is a currency in the purest sense. The difference is that although your Dollar responds only to your trust in the system, Bitcoin is built around a technology called the Blockchain.

What is the Blockchain?

The blockchain is a digital, decentralized ledger of every Bitcoin transaction that has ever occured. So imagine that you were a bank, and you wanted to accept a check. You would need to talk to the new bank and make sure that that check actually came from the other bank, that it actually belonged to that customer, and that there was actually a worth denoted by the check. At that point, that worth could transfer from one bank to the other.

Now imagine that instead of needing to communicate with a bank, you could just pull 6 random people off the street and tell them you wanted to move money to a new location. What if everyone was their own bank all hooked into the same ledger. Imagine that you would say you wanted to move money somewhere, and everyone knew the original location. If 6 people all were checking around the ledger that day, and they all confirmed that the money from the original location was legit, then the money would go through, and everyone's ledger would update with value in a new location.

That is an overly simplified description of the blockchain, but it's good enough for these purposes. The blockchain is a virtual decentralized guarantee that the amount of currency you say you're transferring came from somewhere and is the amount you said it was.

So how does Bitcoin mining work?

Not all cryptocurrencies are based on the same technology, and some of them have utility beyond their worth as a currency. Bitcoin mining is the way that the ledger is proved. Anyone can become a miner and it serves two purposes.

One, when Bitcoin was first proposed, in order to not allow anyone to be able to fully control it, not all of the coins were produced at once. Coins can be mined by solving complex mathematical problems. As these problems are solved, new coins are unearthed at certain stages. Everyone mining improves the distance for everyone else toward the next coin, but only the last person gets the coin. Everyone chips away at a gold mine, until only one person gets the nugget. This system actually encourages miners to pool their resources and then share the spoils if a coin is unearthed.

Two, as miners mine, they also are the ones proving transactions. When bitcoin transactions are occuring they get passed to miners for approval before being confirmed in the core ledger. Every transaction also incurs a small fee, and these fees are then passed on to the miners to encourage the act of mining beyond the possibility of finding whole Bitcoins, and indeed the time after all Bitcoins have been mined.

How many Cryptocurrencies are there?

Lots. Hundreds, bordering on thousands.

So isn't that bad? Sort of. Not really. Think about it this way, most countries have their own currency. Wouldn't it be better if all countries, indeed all peoples, used the same currency? Possibly, but that's not happening. Although any country can issue its own currency, it doesn't mean anyone will use it.

Likewise, although anyone can create a currency based on a doge, it doesn't mean anyone will use it for anything other than collecting and trading. These days there are not just different Cryptocurrencies, but there are even different underlying technologies. Many of these currencies are based on what's called a fork of the original Bitcoin documentation. They took what Bitcoin was, and made their own version. Some of them even took the same ledger as Bitcoin at the time, and gave everyone who had some Bitcoin some of their new altcoin.


Part 2

If you would like to tip me some Bitcoins, you can use this address.

1N37odPafRyrKRnKxEsPLFqiEgtoPbxE4S

The Landscape Ahead
January 4, 2018, 8:34 am

What seems like ages ago, one of my first crypto purchases was litecoin. I liked litecoin, and I liked that it was cheap.

When I started trading coins, litecoin was the first one I traded, cuz it was a pawn. It was the nuthin coin. I traded like 1 whole litecoin for like a million of a coin called TRX. An even trashier coin. Because, in my mind, I wanted to have a lot of a coin. It was worth 17 SAT at the time, or in other words 0.00000017 of a bitcoin. It was worth nothing, but that's why I bought it. I just wanted a lot of coins. I wanted to jingle some pennies.

TRX just passed litecoin in marketcap today. That's insane. We used to use the term big 3 to refer to Bitcoin, Ethereum, and Litecoin. But I'm not certain we can use those terms anymore. The whole landscape of crypto has drastically changed in the last 2 weeks, much less the last two months.

TRX has a lot of coins in circulation. Way more than BTC. This means it's worth can only go so high. But it's market cap actually still has quite a ways to go. I'm on the ride though. On this trash coin that I thought would go no where. It might go all the way.

Gambling is taboo because people suck at it
November 28, 2017, 9:08 am

Ok, let's talk about the difference between gambling for fun, gambling for profit, and gambling with your life.

Gambling for fun is something most people can do. Hell you probably do it every time you play a video game. Gambling concepts, strategies, and triggers are all over the video game world. The new Battlefront Star Wars game is coming under heavy fire for having a gambling system in place that uses real money. I think the key to gambling for fun involves a few things.

1. Gamble with gains. Never gamble at the bottom of your worth if you want to have fun gambling.

2. Set yourself a goal, and cut out your goal from your gambles, if you've managed to win. You'll walk away with something, and you still had fun.

3. Always consider your gamble to be money spent. This is the problem a lot of gamblers can't get their head into, and they psych themselves out. "I'm up 5 since last hour." No, you're down 20 for the day.

Now gambling for profit is a different beast. It is 100% possible to gamble for profit, and not have a problem. BUT, whereas all the previous rules still apply, there's an amount of strategy and higher buy in that SHOULD discourage the average joe from thinking they can attempt it. gambling for profit involves a full understanding of the rules, the odds, and a complete separation of the personal need for any one amount of money.

I think this is where gambling with your life comes in, is when people can't see those road stops in the concept of gambling. They see people gambling with high amounts, and they think that's what gambling is. They see people making moves, and they think it's JUST guessing. They see people winning lots of money, but they don't see the losses the next day.

When I used to go to the casino I would leave my wallet in the car. I would bring in 50 dollars, and I considered it payment for the amusement park ride. If I got up above 100, 50 would go in one pocket, and I would only gamble with the other pocket. And most days I would walk away with nothing. But more often I walked away with 50. And some days I walked away with more. But I always had fun. I think it is possible to gamble and have fun. I think one has to keep their head about them in order to do it. But I think it's possible.

The Elements of Euclid
October 3, 2017, 8:53 am

I bought a book on a whim while at the book store.

The Taschen books on art and history are really fascinating to me, and last night I picked up The Elements of Euclid from Green Apple on the strength of its interior alone. Lately I have been doing a lot of work with geometry and trigonometry and this book speaks to me in a very real way.

If you have ever been interested in math, geometry, or even design, this book will be an amazing addition to your repertoire.