JavaScript

Browser and Node.js

Javascript is a scripting language for web browsers and servers. The code below enables the arrow keys to load the next and previous pages. Give it a try!


JavaScript:

1
2
3
4
5
6
7
8
9
10
document.addEventListener('keydown', (event) => {   // this listens for all key presses on the keyboard
  
    if (event.which === 37) {                       // 37 is the keycode for the 'left arrow' key on the keyboard
        window.location.href = 'css.html';          // if pressed, go back a page to CSS
    }

    if (event.which === 39) {                       // 39 is the keycode for the 'right arrow' key on the keyboard
        window.location.href = 'serverside.html';   // if pressed, go forward a page to Server Side
    }
});

This code listens for a "keypress" on specific keys. When a key is pressed this code is executed. If you press 14 keys in a row, this code gets executed 14 times. It will ignore every key except the 2 specified. If the key pressed is the 'left arrow' key, your browser is redirected to the CSS page. Or Server Side page for the right arrow.

The "keypress" is just one type of event listener. Any input including mouse movements, clicks, swipes, etc. can be listened to and acted upon. This is part of what makes JavaScript so flexible when adding functionality to a webpage.


Fetch data from a website:

1
2
3
4
5
6
7
fetch('/some/url')
  .then(response =>  { 
    // response might be your user profile
  })
  .catch(error => {
    // its nice to show the error to the user
  });

The above example is an AJAX request using the Fetch API. This is an async request that returns a Promise. The response can be used to update a webpage.

Fetch using ES6 Async/Await:

1
2
3
4
5
6
try {
  const response = await fetch('/some/url');
  // response might be your user profile
} catch (error) {
  // its nice to show the error to the user
}

Async/Await is a modern javascript standard. This example produces the same result as the first example. The 'await' keyword pauses javascript execution until the asyncronous request completes. This is less code and looks and feels more like syncronous code.