Hand-in-Hand Walkthrough Web Development Episode 3

Hand-in-Hand Walkthrough Web Development Episode 3

In sequel to the last episode,

JavaScript

Now, this is where logic comes in front-end development. It is the place with the programming syntax and functionalities. This is an all-purpose language for both client and server-side development with libraries such as (React.js and Node.js for the client and server side respectively).

JavaScript is the language that makes our webpage interactive. Remember our Jumia web app example?, what happens when you click on the "Add to Cart" button? you would realize that you can then pay and the item would be successfully purchased. This is all JavaScript. Before we get into it, I want to tell you that Google is your best friend, and do not be ashamed to go and find solutions there, as all developers do. You only get better through practice. I'm sure you are excited about the prospect of being able to communicate with your device. Let's get into it, Shall we?

Note: JavaScript is in no way related to Java. They are completely different languages used for entirely different things.

The Browser Console

The browser console is your guardian angel on this journey. This is because it can be used to test the result of your code, write code, have errors are displayed there, and many more. So, if your program does not seem to work, make sure you inspect it via the browser console and correct it. How do I get to the Console? Okay, right-click anywhere on your browser screen and then click on inspect, a pane that shows the elements, styles and all characteristics of your code would appear. You would be automatically logged to the Elements tab, the Console tab is the one next to it. Click on it and you are at your browser console. You can log contents into the console by using this code below; console.log("I am a web developer in the making.") This would display "I am a web developer in the making." in the console.

JavaScript Data Types

These are the kind of data that JavaScript programs can accept. They are strings, integers, floats, booleans, null and undefined. Let's take a look at all of them one after the other. Strings are alphabetical and are passed via single or double quotes. Integers are whole numbers (numbers with no decimal numbers), for example, 1,4 ,6,845, and so on.

Floats are numbers with decimal numbers like 3.5, 43.9, and all.

Booleans are simply true and false values.

Null simply means empty in JavaScript.

Undefined, as the name implies, is when a variable or another javascript syntax is not defined or given any value.

Arithmetic Operators

These are the normal add, subtract, multiply and divide as you did in elementary school. But this is with JavaScript.

The main thing to know here is that the values that you want to perform the operations on must be integers(int) or float(float). If you add a string and an integer, it concatenates both values. For instance, "2" + 2 = 22. This just puts both values side by side instead of the desired addition. But this syntax works as desired for other arithmetic operators, but it is not a good practice. If you are stuck with a string, just turn it into an integer by passing the string into an int() function, such that int("2") + 2 = 4. You can also round off and perform various mathematical operators by using the Math module. Go through and play with the possible uses of the Math module as it is very useful.

How variables are assigned in JavaScript with =, ==, ===

These single-equals, double-equals, and triple-equals are known as assignment and comparison operators. = is used to assign values to a variable. == in JavaScript is used for comparing two variables, but it ignores the datatype of the variable. === is used for comparing two variables, but this operator also checks the datatype and compares two values. Checks the equality of two operands without considering their type. Compares the equality of two operands with their types. The main difference between the double and the triple equals is that the triple equals take data type into consideration. For example;

if ("2" == 2)
    { return true };
else{ return false };
The above piece of code would return true.
if ("2" === 2)
    { return true };
else{ return false };

Then this would return false as the data types differ.

Variables

These are what allow you to grab certain parts of your document. Here, you communicate with the document and you can also use variables to store re-useable values in your JavaScript code. These are done with three keywords which are; const, let, and var.

Const These are you assign constant variables in the document. Elements assigned by the const variable cannot be changed or re-assigned in another place. For example; const doc = document.getElementById('name'); const doc = 45; If you run this code, you would see an assignment error as const variables cannot be re-assigned.

Var This keyword defines the variable globally during the whole code. This is desirable if you feel you would refer to that particular variable during the whole programming code. Let's just say that the var is a keyword that defines a variable globally regardless of block scope.

Let The let keyword defines that variable in the block in which it was declared. For instance; if you declare a variable using the let keyword in a function, that variable would only be applicable to that particular fuction block. Those are the three variable types, so use them according to your code situation.

Conditional Statements

These are the if, else, if-else, and switch statements. Imagine if you want to log a particular text based on the user's input, this is an action performed if a particular condition is met. A good example is if you want to welcome people to your website based on the time of the day. The ideal code for this is;

if (time < 10) {
  greeting = "Good morning";
} else if (time < 20) {
  greeting = "Good day";
} else {
  greeting = "Good evening";
}

This is how if-else statements are used. Now to the rarely used switch statement. The switch statement is used to switch between different values of the code. This statement works with different cases as the values. A good example;

let x = "0";
switch (x) {
  case 0:
    text = "Off";
    break;
  case 1:
    text = "On";
    break;
  default:
    text = "No value found";
}

This is basically all for the conditional statements, but they are used for far more complex concepts. You do not have to worry, as it uses the same syntax.

JavaScript Loops

Loops are used to perform repeated tasks based on a boolean condition(true or false). Loops would continue until the initially true condition would return false. There are different types which are the for loop, for-in loop, while loop, do-while loop, and the break­-continue loop.

The for loop This helps to display some code for a particular condition. It works by using the for keyword and then initializing a loop variable(i is usually used) and then set the length and then how you want it to change. Code;

for (let i = 0; i < 5; i++) {
  text += "The number is " + i + "<br>";
}

The While loop The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates. Code:

while (i < 10) {
  text += "The number is " + i;
  i++;
}

The Do-While loop This is used to execute a statement while an expression is at a particular value. Code;

do {
  text += "The number is " + i;
  i++;
}
while (i < 10);

The for-in loop This is a basic control statement that allows you to loop through the properties of an object. The statements of code found within the loop body will be executed once for each property of the object. Code:

for (x in object) {
  code block to be executed
}

The break-continue loop The continue statement (with or without a label reference) can only be used to skip one loop iteration. The break statement, without a label reference, can only be used to jump or exit out of a loop or a switch. For example; Break;

for (let i = 0; i < 10; i++) {
  if (i === 3) { break; }
  text += "The number is " + i + "<br>";
}

Continue;

for (let i = 0; i < 10; i++) {
  if (i === 3) { continue; }
  text += "The number is " + i + "<br>";
}

These are all JavaScript loops and their various uses. These might have been a handful but you just have to know the right applications of all of these loops. And remember, practice makes perfect.

Arrays

An array can be a collection of elements of any type. This means that you can create an array with elements of type String, Boolean, Number, Objects, and even other Arrays. Here is an example of an array with four elements: type Number, Boolean, String, and Object. An array inside another array is known as Nested Arrays. Arrays are usually stored in square brackets. [] It is used as follows; John = ['Davidson', 23, False, [Martha, Jonathan]]; You can edit the contents, loop through and perform a whole lot of complex activities on arrays. Contents of the arrays can be added to or removed by using the push(), pop(), unshift() and shift() methods.

Other useful array methods include; concat() - for merging two arrays, toString() - for converting to the string data type, .length is also very useful for checking the number of items in the array, the splice() method adds new items to an array at specific points, the slice() method slices out a piece of an array, among many others.

See them all on MDN. developer.mozilla.org/en-US/docs/Web/JavaSc.. Warning: Array elements can be deleted using the JavaScript operator delete(). Using delete leaves undefined holes in the array. Use pop() or shift() instead. push() and unshift() for addition of contents and pop() and shift() for removal. The push() and unshift() methods take an argument of what you want to be added to the array. You may be wondering why we have two methods that perform the same function, but there is a very important difference which would be looked at below.

push() adds to the array from the right. That is, the argument passed into the push() method would be the last item of that array while unshift() adds value from the left (The unshift() argument is the first item of the array). This is the same as the pop() and shift() just that they do not take any arguments as they remove values from the right and left respectively. Array methods such as filter(), map(), forEach(), and so on are used to perform different specific tasks on arrays.

For example, the forEach() is used to perform a callback function on all values of the array. Check w3schools.com/jsref/jsref_foreach.asp for a more elaborate discussion on that method and others. Array items can be called individually by referring to them via their indices. A very important point to note here is that arrays are 0-indexed. This means that counting starts from 0. John = ['Davidson', 23, False, [Martha, Jonathan]]; We use this to display the array's first item in the console and so on. console.log(John[0]) Objects An object is an entity of its own, with properties and types. Compare it with an apple, for example. An apple is a type of fruit, with properties. An apple has a color, weight, how ripe it is, etc. A method is simply a function in an object. It has syntax as follows;

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
others: ['bmw', 'honda','tesla']
};

