Skip to content

Instantly share code, notes, and snippets.

@scarhand
Last active June 18, 2019 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scarhand/43b64d79b0d69335d028fe1658ea97d0 to your computer and use it in GitHub Desktop.
Save scarhand/43b64d79b0d69335d028fe1658ea97d0 to your computer and use it in GitHub Desktop.

Adding a JavaScript file to an html document

As a rule of thumb, JavaScript (JS) files should always be included at the end of the document. Most of the times the JS will interact with elements on the page. Putting the JS at the bottom of the document will reduce the chance that an element that is to be interacted with does not exist. JavaScript can be included from an external file, or placed directly inside the document. The former is in general preferred because it increases maintainability and reusability. Directly in the document:

<html>
  <head>
  </head>
  <body>
    <script type="text/javascript">
      // your code here
    </script>
  </body>
</html>
From an external file:
<html>
  <head>
  </head>
  <body>
    <script src="link_to_your_file.js" type="text/javascript">
    </script>
  </body>
</html>

Debugging errors in the file

If you wrote some awesome JS, but it doesn't work you probably made an error somewhere. Luckily most of the modern browsers ship with a debugging tool that allows you to track down your error.

If you are using Chrome or Safari you can press ⌘-⌥-i to open up the development tools. In Safari you first need to enable the development tools for this to work. To do this, open the preferences by pressing ⌘-, click on Advanced, and check the Show Develop menu in menu bar option.

In the development tools, look for something called Console. If there we any errors, the browser will list them there. It also has an input box where you can put in arbitrary JavaScript, it is a perfect playground to try out stuff. The biggest benefit is that you directly see the result of what you are doing. Each of the code blocks below (except for the breakdowns) should be working when copy-pasted in the console.

Variables

A variable is a box that can contain a value. A box can contain only one type of value at once. You can tell JS you want to create a new variable with the var keyword. You can create variables with the same name only once. Once you have created the variable you can use it without specifying the var keyword.

var myFirstVariable = "dog";

Here we tell JS we want to create a new variable, we also tell JS we want to give that variable the name myFirstVariable. We use the equals sign = to assign value to our new variable. In JS (and most other programming languages) the equals sign is used to assign a value and not to check if or state that things are equal. Our new variable is a so-called string, a text with the word dog. Breakdown:

   var myFirstVariable = "dog";
// ^   ^               ^ ^
// |   |               | |
// |   |               | The, in this case string, value you want your
// |   |               | new variable to hold.
// |   |               |
// |   |               Use the equals operator to assign a value to your
// |   |               new variable
// |   |
// |   Give the new variable the name myFirstVariable
// |
// Tell JS you want to create a new variable.

Other types of variables

There are 6 types of variables that are important in JS, string, number, boolean, array, object and function. The last one will be discussed semtely.

String

A string of characters, text. The text is encapsulated in single (') or double (") quotes.

var aStringVariable = "This is my text";
var anotherStringVariable = 'Have you tried smelling a green apple?';

A string can also be an empty string. It is still a string, but is has no text in it:

var empty = '';
// or
var empty = "";

Number

A whole or decimal number. JS makes no distinction between those, a number is a number.

var aNumber = 82;
var anotherNumber = 22;

Boolean

A variable can have only two values. It either has the value true or false.

var thisIsTrue = true;
var thisIsFalse = false;

Array

An array is a list of values. You can put as many values from any type you want in an array. For arrays the brackets ([]) are used. To create a new array you must use the brackets. Every value inside the brackets should be separated by a comma. The whitespace surrounding the values does not matter. You can puts as much whitespace between values or between the opening and closing bracket as you want. You can even put newlines between them if that makes stuff more readable.

// This creates an empty array, it is a list, but there are no items
// in it.
var emptyArray = [];

// You can create an array with names
var names = [ 'Anna', 'Katya', 'Glorializ' ];

// Or you can create a array containing only numbers
var arrayWithOnlyNumbers = [ 2,5,6,1 ];

// You can even mix the types
var allKindsOfValues = [ 'Banana', 99, true, false, 'Dog' ];

// An array really accepts every type of value, even other arrays
// You can create an array with two new arrays in it like this:
var arrayOfArrays = [ ['banana', 'apple', 'peppermint'], [42, 36, 99] ];

To lookup a value in an array you also need the brackets. Looking up a value does not remove it from the array. The array stays intact. Looking up values is done by indexes. Each item in the array has an numerical index. Programmers had to be special and decided they would start counting at zero instead of at one. The first item in an array has index zero (0), the second item has index one (1), etc... We can create the names array again:

  var names = ['Anna', 'Katya', 'Glorializ'];
//             0       1        2

If we want to know what the first name in the list is, we must do this:

// indexes start at zero, so the first element has index 0
var theFirstName = names[0];

This will give us the first item in the array. If you assign the looked up value from an array to a variable, the variable will always be of the same type as the value in the array.

// Get the first name from the array
var theFirstName = names[0];

// The variable theFirstName will now be of the type string, because
// the first item in the names array is a string.
// If we were to pick the first item from the arrayOfArrays array, we
// would get an array.
var firstArray = arrayOfArrays[0];

// firstArray is of type array, because the first item in the
// arrayOfArrays is an array.
// Therefore, you can also request the first item from the firstArray.
var firstFruit = firstArray[0];

Object

The object is, just like the array, a container of values, but in the object the values are not looked up by a numerical index, but by a name. To create a new object you must use curly braces ({}). The name/value combinations are separated by comma's. Its notation is equivalent to what you've already seen in css. Just like with the array whitespace and newlines between the name/value combinations in the object does not matter. Just like with the array you can put any type of value in the object.

// Create a new empty object, with no values in it
var myFirstObject = {};

// Here we create a new object with the name car. This car will have
// three properties:
// - color, which is a string
// - price, which is a number
// - sold, which is a boolean
var car = { color: 'green', price: 2999.99, sold: false };

// We can do the same thing with newlines
var car = {
  color: 'green',
  price: 2999.99,
  sold: false
};

To look up a value, or a property of an object you can use the dot-notation (object.propertyName), or the brackets notation (object['propertyName']). With our car example:

var theColorOfTheCar = car.color;
// or
var theColorOfTheCar = car['color'];
// In both cases the variable theColorOfTheCar will now be the string
// green

If you use the brackets notation, the property should be used as a string. You must put the name of the property between single of double qoutes. For the dot-notation you should not do that.

// Wrong
// This is cause a Uncaught SyntaxError: Unexpected string
car.'color'

// Wrong
// this will cause a Uncaught ReferenceError: color is not defined
car[color]

Functions

With functions you can create reusable packages of functionality. You can create your own functions, and use them just like the existing functions. There are a lot of builtin functions that you get for free, just by using a webbrowser. You can store functions in a variable, or in an array or object.

Functions can take parameters that can be used when executing the function. The parameters are specified between parentheses after the function name, and are separated by comma's. The body of the function, the code that should be executed when the function is invoked, should be between curly braces. If you want your function to return a value you should use the return keyword at the end of the function. If there is any code after the return keyword, it will not be executed. Creating a new function:

// Create a function that will multiply two numbers
function multiply(number1, number2) {
  return number1 * number2;
}

Breakdown:

// Tell JS you want to create a new function
// |
// |        The name of the function
// |        |
// |        |       Opening parenthesis to begin the list of parameters
// |        |       |
// |        |       | First parameter
// |        |       | |
// |        |       | |        Second parameter
// |        |       | |        |
// |        |       | |        |       // Closing parenthesis, to end the
// |        |       | |        |       list of arguments
// |        |       | |        |       |
// |        |       | |        |       | Opening curly bracy to indicate
// |        |       | |        |       | the start of the function body
// |        |       | |        |       | |
// ˅        ˅       ˅ ˅        ˅       ˅ ˅
   function multiply( number1, number2 ) {
     return number1 * number2; <---------- The body of the function, the
                                           code that should be executed
     var useless = true; <---------------- This will never be executed,
                                           because it is after the return
   }
// ^
// |
// The closing curly brace to indicate the end of the function body.

Calling or invoking a function

If you have created a function you'll most likely also want to use it. To call or invoke a function you type the name of the function, followed by parentheses containing the argument(s) for the function. If the function has no parameters, you should still use the parentheses.

// Call our previously created function multiply
multiply(2,3); // this will return 6
// As you can see, you can input the arguments directly
// you can also use variables as arguments, or a combination of both
var two = 2;
multiply(two, 3); // this will also return 6

Operators

There are a couple of operators that you can use in JS. One of them we've already seen: the assignment operator (=).

Assignment

The assignment operator is used to assign a value to a (new) variable.

// Assign a value to a new variable
var animal = "cat";
// Assign a value to an existing variable
animal = "unicorn";

Addition

The addition operator (+) allows to to add to numbers, or to concatenate two strings.

var twenty = 18 + 2;
// twenty will now have the value 20
var helloWorld = 'Hello ' + 'world!';
// helloWorld will now have the value Hello word!

You can add as many numbers as you want, and you can concatenate as many strings as you want.

Other arithmetic

The other arithmetic operators are for substraction (-), division (/) and multiplication (*). These can only be used on numbers. They do exactly what you would expect them to do :)

var five = 22 - 17;
var four = 20 / 5;
var ten  = 2.5 * 4;

Equality

To test for equality the triple equals sign (===) is used. There is also a double equals sign that can be used to test equality, but it is not recommended to use that. If you use the equality operator, JS will check if the values on both side of the operator are the same. If they are the boolean value true is returned. If they are not equal, the boolean value false is returned. These return values can be stored in variable or be used in a conditional (see below).

// Create two variables
var dog = 'dog'; //a string variable with the value dog
var cat = 'cat'; //another string variable with the value cat

// Check if those variables are the same and store the result in a new
// variable
var dogAndCatAreTheSame = dog === cat;
// The dogAndCatAreTheSame variable is now of the type boolean and
// will have the value false, because the string 'dog' is not equal
// to the string 'cat'

You can also test for inequality with the not-equal operator (!==). This will also return a boolean value, but it will be the inverse of the === result.

// Create two variables
var dog = 'dog'; //a string variable with the value dog
var cat = 'cat'; //another string variable with the value cat
// Check if those variables are NOT the same and store the result in a
// new variable
var dogAndCatAreNotTheSame = dog !== cat;
// The dogAndCatAreNotTheSame variable is now of the type boolean and
// will have the value true, because the string 'dog' is not equal
// to the string 'cat'

While it is possible to compare two variables, it is not necessary to store values in a variable in order to compare them. It can be more clear to do so, though.

var input = 'some kind of text';
var empty = '';
input === empty; //this will return a boolean with value false

// however, this is exactly the same
input === '';

// and you can even do this:
'some kind of text' === '';

This is especially useful in conditionals.

Negation

The exclamation mark (!) is the operator that be used to negate, or invert a boolean or a boolean expression.

// We assign the negated value of the boolean true to the variable
var thisIsFalse = !true;
// The variable thisIsFalse will now have the value false

You can also use it on variables, array items, object properties or function results. On variables:

var active = true;
// active has the value true
var inactive = !active;
// inactive now has the value false

On array items:

var array = [ true, false, true, false ];
// Get the second value, that is false
var secondValue = array[1];
// secondValue has the value false

// Get the negated second value
var negatedSecondValue = !array[1];
// negatedSecondValue has the value true

On object properties:

var dog = {
  name: 'Mr. Jones',
  color: 'brown',
  isBarking: true
}
// We now have a brown dog named Mr. Jones that is barking
var silent = !dog.isBarking
// silent now has the value false
On function results:
// Let's create a function with no arguments that always returns true
function myFunction() {
  return true;
}
// Call the function and store the result
var result = myFunction();
// result is true, because the function returned true
var negatedResult = !myFunction();
// negatedResult is true, because the function returned true, but we
// negated it

Conditionals

Conditionals are code structures which allow you to test if an expression returns true or not, running alternative code revealed by its result. Expression are boolean expressions and should always give a true or false value. You can use a comparison expression, a boolean variable, a boolean item from a list, a boolean property from an object or a function that returns a boolean inside a conditional.

var thisIsTrue = true;
if(thisIsTrue) {
  // do the true thing
} else {
  // do the false thing
}

Conditionals can for instance be used to determine which action should be run.

// Create a new customer object.
// This object has three properties
// - email, a string
// - name, a string
// - hasDownloadedLicenseFile, a boolean
var customer = {
  email: 'niels@phusion.nl',
  name: 'Niels',
  hasDownloadedLicenseFile: false
}
// We now have a customer with an email address, a name and a boolean
// to indicate he has not yet downloaded the license file.

// If the customer has downloaded the license file we want to send him
// a congratulations email.
// If he hasn't we want to send him a reminder.
// We use the dot-notation to retrieve the value of the
// hasDownloadedLicenseFile of the customer.
// Because hasDownloadedLicenseFile is a boolean, we can use it inside
// the conditional:
if(customer.hasDownloadedLicenseFile) {
  // do stuff to send a congrats email to customer.email
} else {
  // do stuff to send the reminder to customer.email
}

Or, we can use a comparison value without create a variable or a property for it:

if(customer.name === 'John') {
  // Yay, this is John!
} else {
  // Awwh, not John :(
}

Using JavaScript to interact with your html-document

Ok, so how do you actually put it to use? For the most basic example you need two things: a html file and a JavaScript file. The html file should include a reference to the JS file. If you do this and open the html file in a browser, you get a few things for free in JS.

console

You get a variable called console, this variable is an object and has (besides some other stuff) a property called log. This log property is of the type function. This means you can invoke/call this function using the dot-notation (or the brackets notation). This log functions accepts one argument and it will print that argument to the Console in the development tools. For instance:

console.log("Hello from the console");

Will print the text

Hello from the console to the Console in the development tools.

document

You also get a variable named document, this is a variable that contains an object that describes the html document. This object also has properties that you can access. Those properties can be of any type (string, number, function, etc...)

obtaining a reference to an element

One of the most useful things you can do with the document is looking up elements on the page. The document object offers a few methods to do so. (which you can also try out from the console in the development tools of the browser!)

document.getElementById(id) This is a function that takes one argument, an id in the form of a string, and looks up a html element by its id. Please note that you should not include the hashtag (#) before the id. In this snippet:

<!-- ... html stuff -->
<div class="group">
  <input type="text" name="first_name" id="first_name_field">
</div>
<!-- ... more html stuff -->

There exists an input element with the id first_name_field. We can ask the document to look up that element and store it in variable.

var inputField = document.getElementById('first_name_field');

We now have a reference to the input field in a variable. This variable is an object and its properties are the same as that of the input field. It has for instance a property name which is a string with the value "first_name". The input field has a ton of other properties, but one of the more interesting is the property value, which contains the text the user typed into the input box.

document.querySelector(selector) This is a function that takes one argument, a selector in the form of a string, and looks up an element that matches that selector. The selectors you can input here are the same as those used for css. Considering the same snippet:

<!-- ... html stuff -->
<div class="group">
  <input type="text" name="first_name" id="first_name_field" class="form-field">
</div>
<!-- ... more html stuff -->

we can look up the div where the input field is in, like this:

var div = document.querySelector('.group');

You can also look up the input field by its class or id:

var inputFieldByClass = document.querySelector('.form-field');
var inputFieldById = document.querySelector('#first_name_field');

Because the querySelector function expects a selector you must include the hashtag when looking up elements by id using this function.

There is one caveat though. This function returns the first element that matches the selector. If you have multiple input fields that all have the class form-field, only the first one will be returned. To get all elements that match a certain select, the querySelectorAll function can be used. This will return a value of the type array that contains all elements that match the provided selector. For example:

<!-- ... html stuff -->
<div class="group">
  <input type="text" name="first_name" id="first_name_field" class="form-field">
</div>
<div class="group">
  <input type="text" name="last_name" id="last_name_field" class="form-field">
</div>
<!-- ... more html stuff -->

In JavaScript:

var allInputs = document.querySelectorAll('.form-field');
// allInputs is an array containing the objects for the input fields
// for first name and last name.
// They are in the array in order in which they are in the document.
var lastNameField = allInputs[1];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment