Running JavaScript on your webpage
Firstly, I made a file called app.js within a folder called javascriptVessels. In that file, I made a few commands that practiced newly-learned content:
- First of all, I made console.log("Hello from your first JavaScript file!")
- Within the <head> section of this page, I added the following: <script src="../javascriptVessels/app.js"></script> This allows us to use that JavaScript file for this page. Inspect the page, and you'll see the message from the JavaScript app.js file!
- Important! The <head> is NOT the ideal place to put your <script> element. When writing JavaScript that interacts with HTML elements, we want those elements to be loaded and acknowledged by the browser before the script. So, better to include the script just before the closing <body> tag, just like those two Bootstrap links!
- Additional Note: to comment out an entire section: highlight the area, then use CTRL+'/'
Conditionals and the (Extremely Annoying) Prompt
Experience learning C++ introduced me to what conditionals are, as well as how to use the if/else if/else statements. In this tiny exercise, I want to try and prompt the user to enter a password of at least 6 characters. Additionally, the password must not contain a space. If successful, this page should already have prompted you for a password.
In all honestly, I am very familiar with the vagaries of the &&(AND), ||(OR), and !(NOT) operators. See the minor change with !== vs != doesn't really faze me.
The use of switch statements isn't at all different from in C++, either! Just don't forget the break statements, unless you intend to!
Arrays
Arrays have multiple uses in JavaScript. Among other examples, they can be used to help with:
- A list of comments on an IG post.
- A collection of levels in a simple game.
- The songs in a playlist.
We can set up to an empty array like so:
let colors = [];
This will make colors an empty array of length 0. The term typeof will
return 'object', for reasons that will become clear later in the course.
Other arrays are shown here:
let lottoNums = [5,9,16,37,39];
let days = ['Monday','Tuesday','Wednesday'];
This (truncated) array contains lottery numbers and a few of the days of the week. Unlike in C++, we can
have multiple different TYPES used within the same array. (Note: I think this is useful when dealing
with JSON).
One additional point of interest is the way in which we add elements to an array. In C++, the size of the array is generally fixed (although it is possible to push_back into a vector. Security errors are rife in C++ because of illegal access to an array, by going outside the limits (i.e. below 0 or at/above an index equal to the size of the array). However, in JavaScript, we can do the following:
let beatles = ['John','Paul','George','Ringo'];
beatles[4] = 'Stuart';
let dwarves = ['Doc','Dopey','Grumpy'];
dwarves[6] = 'Bashful';
In the above case, adding a fifth Beatle is no problem! Also of interest, we can just skip the 3
lesser-known dwarves, and plop the ludicrous 'Bashful' in a dwarf 7, at dwarves[6]! Until named, the
spaces in the array at indices 4, 5, and 6 will be empty.
Arrays: .push() & .pop()
The method .push(item) allows us to add an item to the end of our array.
- Using .push(item) is easy!
- .push(item1,item2) is also possible in JavaScript!
- In fact, .push(item1, item2..., ...itemn) is fine in JavaScript!
.pop() removes one item from the back of the array! If you've used a vector, queue, stack, or deque in C++, you should be familiar with the meaning of the functions!
Shift and Unshift
These are new to C++ guys. shift means to remove from the start of the array. unshift means to add to the start of the array
let movieLine = ['Tom','Nancy','Pablo','Oliver','Eva'];
movieLine.shift();
//This RETURNS THE ELEMENT REMOVED, which is Tom...
//Remember that .shift() removes the first element (in line) within the array!
movieLine.push('Bruce');
//Adds Bruce at the end of the line
//.unshift(item): unshift adds an element to the front of the array:
movieLine.unshift('VIP');
//If we print out the movieLine, we have [VIP, Nancy, Pable, Oliver, Eva, and Bruce]
- Essentially, .shift() is analogous to pop_front()!
- Conversely, .unshift(item) is similar to push_front(item)!
Additional Methods
The following methods are also covered in Section 17 of the course:
- concat is used to merge arrays.
- includes looks for a value
- indexOf is just like string.indexOf
- join creates a string from an array
- reverse reverses an array
- slice copies a portion of an array
- splice removes/replaces elements
- sort...well, it sorts an array!
concat CSN.concat(Y);
This is fairly easy to use. We call .concat on one array, and pass the other array into this, like so:
let cats = ['blue','kitty'];
let dogs = ['molly','eric'];
cats.concat(dogs);
console.log(cats) //Gives us ['blue', 'kitty', 'molly', 'eric']
includes(value) beatles.includes('Stuart');
This searches for SPECIFIC elements in our array! Using cats.includes('Bobo') will merely return false in the array above. However:
cats.includes('kitty'); //This will give us TRUE!
indexOf(value) moonwalkers.indexOf('Buzz') will give index 1 (second comes right after first)
Remarkably similar to the above, it returns the index of a specific (yearned after) value. If no such value exists within the array, then -1 is the result. So, in the example above:
console.log(cats.indexOf('molly')) //This will give us 2
console.log(cats.indexOf('ceilidh')) //This give -1!
If multiple elements of the same value are held within the array, then the FIRST index of that value
will be returned.
reverse helps to reverse an array in place, and returns the reference to the same array
reverse is known as a destructive method: it reverses the entire content of the array in place. For example:
let beatles = ['John','Paul','George','Ringo','Stuart'];
console.log(beatles.reverse());
//Gives us Stuart Ringo George Paul John
//Interesting order....
slice() olympicMedals.slice(0,1); (Omits shameful, shameful Bronze)
This returns a shallow copy of a portion of an array into a NEW array object selected from start to end, where start and end represent the index of items in that array.
In other words, it's a means of getting a copy of a slice of an array.
In the example in the header, using olympicMedals.slice(1); will give us Silver and Bronze in a new array!
We can choose between adding just a starting point, or including both the starting and stopping point!
let beatles = ['J','P','G','R','Pete','Stuart'];
let forgottenBeatles = beatles.slice(4);
OR
let forgottenBeatles2 = beatles.slice(4,5);
.splice()
.splice() is a bit more complicated, but involves changing the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, use slice() instead.
.splice(start);
.splice(start, deleteCount);
.splice(start, deleteCount, item1);
.splice(start, deleteCount, item1, item2, itemN);
As you can see, there are so many methods involving splice() to incorporate! This operation is quite efficient, and very rarely used.
let colors = ['Red','Orange','Yellow','Green','Blue','Violet'];
colors.splice(5,0,'Indigo');
Adds indigo into the array between 'Blue' and 'Violet'
colors.splice(5,1,'Deleted');
Removes indigo from our array
colors will now be: ['Red','Orange','Yellow','Green','Blue','Indigo','Violet'];
.sort()
The sort() method sorts the elements in place, returning a refeence to the same array, now sorted. The default sort order is ascending, converting eleemnts into strings, then comparing their sequences of UTF-16 code unit values. The time and space complexity of the sort is NOT guaranteed, as it depends on the implementation.
So, .sort() by itself is NOT a viable numeric sort. We can sort things using functions, which will be covered in Section 20 of the course.
Reference Types and Equality Testing
This is an uncomplicated point, but you should recognize that the way objects or variables are stored in JS is quite similar to the style of C++. In the lecture, the following example is used:
let nums = [1,2,3];
[1,2,3]===nums; //Returns false;
let copyNums = nums;
copyNums===nums; //Returns true!
As anyone with rudimentary understanding recognizes, variables and objects are stored in memory. When we
use an equality operator, we are looking to see if the references are the same: i.e.
whether the references are at the same address in memory.
Long story short, === & !==, and == & != look at the references in memory when determining whether two objects are 'equal' or not.
Arrays and const
With our arrays, we can set an array using:
const nums = [1,2,3];
nums[0] = -13;
Changing the content of the array is just fine! As long as the array stays at the same space/reference
in memory, it's okay to make changes to the internal parts of the array! We can perform all of the
operations we learned, such as .pop(), .push(value), .shift(), .unshift(value) etc...
What isn't possible is to suddenly try and reassign the array to something else entirely. So, we can't use something like nums = 1; (for example)
Multidimensional Arrays
Just like in C++, it is possible to create and use nested arrays in JavaScript. One famous example is the tic-tac-toe game:
const gameBoard = [['X','O','X'],['O',null,'X'],['O','O','X']];
How would we access 'null' in the above array (ignoring the winning line!)? Well, we can use
gameBoard[1][1] = 'O';
If modelling a Rubiks cube, we might be able to use a 3D array :) But not yet...