Objects properties and methods

This is the usage of certain elements stored in the object to perform activities.

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
others: ['bmw', 'honda','tesla']
display: function(){
    console.log('Hello from the object.')
}
};

Properties in various objects are accessed by the dot notation, i.e. by calling the name of the particular property. myCar.display() should display the 'Hello from the object' message on the console. You can also refer to properties defined in that particular array with this. method. For example;

const myCar = {
  make: 'Ford',
  model: 'Mustang',
  year: 1969
others: ['bmw', 'honda','tesla']
display: function(){
    console.log('Hello from the object.')
}

carYear:  function(){
    console.log('My favourite car which was the' + this.model+ ' was made in ' + this.year + '.')
}
};

Objects in arrays

These are used to store multiple objects values e.g. employees in a certain company. These are used to store multiple objects showing different values in an array.

var employees = [
    { name : 'Hafeez',
    skills : ['JavaScript', 'CSS']
    },
    { name : 'Mandy',
    skills : ['Python', 'Machine Learning']
    }
];

Looping through Objects

Objects can also be looped through with the for-in loop to display both the property and the property values. It is the normal for-in loop with little adjustments. It goes thus;

for(var prop in myCar){
    console.log(prop);
}

The above code block would display the object properties.

for(var prop in myCar){
    console.log(myCar[prop]);
}

The above code block would display the values of the object properties.

Note: Object properties are usually referred to by calling particular properties in square brackets by the object name. myCar[prop] is a very good example.

Classes

This allows us to easily perform constructor objects and instances are called to it when it needs to be accessed.

class Person{
    constructor(name, age){
        this.name = name;
        this.age = age
    }
display(){
    console.log('Name: ' + this.name)
    }
}
let person1 = new Person('Hafeez', 121)
console.log(person1)

The above would effectively display an object, which is an instance of the Person class. Inheritance is also a key feature of classes, using the extends and super keywords. Let's discuss that now.

class Student extends Person{
    constructor(name, age, field){
        console.log('From the extend keyword')
        super(name, age);
        this.field = field;
    }
}

let Student1 = new Student('Dan', 33, 'Wed Development;') The extends keyword just helps to refer and access the class that is being inherited from.

The super keyword is now used to access the values of the inherited class. Both inheritance methods work hand-in-hand. Both keywords must be used in the inheritance functionality.

Functions

A JavaScript function is a block of code designed to perform a particular task when it is invoked or called. A JavaScript function is executed when "something" invokes it (calls it). An example of a function is ;

function myFunction(p1, p2) {
      return p1 * p2;   
// The function returns the product of p1 and p2
}

Syntax

Firstly we have the function keyword, followed by our function name, a parenthesis() which contains the parameters of the function, and then, the code to be executed inside the curly brackets {}. The function is called like this ; myFunction(2,7); Those two numbers passed in the parenthesis are known as arguments that give the initially parameterized function values to work with. If the function is called without any arguments or excess arguments, an error would be displayed and our code would not work.

But if we pass in arguments less than the parameters, the first parameters take the first arguments and the remaining gets the 'undefined' values. We can easily create addition, subtraction, division, and multiplication evaluation codes with functions. The above function is actually the multiplication function. I'm sure you are thinking, what exactly is the use of functions? I thought about that in my early days too. The answer is very simple. It allows code reusability. You can define a function and just invoke it multiple times in the whole project. Also, something worth knowing is that a function can be called before it is defined. This is because functions have a specific attribute known as Hoisting. This just means every function created is taken to the top of the whole page and thus makes it accessible at all points in the whole JavaScript code. We can set default parameters for our functions i.e. if no arguments are passed into it, a particular block is executed.

function greet(lang){
    if(lang === undefined ){
        lang = 'en';
    }
    if(lang = 'en'){
        console.log('Hello');    
    }
    else if(lang = 'fr'){
        console.log('Bounjour');    
    }
    else{
        console.log('Hello');
    }
}

Function Constructors

These are functions that makes actual functions. Seems abstract? let's break it down. They make use of this and new keywords.

function MakePerson(name, age, email, skill){
    this.name = name;
    this.age = age;
    this.email = email;
    this.skill = skill;
    this.canAccess = function(){
    if(this.age > 18){
        console.log('Welcome');
    } else{
        console.log('You are not allowed to access this website.');
    }
}

let person1 = new MakePerson('Abdul', 23, 'abdulss@gmail.com', 'Graphic Design')
console.log(person1);
console.log(person1.canAccess());

For the first console.log, we have the function constructor displayed in our console. And for the second, we have either 'Welcome' or 'You are not allowed to access this website.' depending on the user's age.

Arrow Functions

This is used to create functions far easier. This is used by creating an arrow diagram with a greater-than sign and an equal-to sign, to form something that looks like an arrow(=>).

let display = () =>{
    return 'Hello'    
}

This would effectively display 'Hello' in the console. Thinking of arguments and parameters, let's address that.

let display = (name, age) =>{
    `${name} ${age}`
}
console.log(greet('Hafeez', 11))

Another thing worth knowing here is that the parenthesis for the parameters can be ignored if we have only one parameter.

let display = name =>{
    `${name}`
}

This can be used as normal functions in objects, classes, etc.

Working with Strings

There are several methods passed in strings to perform different purposes. For example, have you ever noticed that if you type an email without an '@', it would prompt you to write a valid email? This is actually done with one of the several string methods. Another thing to note about strings is that they are also 0-indexed. Let's start with the CharAt() method. The index you want to find would be passed in the parenthesis.

The CharAt() method

var str = 'Hello'
console.log(str.charAt(1)) ;

This logs out 'e' as that has an index of 1.

The indexOf() method

This works differently from the charAt() method as you pass the particular letter as an argument to the method. It then returns the index of that letter and -1 if it does not exist. This is actually what those email configurations use.

var email = 'abdulss@gmail.com ';
if(email.indexOf('@') === -1){
    console.log('This is not a valid email.');
} else { 
    console.log('This email is valid.');
}

With the email above, the 'The email is valid.' text would be logged to the console. The toUpper() and toLower() methods These just convert to uppercase and lowercase when passed to that particular variable. MDN has a very good explanation of all string methods. link

Combining strings and variables

This is a better way of displaying both normal strings and variables. This was formally done by the use of the (+) key and separating the string and variables. As you suspected, this is a very stressful and old way of writing strings and variables together. Now, template strings/literals are used. This is done by using the back ticks (``). The text is written in the backticks and then there is an expression to break out of this template literal and grab variables. This is the combination of the dollar sign and the curly braces(${}). For example;

var name = 'AbdulHafeez'
console.log(`My name is ${name}.`)

This would display, 'My name is AbdulHafeez.' This would save you from the opening and closing of quotes. Formally; console.log('My name is '+ name+ '.' ) I'm sure you see the advantage.

Working with Document Object Model (DOM)

The DOM simply means linking HTML documents. So, this is all about writing dynamic text in your document from JavaScript.

JavaScript is implemented in two ways, they both involve using the script keyword.

In the HTML This is done by using the <script></script> line and then writing the JavaScript code in the middle of the opening and closing script tags. For example;

<script>
    let email = and@yahoo.com
</script>

This is not the best way as it makes our HTML code very ambiguous.

In Its Own File You create an individual javascript file with the extension ''.js" as an indication that it is a JavaScript file and then link it to the HTML with the script link. <script src='./test.js'></script>

We can display text in HTML tags after assigning them to variables using innerText, textContent and innerHTML. innerHTML detects HTML syntax in the text passed and acts on it as normal HTML would, but also acts very well on normal text. It works like this;

var h1 = document.getElementById('heading')
h1.textContent = 'Hello'

or

var h1 = document.getElementById('heading')
h1.innerText += 'Hello'

or

var h1 = document.getElementById('heading')
h1.innerHTML  += '<h1>Hello</h1>'

HTML tags and elements are usually referred to by their classes and id's with keywords like getElementByID, getElementByClassName, getElementByTagName, querySelectors and so on.

So, that's the first part of the JavaScript section of this article. Be sure to stick around for the rest as we are going to learn more interesting JavaScript code. 👌