Closures in JS

I’m having a lot of trouble understanding how to use closures in JavaScript. A closure seems to be just a function within a function. I am still trying to find more examples of closures and their usage, so feel free to share any good ones you come across.

In the meantime, I found this Stack Overflow explanation pretty good:
http://stackoverflow.com/questions/111102/how-do-javascript-closures-work

 

Also finally found out what to call the ‘=>’ operator:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Advertisements

FCC – Twitch TV Project

Finally finished this project! I started this project during a pair programming session before the holidays and then just got busy and never finished it.

This project required using Twitch.tv’s API. Working with API’s is always challenging, especially if the API is not well documented. Twitch’s API has a lot of documentation and there’s tons of information on how to get it to work in the FCC forums: https://forum.freecodecamp.com/t/how-to-use-the-twitchtv-api/19541. (This link is also included in the project bullet-points.)

The first step was reading the forum and getting the correct API URL.
Using this: https://wind-bow.gomix.me/ as the starting point.

After getting that URL, it became time to read the Twitch.tv API documentation to see how to get the information we want. I focused on a list showing my favorite channels, but you could also have focused on users or videos. Twitch documentation here: https://github.com/justintv/Twitch-API

Endpoint Description
GET /streams/:channel/ Get stream object
GET /streams Get stream object
GET /streams/featured Get a list of featured streams
GET /streams/summary Get a summary of streams
GET /streams/followed Get a list of streams user is following

The URL I used to make the API call became: https://wind-bow.gomix.me/twitch-api/streams/' + channelNames[i] with channel name being taken from an array of my favorite channels in a for loop

Once I got the URL down, I decided to build the front-end, just a basic skeleton of the page, and then focus on the JS. Wanting to use pure JavaScript, there was ALOT I had to learn. I read about making XMLHttpRequests to the API and how to handle the request response. I also read about jQuery’s .prepend() and .append() functions and how to translate their properties into JavaScript.

You can find my finished code here: https://github.com/sunsplat/fcc_twitch

Designing this project was super fun! I played around with Google’s Material Design by using Material Design Lite.

You just insert these links into the of your HTML and you have access to the classes and icons:

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.3.0/material.min.js">script>

To access the icons, go here: https://material.io/icons/

To read more about the purpose and Do’s and Don’t’s of each component in Material Design go here: https://material.io/guidelines/material-design/introduction.html

View my final project here: https://sunsplat.github.io/fcc_twitch/

JavaScript Resources

So I’ve begun the dive into learning the JavaScript MEAN stack after becoming confident in writing vanilla JS. I have found some great resources recently and wanted to share:

This is by far my favorite resource for learning Express and NodeJS:
http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/

The guy breaks down and explains every line of code so that you have a better understanding of what it’s doing.

He also has a Part 2 that incorporates MongoDB: http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/

Trello Board of Resources for learning Front-End and Git. I mainly look at the boards under React:
https://trello.com/b/EbwlbqRR/resources

A great and easy way to develop responsive sites:
http://susy.oddbird.net

A great way to learn JS by playing a game: https://codecombat.com
Free Code Camp has a clan you can join: https://codecombat.com/clans/5835e3b200a02f2400786712

 

Code4Startup- ReactJS for Newbies

This is a great tutorial for people new to React and looking for a simple and easy to understand introduction: https://code4startup.com/projects/reactjs-for-newbies

Several things to note about this tutorial:

  1. Grabbing the CDN links off the React website will not work with this tutorial. You must use the versions that Leo uses:
      <!-- The core React library -->
      http://fb.me/react-0.14.7.js
      <!-- The ReactDOM Library -->
      http://fb.me/react-dom-0.14.7.js
  2. If you want to use Codepen to store the code, you must select Babel in the Settings as the JavaScript Preprocessor. Add the External JavaScript links in #1 and you’ll be all set!

My Pen:

Install MongoDB on Windows 10

To install MongoDB on your Windows 10 machine, follow the following steps.

  1. Go to MongoDB website and download the Community version of the package like you see in the image below:
    unnamed-qq-screenshot20160925205425
  2. Once the download finishes, double click on the .msi file to start the installation. Install using the default settings, installing Complete package.
  3. Once installation completes, we need to add MongoDB to the Path in System Variables so that you can use the MongoDB commands in the command prompt. Right click on the Windows icon (the very left icon) on the taskbar and click on ‘System’.
  4. Click on Advanced System Settings on the left hand side and then when the window pops up, click on the Advanced tab and find Environment Variables…unnamed-qq-screenshot20160925205921
  5. Under the System Variables, double click on Path to add a new path for MongoDB:unnamed-qq-screenshot20160925210218
    You can also click on ‘New…’ button to add a new variable.
  6. Once the new window opens, add a new path for MongoDB according to your download path. If you used the default install settings, your install path for MongoDB should be similar to this:
    unnamed-qq-screenshot20160925210240
    3.2 is the version number, so just double check what your version number is before adding it in. Then click OK to save the changes.
  7. Then open your command prompt and type:
    $ mkdir C:\data\db\
    This is where all your database collection information is stored. NOT where your actual database for your app is stored.
  8. Now to connect your path to this directory, type this in the command prompt:
    $ mongod --dbpath <path where you want your database for your app stored>
    For example:
    $ mongod --dbpath C:\Users\Ellen\myfirstapp\contacts

  9. To check if your MongoDB is set up correctly, you can always run
    $ mongod
    You’ll get a response like the following:
    unnamed-qq-screenshot20160925211256

    Source: https://code.msdn.microsoft.com/Mongo-Database-setup-on-6963f46f

Passing a PHP Array through AJAX

If you are creating dynamic elements on your page, you will need to be able to send information to and from the browser. There’s lots of documentation on how to POST data using AJAX to the server side. What if you want to return an array of data back to the browser?

$.ajax({
    url: "<?php echo site_url('test/urlGoesHere/'); ?>",
    type: 'POST',
    data: form_data,
    dataType:"json",
    success: function(data) {
        alert(data[0]);
   }

Marking the dataType as json here is key.

In your PHP file, use json_encode to send your array:

print json_encode($my_array);

If you don’t want to save the array into a variable, you can also just write the array between the json_encode parantheses:

print json_encode(array("name"=>$name,"title"=>"Ms."));

Then in your AJAX success, you can access the array elements this way:

data.name[0]; //the first name element
data.title;  // "Ms."
data[0];

If this was your array: array("Jack", "Mr."), then your AJAX data can be handled like this:

$.ajax({
    url: "",
    type: 'POST',
    data: form_data,
    dataType:"json",
    success: function(data) {
        var name = data[0];
        var title = data[1];
        alert('Name: ' + name + ', Title: ' + title);
   }

Looping Through JavaScript Associative Array

Create your array so that it follows the following format:

var weekdays = {"MON" : "monday", "TUES" : "tuesday", "WED": "wednesday", "THURS" : "thursday", "FRI" : "friday"};

*Note the use of curly braces instead of square brackets and also the colon instead of =>

Then to loop through this associative array:

for (var day in weekdays) {
  document.write( day + " : " + weekdays[day] + "<br />" );
}

Here, the variable ‘day’ represents each individual key in the array ‘weekdays’. The loop will run through each key and stop after the last one is completed.

Your output:

KEY : value

MON : monday
TUES : tuesday
WED : wednesday
THURS : thursday
FRI: friday

Show the Local Weather – Part 2

Read Part 1 here. Part 1 covers how to get a user’s geolocation to dynamically generate the weather according to the user’s location.

Part 2 is about using the user’s location to get the local weather forecast.

I used OpenWeatherMap‘s API to get the weather information. You’ll need to sign up (it’s free!) and get an API key: http://openweathermap.org/appid

  1. Sign up and get an API key from OpenWeatherMap.
  2. This is an example of the URL (API call) you will use to get weather info:
    http://api.openweathermap.org/data/2.5/weather?lat=33.7708&lon=-84.2931&units=imperial&APPID={APIKEY}

    This is the URL to OpenWeatherMap API:

    http://api.openweathermap.org/data/2.5/weather?

    You can use a city name, city ID, or longitude & latitude coordinates. I decided to use the longitude and latitude for more accurate weather.

    This is where you put the latitude and longitude coordinates.

    lat=11.111&lon=-11.111

    The longitude and latitude coordinates were derived from Part 1:

    {"ip":"8.8.8.8",
    "country_code":"US",
    "country_name":"United States",
    "region_code":"NY",
    "region_name":"New York",
    "city":"New York City",
    "zip_code":"10128",
    "time_zone":"America/New_York",
    "latitude":40.7142700,
    "longitude":-74.0059700,}

    You can also toggle Celsius and Fahrenheit with

    &units=

    Celsius: units=metric
    Fahrenheit: units=imperial

    Read more here.

    In place of {APIKEY} paste your OpenWeatherApp API key. You can find your key when you log into your account and go to the API Keys tab.

  3. Test your API call with Postman by placing the full URL ( http://…APPID=&#8230;..) in as a GET request. You should get a response similar to something like this:
    {"coord":{"lon":139,"lat":35},
    "sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},
    "weather":[{"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}],
    "main":{"temp":289.5,"humidity":89,"pressure":1013,"temp_min":287.04,"temp_max":292.04},
    "wind":{"speed":7.31,"deg":187.002},
    "rain":{"3h":0},
    "clouds":{"all":92},
    "dt":1369824698,
    "id":1851632,
    "name":"Shuzenji",
    "cod":200}

    Play around with different locations and when it is successful, you can go to the next step!

  4. Start writing your JavaScript function! We need to create an AJAX call to get the data returned from the API and store it in our own variables so we can use the information. I used the jQuery .ajax function.
    function getWeather(url) {
    	$.ajax({
    		url : url,
    		dataType : "json",
    		success : function(data) {		
    			var temp = data['main']['temp'];
    			var image = data['weather'][0]['icon'];
    			var desc = data['weather'][0]['description'];
    			var humidity = data['main']['humidity'];
    			var rain = data['weather'][0]['main'];
                            var sunset = new Date((data['sys']['sunset'])*1000);
                            sunset = sunset.toString().slice(16,21);
                            document.getElementById('image').src="http://openweathermap.org/img/w/" + image + ".png";
    			$('#temp').html(temp);
    			$('#desc').html(desc);
    			$('#wind').html(rain);
                            $('#sunset').html(sunset);
                            $('#humidity').html(humidity + "%");
    		}
    	});
    }

    The sunset variable is storing the sunset UNIX number and converting it to a readable format according to the user’s timezone.

    I am passing in the parameter to getWeather the URL saved as Weather in Part 1. It’s the URL you use to make the weather API call.

To load OpenWeatherMap’s weather icons, use this img source format:

http://openweathermap.org/img/w/" + image + ".png";

Where:

var image = data['weather'][0]['icon'];

Final Product: http://sunsplat.github.io/fcc_weather/index.html

Source for how to get the weather icons here: https://openweathermap.desk.com/customer/portal/questions/13287488-weather-icon-id

Another weather API you can use: forecast.io

Random Quote Machine

Today I completed the FreeCodeCamp Zipline: Build a Random Quote Machine!

It took me about two hours, plus an hour of styling to get something that I liked.

This is what the completed machine looks like:

quote

Check it out here.

To approach this Zipline, I broke it down into manageable parts.

  1. I created the HTML file with three main items: my page title, div container where I wanted to put the quotes, and two buttons. I used Bootstrap to get the positioning the way it is.
  2. I then wanted to add text to my currently empty div container so I did a Google search on how to dynamically add text with JavaScript and came across this.
  3. Then I created an array of quotes that could be randomly chosen by their array index number. I pulled a sample of quotes from here.
  4. When a user presses the ‘Another thought’ button, I want a quote from my sample to appear. I did a Google search on how to implement an .onClick event and found this.
  5. To pull randomly, I did a search on how to select random items in an array using jQuery and found this. I created a function to hold the sample array and the random number generator.
  6. To create the Twitter sharing button, I used this to help generate the correct data for my link. If you want to use Twitter’s pre-designed buttons, you can go here to generate code for that.
  7. After I got all that to work, I did the page styling. I used Unsplash for my background image. Go here for a text-shadow lesson.

Whoohoo! Working quote machine!

Bonfire: Falsy Bouncer

Challenge:

Remove all falsy values from an array.

Falsy values in JavaScript are false, null, 0, “”, undefined, and NaN.

Use the following:
Array.filter()
Boolean objects


My Solution:

function bouncer(arr) {
  // Don't show a false ID to this bouncer.

  var newArray = [];
  for (var i = 0; i < arr.length; i++) {
    var arrBool = Boolean(arr[i]);
    if (arrBool === true) {
      newArray.push(arr[i]);
      //return newArray;
    }
  }
  return newArray;
}


bouncer([7, "ate", "", false, 9]);

To approach this challenge, I broke it down like this (my thinking process):
1. I need to pass each element of the given array (arr) through a loop to check if each item value is 'false' or 'true'.
2. I can use the Boolean object to check if an item is false or true. I’ll do that within my loop.
3. I don’t know how to use Array.filter(), even after reading the Mozilla page. I’ll ignore that for now.
4. What kind of loop will allow me to iterate through each item in the array? I can use a ‘for loop‘.
5. Do I need to use split()? No, .split() only works for strings.
6. Oh, if you have an array, you can check each individually by using their index number, which starts with 0. So, [0=>7, 1=>”ate”, 2=>””, 3=>false, 4=>9]. Then I’ll start my ‘for loop’ variable ‘i’ at 0 (var i = 0), iterate the length of the array (i< arr.length), and increment by 1 because I want to go through every index in the array (i++).
7. I’ll use an if statement within my loop to check if the values are true or false.
8. After I check if the value is true or false, I want to take all the true values and put them somewhere. Maybe I’ll create a new array called newArray and store all the true values (var newArray = []). I want to be able to return the newArray so I’ll declare this newArray outside of my loop.
8. To add items to an array, you can use .push(), with what you want to push included inside the parentheses.
9. I tried to do newArray = newArray.push(arr[i]); but was getting an error. I removed newArray = and now it works! Will need to look into why that is later.
10. I want to return the new array, so I’ll write return newArray outside of my for loop.
11. I also want to return my newArray in my if statement so that the for loop can access the newArray values.
12. Well, returning the newArray within my if statement causes an error, so I’ll comment that out.
13. Yay! Passed all tests!