So you want to build a house, that is a metaphor for a website (we will pretend for this exercise that we live in a country where that is financially feasible). First you will need your plan and framing, this would be your HTML. HTML tells the computer what elements you have, and where they go (your DIV rooms, your < a href> doors, etc).
Next comes the decoration (a little backwards maybe, but hey, this is your house, your rules). This is your CSS paint, wallpaper, furniture, all that fun stuff.
But wait! You need to do the electrical wiring, the plumbing, all the backend stuff that makes things actually work! Well my friend, luckily you can use JavaScript (JS) for that!
When following instructions, you are likely to follow them in order (I say likely, you might be one of those maverick types who doesn't read instructions). In the same way, your computer is going to read the instructions given to it in a particular order. We call this the control flow, and this can make big differences in the behavior of your programs.
console.log("Get instant noodle packet from cupboard");
console.log("Boil water in pot");
console.log("Add noodles from packet to pot");
console.log("Drain water once noodles are cooked");
console.log("Add flavouring sachets and mix");
console.log("Eat noodles straight from pot because you have lost control of your life");
This code will execute each instruction in a particular order. In this example's case, the order will be going down in the order you read them, but that's not always true, so watch out!
Now, you have found yourself in a strange situation, you now all of a sudden own an instant noodle food truck! You will need to keep making instant noodles for people, but you don't want to copy and paste this code over and over again, so instead you decide to use a loop!
for (let i = 1; i <= 5; i++) {
console.log("Get instant noodle packet from cupboard");
console.log("Boil water in pot");
console.log("Add noodles from packet to pot");
console.log("Drain water once noodles are cooked");
console.log("Add flavouring sachets and mix");
console.log("Serve noodles to customer");
}
This is a basic loop that will execute these instructions a set number of times (the bottom instruction has changed, you have a small business, you have gained control of your life). It works thusly:
DOM stands for Document Object Model (not the other thing, you weirdo). The DOM is the interface programmers use for interacting with and manipulating web documents with JS (or other languages). With the DOM, programmers can navigate the document (HTML in our case) and add, delete, or modify content and elements, to add interactivity, update information, and other cool effects to the website. Sounds pretty abstract and brain bending (because it is), but let's demonstrate with examples!
This code in the HTML document tells the webpage there is a button here:
<button class="buttonClass "id="buttonId">Click me</button>
Styling of the button in CSS (gotta have a stylish button):
.buttonClass {
background-color: #80CCFF;
box-shadow: 2px 2px 5px #523a4d;
color: white;
margin: 15px 25%;
border: none;
width: 50%;
height: 50px;
}
This JS adds the actual functionality, or the button wouldn't do anything. This code creates an "alert" at the top of the page, that says 'Hello World!'
document.getElementById('buttonId').onclick = function () {
alert('Hello World!');
return
};
Wouldn't be any fun without the actual button!
What we have done here is add code to the button that interacts with the DOM via dot notation. Specifically the 'getElementById' method is applied to the 'document' object (the HTML page), allowing us to 'select' the element that has the id 'buttonId' (the button on the page). 'onclick' then accesses the 'onclick' (which is an 'event handler') property of the HTML element we have selected. This will then trigger the function after it, running the code block in the function, saying hello to the world!
Another way to think of the DOM is with a tree, with branching points being nodes, or HTML tags. The Document Object Model sees every HTML tag as an object, with nesting tags being treated as the child of the ones they are enclosed by. The contents of these tags, what is between them, is also an object to the DOM.
This HTML here can be represented as the DOM tree below it:
<!DOCTYPE html>
<html>
<body>
<h1>HEADING</h>
<p id="paragraph"><em>content</em></p>
</body>
</html>
Ok so, we have a shop. Not just any old shop, this one sells data! But we have to store the data, in our shop, otherwise how will we access it to sell? This is where objects and arrays come in!
Arrays are collections of values that are stored in a particular order (almost like a list). Each value in an array is assigned a number, or index, starting at 0 (not 1) for the first value. An array can look, and be accessed, like the example below:
const yourSocialMediaAccount = ['Your passwords', 'Your browsing habits', 'Your personal info'];
console.log(myArray[1]);
--// Output: 'Your browsing habits' //--
In this array we have some data to sell (we are a social media company), and we need to output one of the values from the array. In this example, the second value is outputted, as we have logged yourSocialMediaAccount[1].
But we want to store some specific data types together, so that we can access particular values that are related. So let's use an object, as below:
const yourPersonalInfo = {
name: 'John Smith',
age: 35,
occupation: 'Entrepreneur'
};
console.log(yourPersonalInfo.age);
--// Output: 35 //--
In this object, we have 'key: value' pairs. The 'key' part is the first part, eg 'age', and the value is assigned to the key, eg '35'. We can then access it via dot notation as in the code example above (object.key returns the value).
Last but no least, we have functions (no not like parties, don't be silly). A function is essentially a discrete code block, that can be used as many times as needed to produce an output. So instead of rewriting the same code every time you need part of your code to produce something, you can instead call the appropriate function you have already created! Planning makes functions successful (no not parties, stop asking).
The function is named first eg 'functionTime', and given an parameter if needed. The code block inside the {} curly brackets is the then executed when the function is called. Here is a simple function example, that reminds us of a very important thing:
function partyTime() {
console.log('It's time to party!');
}
We will need to use this very often, so instead of repeating this through our code, we can just call it at the appropriate times like so:
partyTime();
Functions also accept parameters, which then can be passed into the function body for whatever you need, like so:
function boogieTime(name) {
console.log('Stop eating those noodles out of the pot ${name}! It's time to boogie!');
}
boogieTime('you loser ');
--// Output 'Stop eating those noodle out of the pot you loser! It's time to boogie!' //--
Functions mean you don't have to rely on hard coding inputs as often, or having magic numbers floating all over that you will forget to change when it's important, making your code a lot more flexible. Functions are ESSENTIAL to keeping your code tidy and easy to read, and easy to maintain for the poor person who has to work on it after you.