G Frequently Asked Questions
Last updated: 2023-01-05 18:18:21
G.1 Chapter 3
G.1.1 Modifying global variable
Q: How can a function influence the value of a global variable?
A: As discussed in Section 3.9, global variables can be accessed (and modified) from within a function. For example, the following function f
, when executed, modifies the global variable x
(initial value 100
) to a new value 200
, by multiplying it by 2
:
let x = 100;
function f() {
= x * 2;
x
}f(); // The value of 'x' is now 200
Hovever, changing a global variable is not recommended because it makes it difficult to keep track which parts of the code affect a given variable. The recommended approach is to make the function independent of the global environment, so that it gets all inputs through the parameters and affects the global environment through the returned values. For example, here is the recommended approach instead of the above example:
let x = 100;
function f(x) {
return x * 2;
}= f(x); // The value of 'x' is now 200 x
G.1.2 Inserting/removing array element
Q: How can we insert or remove an element into a specific position in an array?
A: Inserting a or removing an element at a specific position can be done with the .splice
method.
For example, the following expression inserts a new element into position 2
(the 0
means that no elements are deleted):
let fruits = ["Orange", "Banana", "Mango", "Apple"];
.splice(2, 0, "Pineapple");
fruits; // Returns ["Orange", "Banana", "Pineapple", "Mango", "Apple"] fruits
The following expression removes the element in position 2
(the 1
means “delete one element”):
let fruits = ["Orange", "Banana", "Mango", "Apple"];
.splice(2, 1);
fruits; // Returns ["Orange", "Banana", "Apple"] fruits
For more details and examples, see the .splice
method reference.
G.1.3 Object Oriented language
Q: Is JavaScript an Object Oriented programming language?
A: Yes, JavaScript is an Object Oriented language. JavaScript uses special functions called constructor functions to define and initialize objects and their features.
For example109:
function Person(name) {
this.name = name;
this.greeting = function() {
alert('Hi! I\'m ' + this.name + '.');
;
} }
The constructor function is JavaScript’s version of a class. Here is how we can create instances of the class Person
. The new
keyword is used to tell the browser we want to create a new object instance, followed by the function name with its required parameters contained in parentheses, and the result is stored in a variable. This is very similar to how a standard function is called:
let person1 = new Person("Bob");
let person2 = new Person("Sarah");
After the new objects have been created, the person1
and person2
variables contain the following objects:
{name: "Bob",
greeting: function() {
alert("Hi! I'm " + this.name + ".");
}
}
{name: "Sarah",
greeting: function() {
alert("Hi! I\'m " + this.name + ".");
} }
G.1.4 JavaScript console inside VSCode
Q: How to access a JavaScript console inside Visual Studio Code (VSCode)?
A: To setup a JavaScript console in VSCode, go through the following steps:
- Download and install Node.js from https://nodejs.org/en/download/.
- Restart VSCode (in case it was already open).
- Inside VSCode, select Terminal→New Terminal. This will open a terminal panel within VSCode.
- In the terminal, type
node
and press Enter. You are now in a Node.js JavaScript console (Figure G.1).
The Node.js console is useful for experimenting with general JavaScript code, but keep in mind that:
- Even though the Node.js engine should be compatible to the one used by browsers such as Chrome, eventually code intended to run in the browser should be tested in a browser.
- The Node.js environment is isolated and not associated with any web page, so that, for instance, the
window
anddocument
objects (see Section 4.3.1) are not accessible.
G.2 Chapter 4
G.2.1 Removing collection of HTML elements
Q: Consider example-04-03.html
(Figure 4.4). How can we remove all <li>
elements from the page?
A: First, we need to create an HTML collection object, which contains the references to all elements that we want to remove (Section 4.7.2):
let nodes = document.getElementsByTagName("li");
Second, we need to go over the elements in the collection nodes
, using a for
loop (Section 3.10.3), and remove them from the page:
for(let i = 0; i < nodes.length; i++) {
// nodes[i]. ...;
}
The first thing we might try to do is to use the method called .remove
, which removes an element from the DOM:
for(let i = 0; i < nodes.length; i++) {
.remove();
nodes[i] }
However, this only removes two out of four list items (Figure G.2)! (Can you guess why?)
The recommended approach, in this case, is to use the hidden
attribute instead. The hidden
attribute is a general HTML attribute that hides an HTML element from view, without removing it from the DOM. The following for
loop sets the hidden
attribute of all list items to true
, thus practically removing them from the page:
for(let i = 0; i < nodes.length; i++) {
.hidden = true;
nodes[i] }
G.2.2 Constraining event listener frequency
Q: How can we delay an event listener function to execute only 1 second after the last event?
A: To limit the event listener frequency, we can use a conditional measuring the time elapsed since the last event. The condition uses a counter variable, hereby named lastMove
, which is being reset every time the function is executed. Here is a modified script for example-04-05.html
(Figure 4.6), where the displayed coordinates are only updated if the mouse was moved at least one second after the last update:
let el = document.getElementById("position");
let lastMove = 0;
document.addEventListener("mousemove", function(e) {
if(Date.now() - lastMove > 1000) {
.innerHTML = e.pageX + " " + e.pageY;
el= Date.now();
lastMove
}; })
A live version of this example can be found here:
This solution is based on the following StackOverflow answer:
G.2.3 Saving .getElementById
method in variable
Q: Why isn’t it possible to assign a method into a separate function? For example, this works:
document.getElementById("intro");
but this returns an error (Figure G.3):
= document.getElementById;
f f("intro"); // Returns error!
A: The reason for the error is that a method depends on its context, namely the object that contains the method. Without the context, the method cannot operate. For example, a method can access other properties of its containing object via the this
keyword. This is beyond the material in our course. For more information, see the this
tutorial by Mozilla (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this).
G.3 Chapter 6
G.3.1 Routing
Q: How can we add routing (shortest path between two points) in a Leaflet web map?
A: There is no built-in routing capability in Leaflet, because it requires a dedicated service and routing algorithm, which are beyond the scope of the Leaflet library. However, Leaflet can be combined with one of the numerous routing APIs to integrate routing into our map.
The Routing example demonstrates this idea (Figure G.4), using the Mapbox Directions API.
Note that the code uses two concepts which we haven’t covered yet, namely layer groups (Section 7.6.5) and the Fetch API (Section 7.7). By the end of the course you will be able to understand the complete code in this example.
The examples are from the Object-oriented JavaScript for beginners tutorial by Mozilla (https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS).↩︎