Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript in the Web #6

Open
noobling opened this issue Jun 27, 2019 · 0 comments
Open

JavaScript in the Web #6

noobling opened this issue Jun 27, 2019 · 0 comments

Comments

@noobling
Copy link
Owner

noobling commented Jun 27, 2019

JavaScript was a language created for the web that is why its popularity has sky rocked because as the popularity of the web has increased so has the popularity of JavaScript. Since most developers know JavaScript we have taken it out of the web to build mobile applications (React Native), servers (Node JS) and desktop applications (electron). It is important to gain a deep understanding of it if you become a professional dev but it is very easy to get started. Let's look at its original application, making dynamic websites through DOM manipulations and making HTTP calls to get data from websites/servers.

DOM

It is a JavaScript API for accessing the website to alter the HTML and example JavaScript that would alter HTML

document.title = 'hello world'

This would change the text inside <title></title> tags. You can imagine how we could create dynamic websites now, for example, we set the title of the page based on the user's name. The DOM allows us to think of the HTML in a website in a programmatic sense.

Here is how JavaScript would view a webpage.
image

We won't spend much time learning the DOM because you don't work with it much in your day job because of libraries that have built abstractions over it so you don't directly write JavaScript that manipulates the DOM like what we did above. Example DOM manipulations

window.onload = function() {alert('hello world')} // When the webpage loads we create a popup with the text hello world

// Get the first paragraph element and 
var paragraphs = document.getElementsByTagName("P");
alert(paragraphs[0].nodeName); // loads a popup with `P`

// Sets the text for an element
document.getElementById("someId").innerHTML = "Hello World!";

// Appending an element to the DOM
var node = document.createElement("P");                 // Create a <li> node
var textnode = document.createTextNode("Water");         // Create a text node
node.appendChild(textnode);                              // Append the text to <li>
document.getElementById("container").appendChild(node);     // Append to the container element 

// When you click a button with id btn it will write to the console the current date
document.getElementById("btn").addEventListener("click", function () {console.log((new Date).toLocalDateString())});

Making a reactive webpage

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <button id="btn">Add some text</button>
    <h2>Some text will go here</h2>
    <ul id="list"></ul>
  </body>

  <script>
    function addSomeText() {
      var node = document.createElement("LI");
      var textnode = document.createTextNode("some text");
      node.appendChild(textnode);
      document.getElementById("list").appendChild(node);
    }

    window.onload = function() {
      document.getElementById("btn").addEventListener('click', addSomeText)     
    };
  </script>
</html>

Take away

Although you won't use this much or at all (I haven't used this sort of code for over a year) it is important to appreciate what is going on behind the scenes with the frameworks you are using. At the end of the day, all the frameworks compile down to plain JavaScript consisting of these types of functions. The most important concepts are the DOM and event listeners so you should research them more before a job interview.

JavaScript Syntax

It is a very relaxed language that has a lot of quirks noobling/david-learns#21 that remain because if they changed it would break a lot of websites that have written this kind of code. A major reason why I believe JavaScript has become so popular is the low barrier to learn it. You can just open up your browser console F12 and start writing JavaScript. The issue with that is it has allowed a lot of low-quality content to float around and to make things worse the language changes so fast, new syntax is constantly added for example es5 introduced classes, destructuring, let and const.

The important parts

I find it boring just listing out everything like a dictionary. But somethings you just have to learn before you can do the fun practical stuff.

variable definitions

var x = 1
const y = 2
let n = 3

function declarations

function x() {
...
}

function () {
...
}

() => {
...
}

const x = function () {
...
}

const x = () => {
...
}

loops

for (var i = 0; i < 10; i++) {
...
}

// Given x is an array
for (let i of x) {
...
}

// There is also while and do while loops but I haven't used them 

conditionals

if (x !== y) {
...
} else if (z === k) {
...
} else {
....
}

switch(expression) {
  case x:
    ....
    break;
  case y:
    ....
    break;
  default:
    ....
}

Data structures

{
  key: 'value',
  key1: { key: 'value' }
}

[{k1, 'value'}, 1, 2, [1, 2, 3]]

Iteration and manipulation of data structures

const nums = [1,2,3,4]
nums.map(x => x + 1) // => [2,3,4,5]
nums.filter(x => x < 3) // => [1,2]
nums.reduce((accumulator, current) => accumulator + current)) // => 10
nums.forEach(x => ...) // loops through each number in array
nums.find(x => x < 3) // => 1
nums.findIndex(x => x < 3) // => 0

const obj = {
  key1: 'value',
  key2: 'value'
}

Object.keys(obj).forEach(key => obj[key])

Strings

const hello = 'hello world'

`string template ${hello}`

hello.length // => 11

hello.indexOf('hello') // => 0
hello.indexOf('apple') // => -1

hello.slice(1, 4) // => ell

hello.replace('hello', 'dog') // => dog world

hello.toUpperCase() // => HELLO WORLD
hello.toLowerCase() // => hello world

'   hello world'.trim() // => hello world

hello.split() // => ['hello', 'world']

['hello', 'world'].join() // => 'hello world'

// NOTE: most string methods can take regex input instead of string input

Object destructuring

// This is an advanced concept introduced in es6

const obj1 = {k1: 1, k2: 2}
const obj2 = {k3: 3, k4: 4}
{...obj1, ...obj2} // => {k1: 1, k2: 2, k3: 3, k4: 4}

const obj3 = {k1: 4}
{...obj1, ...obj3} // => {k1: 4, k2: 2}

const {k1} = obj1 // k1 = 1

const arr = [1,2,3,4]
const [first, second] = arr // first = 1, second = 2

Async

There are two types of communication synchronous and asynchronous the former you have to wait for the response and the latter you don't wait for the response. The main use case for this is when you want to read or save from an API/Server/Database but you don't want to reload the entire page. JavaScript can be written asynchronously the issue with this is it can make the code hard to understand.

fetch('https://api.somewhere.com')
  .then(
    function(response) {
      if (response.status !== 200) {
        console.log(`error occured ${response.status}`)
        return;
      }

      // Examine the text in the response
      response.json().then(function(data) {
        console.log(data);
      });
    }
  )
  .catch(function(err) {
    console.log('Fetch Error :-S', err);
  });

console.log('hello world') // code here will execute immediately without waiting for the slow network request.

// Using async/await instead of promises

try {
const response = await fetch('https://api.somwhere.com')
  if (response.status !== 200) {
    console.log(`error occured ${response.status}`)
  } else {
    const { data } = await response.json()
    // do something with data
  }
} catch(e) {
  console.error(e)
}

Perhaps it is a bit easier to read with async/await since it looks synchronous.

Wrap up

That is it you can build a lot of things with just those constructs. Of course, there is much more to JavaScript, but that is what I use daily. I encourage you to go deeper into JavaScript and learn it more in-depth because like it or not it is here to say and will remain the dominant programming language for years to come.

Practical Example

Specification

  1. Get an api key from alphavantage
  2. On a new webpage fetch stock data from https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=YOURAPIKEY
  3. Display back the data in an intuitive fashion
  4. Allow users to input their own stock symbol and search for that
  5. Deploy your new website with now

Example solution

Go further

There are a lot of issues in our current implementation

  • Grab the correct date in a more robust way e.g. use a library
  • Indicate some loading when making a request to fetch the stock price
  • Create a graph with historical prices

Further readings

noobling/david-learns#2
noobling/david-learns#21

🌮 We did it! Let's look at how we can improve what we did by using React

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant