NotesOn.js


There a few different ways to declare a variable in JavaScript. The first is the most basic, var, which creates a variable without a value or type. const creates a variable whose value cannot change whereas let is a variable declaration that allows the value to be changed. Both were introduced in ES2015.

To print something out to the console, use the console.log() function with the variable to be printed within the brackets, like this: console.log("Hello, World!"). If inputting a string, both single and double quotes can be used. Other datatypes such as integers and boolean values can also be used.


console.log() can also be used to print the results of mathematical sums. Math operators such as +, -, /, * and % can be used to create results like the following console.log(32 + 6). Here, the console would print out the result 38

When a variable is created, subsequent uses of that variable are known as instances. An instance, which could be a string or array has properties. These properties are additional pieces of information attached to the variable. Methods can also be applied to the variable to then return a result containing information about that instance. Properties and Methods differ in that properties are generated (but not returned) on the creation of the variable, and methods generate the results when they are called. Some examples of properties and methods include:

Libraries contain methods that can be called without the need to create an instance. They can be used independent of variables. An example of a library is the Math library which contains methods for mathematical functions including the .random() method, which generates a random number between 0 and 1. This method would be called from the Math library like so: console.log(Math.random()) and a random number would be printed to the console.


To generate a number between 1 and 100, or 1 and 10, the code Math.random() * 100 (or 10) is used.


The Math.floor() method rounds down the generated number. It would be used like so: console.log(Math.floor(Math.random() * 100))


Math.ceil() rounds up the generated number whereas Math.round() rounds the number either up or down, whichever is closest.


More can be found on the MDN via the Math library or the Number library pages.

String interpolation, simply put, is the manipulation of string variables. The + operator can also be used for strings and is used to insert extra variables or values into strings. For example:

let name = "James";
let age = 22;
console.log("My name is " + James + " and I am " + age " years old.");

Would produce the following code: Hello my name is James and I am 22 years old.


Another way of doing this with the new JavaScript ES6 version is with backticks and ${variable}. The backticks wrap everything in a string and the other code specifies the variable to interpolate with the string, for example, the code: console.log(`My name is ${name} and I am ${age} years old.`); would produce the same result. With ES2015 we can also use backticks to interpolate strings and other elements, including variables.

Control flow statements do exactly what they say on the tin - they control the flow of the program. Some examples include if/else statements and loops.


If/Else

These statements ask questions of variables. If the results meet a set of specified criteria, code will be executed, but if the results do not, then the subsequent code will not be executed. The syntax for an if else statement is like so:

let hobby = "Fishing";

if (hobby == "Fishing") {
  console.log("Cool Hobby!");
}
else {
  console.log("Haven't you got a hobby?");
}

It is possible to check the boolean value of a non-boolean datatype variable by checking the truthiness of the variable. In the below example, a the variable variableOne is a string, however we can check the truthiness of the variable based on its declaration and value.

A variable will be truthy as long as the variable does not contain the following:


Comparison Operators

As well as checking whether or not something is true or false, other comparison operators can be used, including:

As with writing !=, writing ! to the variable in the statement conditions will check that the variable is not truthy.


To add conditions to the if/else statement, || acts as an OR operator, and && acts as an AND operator.


Switch Statements

Switch statements are control flow statements that act in the same way as if/else statements but are much quicker to write. They are written like so:

The code at the beginning, switch () contains the conditions to check against, the cases work as else if statements and the default value is the else statement.


Ternary Operator

To simplify if/else statements in another way, the ternary operator is a ? The following is an example of how the ternary operator is used.

This would be simplified with a ternary operator like so:

The code before the operator is the conditions to check for, the code after is the code to execute based on the result of the conditions.

Ternary Operator

A super concise way to check if something is either or (2 way) is a ternary operator. They are formatted like so condition ? expression1 : expression2 where condition is the expression that evluates to true or false and the expressions are what will execute if the condition is true (before the colon) or false (after the colon). The following example checks whether the variable is old enough to drink in the USA:

Functions are blocks of code that contain a particular step or task. Once created, they can be called and the code within the function will be executed. One method of declaring a function is with arrow function syntax which is a shorthand way of declaring a non-method function.
The syntax of initiating an arrow function is like so: var variableName = () => {    } where the code between the curly braces is the code to be executed when the function is called. More information can be found via the MDN here.


Parameters

parameters allow functions to take data as an input and use that data within the function. Parameters are written between the parentheses of the function declaration, like so:funcion functionName(parameterName) {    } or via the arrow function syntax like so: var variableName = (parameterName) => {    }
When the function is called, an argument is passed between the parentheses, which is the input for the parameter. For example:

Instead of using console.log() to return the results of the function, use the return keyword instead. This means that if a function is used elsewhere, code won't be continually returned to the console.

In ES2015, the arrow function syntax was introduced, where functions are declared like this: function isPresent() => {};

Scope refers to the accessibilty of variables within a program. If a variable has global scope then it can be accessed from anywhere within the program, however a variable may have limited scope and can only be accessed from within a single function. Variables with a global scope are those which are declared outside blocks of code, or curly braces.

The JavaScript interpreter assigns "This" a value based on where in the document it is. There are 4 ways that This takes a value: Where it is used within a function, when methods and objects use this and when a constructor is used to create a new instance of a prototype. The final way is when certain methods are called. More information can be found on the MDN or on W3Schools.

One fundamental concept of programming is how to handle and store data. One way of storing data is with a list. JavaScript handles this with the use of array's which contain data. Array's are formatted like so: let arrayName = [ 1, 2, 3, 4 ];.


In order to access items within an array, you access the corresponding number, which is known as an index. JavaScript, like many programming languages is zero-indexed, meaning that you start counting from 0, not 1. Below is an example of accessing an item in an array using the correct index with a variable or by directly logging to the console:

As well as accessing the item, the indexes of an array allow you to change values of specific indexes. For example, arrayName[1] = "New array item"; will change the value of the item stored in the 2nd index.


Arrays, like other data objects, can be manipulated by properties and methods. Some examples include length, push, pop, shift, unshift.

Would remove the items from 1-4, or "bananas", "coffee beans" and "brown rice", returning them in a new array. More array methods can be found via the MDN here

Loops are a programming languages way of repeating blocks of code without having to recreate the process multiple times. There are two types of loops, For and While.


For loops

For loops iterate a known number of time. The syntax for a for loop is: for (startCondition; stopCondition; iterator) {    }. The start condition is a variable containing an integer, usually starting at 0, the stop condition is a value that is either specified explicitly (2, 5, etc) or is a numeric value taken from a method, such as the number of items in an array, using the .length method. The iterator is the start condition variable iterated either positively or negative, usually by 1. For example:

While loops

For loops are limited in that you have to know how many times they will run. However, while loops can iterate an unknown number of times. They are written in the same way that if statements are written.

Sometimes it is necessary to iterate over an array or other data object. This can be done with for loops, however JavaScript contains methods that allow for this functionality to implemented much more easily and effectively. These methods are known as iterators and are called on an array in a way similar to other array methods. The first is known as a .forEach() method which executes the code within the block for each item within an array. They are formatted like so:

Map

Another iterator method is known as .map() which, unlike the .forEach() method, allows us to change the contents of the array. Map looks like this:

Filter

The .filter() method is similar to the .map() method in that it can change the contents of an array, creating a new one, however filter also returns items from the original array if they meet a set of specified criteria.

The above example shows the creatin of an array, words, which contaiins a list of words. The .filter() method is then called on that array, taking the words as arguments, as shown in the parameter word. The code within the block returns any word that has a length of 5 or lesser.

More array methods can be found on the MDN network here.

Objects are containers that allow us to store data and functions easily. A value inside an object is known as a key-value pair, with the value being the data and the key being the corresponding name for that value and the method of accessing it. An object is written like so:

An object can contain strings and other basic datatypes, arrays and even functions and are accessed by the dot notation. For example, printing out the age of our created object would look like this: console.log(person.age), key-value pairs can also be accessed using square brackets, like so: console.log(person['name']. We can add items to objects by adding a new key and assigning it a value, like this: person['name'] = ['James Daykin'] or like so: person.name = ['James Daykin'].


Methods can be added to objects and returned to the console like this:

In the latest version of JavaScript however, a method can be created inside an object without the arrow syntax, like so: sayHello () {    }


This

If we want to reference a value inside the object, we use the this keyword. For example, returning the name variable inside a method within the object can be done like so:

Get/Set

Another method of accessing or modifying the values within an object is with the use of get and set methods. These allow for values to be manipulated directly and have the advantaage of being able to check if the data is valid before setting a new value.

The above is a set method which replaces the current age variable with a new age variable that is checked for validity. To then set a new value we call the setter method as we would any other method that operates on an object, like so: person.age = 30. We then create a get method which returns the value and print it to the console:

JavaScript is an object-oriented language, and if we want to create objects that are similar to each other, it would create a lot of code, reducing performance, reability and efficiency. To deal with this, we can use classes, which are similar to classes in HTML in that they allow us to group together similar objects and apply similar rules or characteristics to them. In the below example we create a class, dog which contains information that might apply to any dog, then we create an instance of that dog class called halley before printing those class characteristics to the console:

The constructor method is called every time a new instance of a class is created. In this example, the dog class has a constructor which takes a name as an argument, then, within the constructor method, the variables which will be filled with a value every time a new dog is created are created, including name and behaviour score. The reason that name is an argument is that that variable is what will be input by the user in this program.

When multiple classes share properties or methods, they become candidates for inheritance — a tool developers use to decrease the amount of code they need to write. With inheritance, you can create a parent class (also known as a superclass) with properties and methods that multiple child classes (also known as subclasses) share. The child classes inherit the properties and methods from their parent class.


Once the parent class is created as we have already created classes, the child or subclasses are created. This is done using the following syntax:

The super keyword appears alone and must be used before the this keyword is used in a class. It calls the parents constructor and allows us to update or modify any properties from the parent class, depending on the arguments provided. In the above example, we want to update the name property, so it is called in the child class using the super keyword.

Static Methods

Sometimes we may want to create a method that can be accessed from within the parent class, but nowhere else, such as in a child class. This can be done with static methods. For example, if we have a class that generates students that are enrolled on a course, we may have a method that assigns a random number to that student. This would be done with a method, but we dont want that number to be accessed/manipulated from a child class that creates a new student. To do that, we add static before we declare the name of the method.

Modules are similar to packages in Python, they are files that contain code that can be exported/imported as and when it is necessary to use the code within. Modules allow us to be able to debug easily, reuse and recycle already defined logic, keep information private and separated from other modules and prevent naming collisions between objects or variables within the global namespace. The syntax for creating a module and exporting it is like so:

To import the module, we use the require() function in which we pass the path to the module as an argument, like so:

In this example, we define a variable Airplane which contains the method require() with the path to the module inside. Notice how we can call the variable the same name as the variable in 1-airplane.js as it is in a different file now. We then create a function which returns the value stored in the Airplane object, myAirplane and log it to the console.


We can also wrap code in an object declared with the exports() function that can be called in an other file, like so:

In ES6, this is now written like this: export default moduleName





The document object is a global object making up the HTML and content of the web page. It can be manipulated using JavaScript by selecting various sections of the document. The document object model, or the DOM is the representation of a web page as a tree-like structure. Similarly to a file-tree in computer science, or a family tree, the document starts with the root and the container elements, such as the <div> acting as the parents. Then, there are children elements, like <p>, which would be siblings of each other.


JavaScript can select these different elements using the tree-like structure, read or change those elements and respond to user events.


Selecting Elements

The most basic form of manipulating elements within the document object model, is by selecting them directly within JavaScript. In this example we are selecting the <h1> element "myHeading" and changing the colour to red whenever we select a specified button:

Here, we assign an id to both the h1 element, and the button we want the user to click. Then, in our JavaScript file, we create a variable for the button which is assigned the id of "myButton" from the HTML. Next, we create a function that specifies that when our event listener "hears" the user click the button "myButton", the style of "myHeading" is changed to red:


Accessing Elements by Tag and Element

It's possible to select all elements with a specific tag. To do this, we type document.getElementsByTagName('x') with the tag in quotes. Once crucial difference with this, is that it selects multiple elements as a collection, which can then be looped over or accessed with indeces, as you can with an array. Elements can be selected with document.getElementsByClassName('x').


Query Selectors

We can select the first element matching a specified tag, class or id with the document.querySelector('x') selector. Use 'x' where x is the tag name, '.x' where x is the class name and '#x' where x is the id name.


It's also possible to further specify the selection of tags, classes and id's as you would with CSS, like so: const listItems = document.querySelectorAll('#shopping-list li');


Getting and Setting Text

Once we have selectedf a tag, class or id with the previous properties, we can retrieve the value of them using .textCOntent or we can set the value by assigning a string to the selected element like so:

In the following example, we have an unordered list with a description that can be changed by the user:

Another way of changing content is with the .innerHTML property. This functions the same way except it can change the elements within tags. For example, we could change<h1 class="myTitle"><Hello!></h1> to <h1 class="myTitle"><Hello, world!></h1>>


We can change the class with .className, the type attribute with .type


Changing Element Styles

Change the style of specific elements once they have been selected using .style followed by the property, like so: p.style.color = 'blue';


Creating New DOM Elements

.createElement('element') can be used to create a new element. This is useful for adding to lists or updating other elements. In the following example we make it so the user can press a button and add a new item to the list:

Next we will see how to insert these created elements into the document object model so that it will appear on the page.


Appending Nodes

Creating an element does not instert them into the tree model that we discussed earlier. To add leaves to a branch in the DOM tree, we need to append them to a node (element). We do this with the .appendChild(element) property. The following example shows how the user can append an item to a list using this property:


Removing Nodes

We can remove nodes, such as photos in a gallery or items from a list with the .removeChild(element) property. We can also do this by selecting a specific child using CSS selectors and the .querySelector property. An example of this is with our previous example, but instread of adding a list item, we can remove the last one by selecting it in the variable declaration, like so: let li = document.querySelector('li:last-child');

The most basic form of manipulating elements within the document object model, is by selecting them directly within JavaScript. In this example we are selecting the <h1> element "myHeading" and changing the colour to red whenever we select a specified button:

Here, we assign an id to both the h1 element, and the button we want the user to click. Then, in our JavaScript file, we create a variable for the button which is assigned the id of "myButton" from the HTML. Next, we create a function that specifies that when our event listener "hears" the user click the button "myButton", the style of "myHeading" is changed to red:


Accessing Elements by Tag and Element

It's possible to select all elements with a specific tag. To do this, we type document.getElementsByTagName('x') with the tag in quotes. Once crucial difference with this, is that it selects multiple elements as a collection, which can then be looped over or accessed with indeces, as you can with an array. Elements can be selected with document.getElementsByClassName('x').


Query Selectors

We can select the first element matching a specified tag, class or id with the document.querySelector('x') selector. Use 'x' where x is the tag name, '.x' where x is the class name and '#x' where x is the id name.


It's also possible to further specify the selection of tags, classes and id's as you would with CSS, like so: const listItems = document.querySelectorAll('#shopping-list li');


Getting and Setting Text

Once we have selectedf a tag, class or id with the previous properties, we can retrieve the value of them using .textContent or we can set the value by assigning a string to the selected element like so:

In the following example, we have an unordered list with a description that can be changed by the user:

Another way of changing content is with the .innerHTML property. This functions the same way except it can change the elements within tags. For example, we could change<h1 class="myTitle"><Hello!></h1> to <h1 class="myTitle"><Hello, world!></h1>>


We can change the class with .className, the type attribute with .type


Changing Element Styles

Change the style of specific elements once they have been selected using .style followed by the property, like so: p.style.color = 'blue';


Creating New DOM Elements

.createElement('element') can be used to create a new element. This is useful for adding to lists or updating other elements. In the following example we make it so the user can press a button and add a new item to the list:

Next we will see how to insert these created elements into the document object model so that it will appear on the page.


Appending Nodes

Creating an element does not instert them into the tree model that we discussed earlier. To add leaves to a branch in the DOM tree, we need to append them to a node (element). We do this with the .appendChild(element) property. The following example shows how the user can append an item to a list using this property:


We can remove nodes, such as photos in a gallery or items from a list with the .removeChild(element) property. We can also do this by selecting a specific child using CSS selectors and the .querySelector property. An example of this is with our previous example, but instread of adding a list item, we can remove the last one by selecting it in the variable declaration, like so: let li = document.querySelector('li:last-child');

Using .parentNode to Traverse Up the DOM

While .parentNode selects the parent of a selected child element, .previousElementSibling selects the the nearest previous sibling to the selected child element. It is important to use .previousElementSibling rather than the older property .previousSibling, as that returns whatever is previously in the document, which can be an empty string if the developer created a new line between elements, for example. We can also use .nextElementSibling to select the immediate following element to a selected child element.

We can also insert a node before the selected element with .insertBefore(newNode, referenceNode);

Any time we interact with a web page, we are creating events. Most of the time nothing happens from thes events but the JavaScript eventListener() property listens for these interactions in order to carry out specified functionality. We've already seen the click event, but here are some more examples from the Mozilla Developer Network:


Listening for Events

We have already seen how to select and manipulate elements on a page, but now we are going to see how we can listen for events. The MDN page on the .addEventListener() method here tells us that we can register the specified listener within the parentheses on the target it is called on before the full stop. This target can be an element, the document itself or a window.


It also tells us the syntax for calling the .addEventListener() method, which is like so:

The type is the event type we want our target to listen for, the listener is the function we want to call when the event occurs and the third parameter is optional and refers to specific characteristics about the listener. The following is an example whereby we target a paragraph tag to change the colour of the text as the user hovers over specific coloured boxes:


VIEW JSFIDDLE HERE

Sometimes we don't want our variables or functions to be accessible in the global namespace. For example, we may be building a large website that uses various JavaScript libraries like jQuery and Angular. In this case, there are many reserved keywords and variables that will be used in both the libraries and our website. To avoid cluttering up our global namespace and to avoid referring to these reserved keywords when we don't want to, we can use module patterns. More can be learned here: StackOverflow or via Cory Rylan