Categories
JavaScript Uncategorized

Object-oriented programming with JavaScript

Good JavaScript programming needs a process — a way to guide how you think about problems and how you write code to solve these problems.

Arbitrarily inventing and improvising your code’s structure is fine for a beginner, but any technical recruiter administering a JavaScript proficiency test will always consider this amateurish at best.

So stop improvising your code structure and writing spaghetti JavaScript.

How?

Use a programming paradigm.

In JavaScript, one of the best programming paradigms is the object-oriented paradigm.

It’s a set of principles that guide the logic of your code structure and how you should write your JavaScript.

And while it has technical aspects, it is not solely a technical component of JavaScript, as a function or loop is. It’s also a way of thinking about problems and a set of rules about how to write your code to solve these problems.

In its simplest interpretation, it’s nothing more than a way to structure your code.

In it’s most complex, it’s a set of methodologies to guide how you think about and solve problems with your JavaScript code.

This guide will help you understand and apply the object-oriented programming paradigm.

Object-oriented programming

Object-oriented programming relies heavily on objects and is based on four scary-sounding principles:

  • encapsulation
  • abstraction
  • inheritance
  • polymorphism

Each principle is applied through JavaScript objects, meaning you’ll be using objects to structure and organize your program.

You’ll still use functions and loops and all your favourite JavaScript methods, but they will all be organized within and around the capabilities of objects.

Let’s explore these principles to help you understand what they mean.

Encapsulation

Or, in simpler terms — keep related parts of your code grouped together.

Your JavaScript programs will always have portions of code that are directly related to each other.

The principle of encapsulation dictates that when you have code that can be grouped together, you group it together.

Take a look at the code below, do you see any groups that the statements can be organized into?

let dogBreed = "Golden Retriever"
let dogColour = "Yellow";
let dogAge = 2;
let dogSound = function() {
alert("Woof Woof!");
};
let catBreed = "Tabby";
let catColour = "Grey";
let catAge = 3;
let catSound = function() {
alert("Meooooow!");
}
      

Right, the two categories are fairly obvious: dog and cat.

Following the principle of encapsulation, let’s reorganize our code with the use of JavaScript objects.

Here’s what that looks like:

let dog = {
  breed: "Golden Retriever",
  colour: "Yellow",
  age: 2,
  sound: function () {
    alert("Woof Woof!");
  },
};

let cat = {
  breed: "Tabby",
  colour: "Grey",
  age: 3,
  sound: function () {
    alert("Meooooow!");
  },
};	

That’s really it, to apply this principle you just need to make sure that when you have code that can be grouped together, you group it together.

And with the use of the encapsulation principle, we can ensure that data and methods are all grouped together, thereby making your code easier to understand and maintain.

Abstraction

Or, in simpler terms — keep the JavaScript objects you create simple.

Objects have a tendency to become unnecessarily complex as they are versatile and have no limit to the number of methods or properties they can contain.

The principle of abstraction encourages you to keep your object simple by only using the methods and properties which are essential to the object to perform it’s desired output.

Let’s consider a TV through the lens of abstraction to arrive at a better understanding of the concept.

A TV does many things, it can turn on, turn off and switch to specific channels, you can even cast content to it from your phone.

A TV also has many properties: weight, size, colour, age, brand.

Through the lens of abstraction, if we were to create a JavaScript object to allow the TV to turn on, that object should only contain the properties and methods directly related to making the TV turn on, everything else is irrelevant.

In other words, the object is an abstraction of the TV as a whole. It is a simplified version of a TV as it does not contain all the properties and capabilities of a TV, but only what is necessary to allow the TV to turn on.

Let’s write some code to demonstrate how abstraction works for this TV object designed to turn the TV on.

Here’s what a the object might look like without abstraction.

turnOnTV = {
  tvAge: 4,
  tvColour: "black",
  tvHeight: 45,
  tvBrand: "Samsung",
  turnOn: function() {
  console.log("TV is on");
  }
}

Here’s what the object looks like with abstraction.

turnOnTV = {
  turnOn: function() {
  console.log("TV is on");
  }
}

Notice how the second version only contains what is necessary to allow the TV to turn on?

That’s the essence of abstraction. Only put in your objects what is necessary.

Inheritance

Or, in simpler terms — reduce repetition.

When using objects in JavaScript we often end up with a lot of very similar objects. Many times you’ll need an object to have the same method or property of an existing object.

Object-oriented programming seeks to minimize the confusion that similar objects have through inheritance.

This is a bit of a tricky concept, so let’s use an analogy of a library.

Think of a library with thousands of books. While each of these books may be unique, they are all still books, and books can all be read.

Thinking of this through the principle of abstraction and objects, we’d want to have a single instance of the read method that is shared (inherited) by all books.

We can do this with the use of a JavaScript prototype.

A prototype allows you to create objects that are based on a single, master object. In JavaScript, this process is called instantiation.

For books, we’d want our prototype to contain a read function so that any time a new book object is instantiated from it, it contains the same read method, saving us from having to recreate the same read method for every book.

Let’s use some code to help illustrate the concept of inheritance and prototypes in action.

First, let’s create a prototype for the book.

function Book(title, author, year, category) {
  this.title = title;
  this.author = author;
  this.date = year;
  this.category = category;
  this.read = read() {
  console.log("You are reading this book!");
  }
}

Next, let’s instantiate a new object based on the prototype.

function Book(title, author, year, category) {
  this.title = title;
  this.author = author;
  this.date = year;
  this.category = category;
  this.read = function() {
  	console.log("You are reading this book!");
  }
}

let book1 = new Book("Dune", "Frank Herbert", 1965, "science fiction");

Now that you’ve instantiated a new object from the prototype, try calling the function from the Book prototype with the book1 object in your JavaScript console.

Notice how the book1 object has the read method even though it wasn’t specified when you were creating it?

The book1 object has the read method because it inherited it from the Book prototype.

With the use of the inheritance principle, we can ensure that data and features used by multiple objects are contained in a single source, thereby reducing the need for repetition and making your code easier to maintain.

Polymorphism

Or, in simpler terms — your JavaScript statements can have varied outputs.

The concept of polymorphism is the trickiest of the four principles for me. It took me quite some time to wrap my head around the concept and how to apply it, but I think the explanation that follows will help you avoid some of the headaches I experienced.

The word polymorphism is ancient Greek and translates roughly to many kinds. In JavaScript this, means a statement can have many varied outputs.

Think of the prototype concept we just explored in the previous section which can pass on a method or property to an instantiation.

Polymorphism allows each instantiation to produce its own unique output when using a method or property inherited from a prototype.

Let’s look at an example using animal sounds to better understand how polymorphism works.

First, let’s create an Animal prototype that receives a parameter for the sound an animal makes.

function Animal(sound){
    this.sound = sound;
    this.speak = function(){
        return this.sound;
}
}

Next, let’s instantiate three objects from the Animal prototype and give them each a unique sound.

function Animal(sound){
    this.sound = sound;
    this.speak = function(){
        return this.sound;
}
}
    var dog = new Animal("woof");
    var cat = new Animal("meow");
    var cow = new Animal("moo");

Next, let’s create a function to display each of the sounds in the console.

function Animal(sound){
    this.sound = sound;
    this.speak = function(){
        return this.sound;
}
}
    var dog = new Animal("woof");
    var cat = new Animal("meow");
    var cow = new Animal("moo");

function showInfo(obj){
    console.log(obj.speak());
}

And finally, let’s log each of the sounds to the console.

function Animal(sound){
    this.sound = sound;
    this.speak = function(){
        return this.sound;
	}
}
var dog = new Animal("woof");
var cat = new Animal("meow");
var cow = new Animal("moo");

function showInfo(obj){
    console.log(obj.speak());
}

showInfo(dog);
showInfo(cat);
showInfo(cow);

Notice how each instantiation of the Animal object passes its own unique argument to the same speak method and a single speak method has three different outputs? This is polymorphism.

Within the Animal prototype there is a single method speak. Within each instantiation of this prototype (dog, cat and cow) the method expresses different outputs.

So, to reiterate, your JavaScript statements can have varied outputs. This is polymorphism.

Applying the principle of polymorphism allows you to keep your code organized and efficient by minimizing the need for repetition.

Applying Object-oriented programming methodology to your problem solving

To use the object-oriented programming methodology effectively you must teach yourself how to look at problems through an object-oriented lense.

Now that we’ve covered the four principles of object-oriented programming: encapsulation, abstraction, inheritance and polymorphisms, I want to share my approach to looking at problems through an object-oriented lense.

But first, I want to acknowledge that there are many articles expressing countless views on how you can, should and should not think about programming in JavaScript.

I suspect that over time JavaScript developers each develop a unique approach to writing JavaScript and that every one of them will profess to you that their approach is the best.

I’m not going to argue that my approach is the best, but simply that it works for me.

My approach is simple and relies on following the steps:

  1. Deconstructing each part of your problem.
  2. Encapsulating each part into an object.
  3. Ensuring each object is an abstraction and contains only what is necessary to arrive at the desired output.
  4. Applying Inheritance and polymorphism to reduce complexity.

Let’s take try using the four steps above on this Netflix homepage.

First, let’s deconstruct the parts of the homepage.

I see three main parts: the navigation, the hero image and the “Popular on Netflix” slider.

Now that we’ve deconstructed the page, let’s create an object for each component.

let navBar = {};
let heroImage = {};
let popSlider = {};

Now, let’s use abstraction to add properties and methods to the navBar and heroImage objects.

let navBar = {
  logo: "netflix-logo.jpg",
  homeBtn: "netflix.com",
  tvBtn: "netflix.com/tv",
  moviesBtn: "netflix.com/movies",
  latesBtn: "netflix.com/latest",
  myListBtn: "netflix.com/list"
};

let heroImage = {
	mainImage: "theLastDance.jpg"
  	playBtn: function() {
    console.log("starting your show");
    },
    moreInfoBtn: function() {
    console.log("here's more info");
    }
};

let popSlider = {

};

Seeing as the popSlider object has a number of movies, we’ll use the principle of inheritance and create a prototype to avoid repetition.

let navBar = {
  logo: "netflix-logo.jpg",
  homeBtn: "netflix.com",
  tvBtn: "netflix.com/tv",
  moviesBtn: "netflix.com/movies",
  latesBtn: "netflix.com/latest",
  myListBtn: "netflix.com/list"
};

let heroImage = {
	mainImage: "theLastDance.jpg",
  	playBtn: function() {
    console.log("starting your show");
    },
    moreInfoBtn: function() {
    console.log("here's more info");
    }
};

function popSlider(title, year, category) {
  this.title = title;
  this.date = year;
  this.category = category;
  this.movie = function() {
  	console.log(this.title);
  }
}

Now let’s instantiate some objects from the popSlider prototype.

let navBar = {
  logo: "netflix-logo.jpg",
  homeBtn: "netflix.com",
  tvBtn: "netflix.com/tv",
  moviesBtn: "netflix.com/movies",
  latesBtn: "netflix.com/latest",
  myListBtn: "netflix.com/list"
};

let heroImage = {
	mainImage: "theLastDance.jpg",
  	playBtn: function() {
    console.log("starting your show");
    },
    moreInfoBtn: function() {
    console.log("here's more info");
    }
};

function popSlider(title, year, category) {
  this.title = title;
  this.date = year;
  this.category = category;
  this.movie = function() {
  	console.log(this.title);
  }
}
let pop1 = new popSlider("Have a Good Trip", 2020, "documentary");
let pop2 = new popSlider("The Last Dance", 2020, "documentary");
let pop3 = new popSlider("Deadpool 2", 2019, "action");
let pop4 = new popSlider("Jerry Seinfeld", 2018, "comedy");
let pop5 = new popSlider("Into the Night", 2017, "suspense");

Finally let’s use the principle of polymorphism to use our inherited movie method to list the title of each of our popSlider instantiations.

let navBar = {
  logo: "netflix-logo.jpg",
  homeBtn: "netflix.com",
  tvBtn: "netflix.com/tv",
  moviesBtn: "netflix.com/movies",
  latesBtn: "netflix.com/latest",
  myListBtn: "netflix.com/list"
};

let heroImage = {
	mainImage: "theLastDance.jpg",
  	playBtn: function() {
    console.log("starting your show");
    },
    moreInfoBtn: function() {
    console.log("here's more info");
    }
};

function popSlider(title, year, category) {
  this.title = title;
  this.date = year;
  this.category = category;
  this.movie = function() {
  	console.log(this.title);
  }
}
let pop1 = new popSlider("Have a Good Trip", 2020, "documentary");
let pop2 = new popSlider("The Last Dance", 2020, "documentary");
let pop3 = new popSlider("Deadpool 2", 2019, "action");
let pop4 = new popSlider("Jerry Seinfeld", 2018, "comedy");
let pop5 = new popSlider("Into the Night", 2017, "suspense");

function showInfo(obj){
    console.log(obj.movie());
}

showInfo(pop1);
showInfo(pop2);
showInfo(pop3);
showInfo(pop4);
showInfo(pop5);

And there you have it, you’ve now got a working understanding of object-oriented programming and are well on your way to becoming an intermediate JavaScript developer.

This is one of the most challenging topics for beginners, so congratulations on making it this far.

<div style="width: 100%;     margin-bottom: 4%;">
<span data-sumome-listbuilder-embed-id="6e423d2042dfc278eef0ff845ff6b3e75df871d9ce39bb9874b44dce3a66d701"></span></div>
Categories
JavaScript

Beginner’s guide to JavaScript objects

Objects are one of the most elegant, simple and extraordinarily useful tools you’ll ever work with when programming in JavaScript.

In fact, objects are one of the reasons why JavaScript is such a popular and widespread programming language.

And if you want to improve your JavaScript programming from beginner to intermediate, you’ll need to understand JavaScript objects.

In fact, without understanding JavaScript objects, you’ll never really understand JavaScript, as almost everything in JavaScript is an object.

This guide will help you understand objects in the JavaScript language. Specifically, it will help you understand object syntax and how to write and use the objects you create.

What are JavaScript objects

The easiest way to think of a JavaScript object is as a container that holds related variables and functions. Sort of like a storage container.

Imagine you have a container and you fill it with sewing items.

You could label this container “sewing supplies” and fill it with thread, needles, pins, and other sewing related items.

This sewing supplies container helps keep your sewing supplies organized and easy to find.

A JavaScript object does the same thing. It helps you keep your data organized and easy to find, and things that help keep your data organized and easy to find are often referred to as data structures.

Actually, you may already be familiar with data structures if you read my beginner’s guide to arrays.

Either way, if it helps you keep your data organized, it’s a data structure, and objects are some of the most useful and simple data structures.

In fact, a JavaScript object is really nothing more than a collection of related name-value pairs, and name-value pairs really only consist of two things: a data value and the name that is used to identify that data value.

Here’s what a name-value pair looks like in a basic JavaScript statement:

let myName = "Daniel"	

The name in the example above is myName and the value assigned to it is "Daniel".

Here’s what a name-value pair looks like for a function:

let myFunction = function() {
console.log("Hello!");
}

The name in the example above is myFunction and the value assigned to it is function() {console.log("Hello!");}

A JavaScript object is, as mentioned, a collection of name-value pairs grouped together.

Here’s what the two examples above would look like organized into a JavaScript object:

let nameValuePairExamples = {
 myName: "Daniel",
 myFunction: function() {
 console.log("Hello!");
 }
};

Both the variable declaration and function declaration from the two previous examples are now within the nameValuePairExamples object.

In other words, a JavaScript object is not only a collection of name-value pairs, but the object itself is like a container you can use to group the name-value pairs. Just like the sewing supplies container.

Here’s another example to demonstrate how a JavaScript object is like a container.

Let’s imagine we wanted to group together a set of attributes for someone named Steve.

In this example, Steve would be the object and the name/value pairs would be the properties of Steve.

Here’s what this looks like:

let steve = {
 height: 190,
 weight: 185,
 hairColour: black,
 alias: "Smiley",
 sayHelloSteve: function() {
 alert("Hello Steve!");
 }
}
};

Simple right? All of the name-value pairs: height: 190, weight: 185, hairColour: black and sayHelloSteve: function() {alert("Hello Steve!"); all fit nicely under the category Steve, which is the object name: steve.

Also, notice how much easier it is to understand that the name-value pairs are all associated with the object steve?

This is a huge help when working with enormous projects with thousands of lines of code.

Now let’s take a look at JavaScript object syntax.

JavaScript object properties, methods and syntax

As mentioned, a JavaScript object is a collection of name-value pairs.

In JavaScript, object name-value pairs have two types: properties and methods.

Let’s take a look at both object properties and methods and then deconstruct a JavaScript object to understand it’s syntax further.

Object properties

Object properties are any variable declarations within the object that are not functions.

Here’s what this looks like using a car as an example:

let myCar = {
	brand: "Subaru",
  	colour: "Blue",
  	year: 2019,
};

Each variable declaration contained within the opening { and closing } of the myCar object: brand: "Subaru" colour: "Blue" and year: 2019 are all properties of the myCar object.

All of these variables declarations are not function declarations and so they are properties of the object.

Object methods

Object methods are function declarations within the object.

Let’s continue with the car example, but this time we’ll create two methods instead of properties for the myCar object.

Here’s what this looks like:

let myCar = {
	carStart: function() {
    alert("Engine is on");
    },
  	carShutdown: function() {
    alert("Engine is off");
    }
}

Each function declaration contained within the opening { and closing } of the myCar object: carStart: function() {alert("Engine is on");} and carShutdown: funtion() {alert("Engine is off");} are all methods of the myCar object.

All of these declarations are function declarations and so they are methods of the object.

To reiterate: any variables contained within the object that are not functions are called properties, while any functions declared within the object are called methods.

Now let’s deconstruct a JavaScript object with both properties and methods to get a better understanding of how objects work.

Object syntax

An empty object in JavaScript is created with the following:

let myNewObject = {};

let myNewObject = asssigns the variable named myNewObject to the object specified by the opening { and closing }.

In JavaScript, an object is created and its contents are defined within the opening { and closing }.

In the example above, however, the object is empty.

Let’s explore the syntax further by deconstructing an object which has content within the opening { and closing } and combines the properties and methods from the car examples from the previous section.

Here’s what that looks like:

let myCar = {
	brand: "Subaru",
  	colour: "Blue",
  	year: 2019,
  	carStart: function() {
    	alert("Engine is on");
    },
  	carShutdown: function() {
    	alert("Engine is off");
    }
};

Ok, the first part you should be familiar with already.

let myCar = asssigns the variable named myCar to an object.

The first statement within the object opening { and closing } is brand: "Subaru". This is a property statement, one of the two types of name-value pairs allowed by JavaScript objects: properties and methods.

brand: "Subaru", is a property of the myCar object. The property name is brand, the value is "Subaru", and a colon : is used to assign the property name to the value.

You indicate that there’s another statement in the object with a ,.

As you can see, there’s another property after brand: "Subaru" which is colour: "Blue". So to indicate there’s another property statement in the object you’d write a , after brand: "Subaru".

Following the property statement colour: "Blue" is another property statement year: 2019.

Each statement in an object must end with a comma , if there is a statement following it.

If it’s the last statement in the object then it does not require a ,.

Following the last property statement year: 2019 you’ll see the other type of statement for a JavaScript object, a method statement, which contains a function.

The first method statement of the myCar object is carStart: function() { alert("Engine is on"); }.

The method statement name is carStart and is assigned to the value with a :. The actual function value which follows is the same syntax as a regular JavaScript function: function() { alert("Engine is on"); }.

And, as we mentioned previously, each statement unless it’s the last statement, ends with a ,.

The final statement in the myCar object is another method statement: carShutdown: funtion() { alert("Engine is off"); }.

Since this is the final statement in the myCar object, there’s no need for a final ,.

Okay, so that covers object properties, methods and syntax.

Now let’s take a look at how you call and reference objects and their properties and methods.

Calling properties and methods of a JavaScript object

Accessing information within a JavaScript object is straightforward.

You can access the properties and methods within an object by calling the object name followed by a . and then the name of the property or method you’d like to access.

Let’s imagine we wanted to access the year property of the myCar object below:

let myCar = {
	brand: "Subaru",
  	colour: "Blue",
  	year: 2019,
  	carStart: function() {
    	alert("Engine is on");
    },
  	carShutdown: function() {
    	alert("Engine is off");
    }
};

If you wanted to access or reference the year property of the myCar object you’d use: myCar.year.

If you wanted to access or reference the carShutdown method of the myCar object you’d use myCar.carShutdown().

If you wanted to list all the properties and methods available to an object you’d simply type the object name in your JavaScript developer console.

In this example that would be myCar.

Ok, pretty handy right?

I think so!

Hopefully, you now have a better grasp on JavaScript object, their syntax and how to write and use the objects you create.

Next up, let’s take a look at how to apply your knowledge of JavaScript objects to write better code through an object-oriented programming paradigm.

Categories
JavaScript

Conditional statements in JavaScript

One of the most incredible powers you can give to your JavaScript program is the ability to make decisions on its own.

Whether you want your program to decide the best time to ask a visitor to subscribe to your newsletter or display your site content in a different language, conditional statements will allow your JavaScript program to make decisions based on conditions and then act on them.

In a way, conditional statements give intelligence to your programs. And this adds a powerful layer of sophistication to any JavaScript program.

This guide will help you understand conditional statements in the JavaScript language. Specifically, it will help you understand conditional statement syntax and how to write and use conditional statements.

What is a JavaScript conditional statement?

A conditional statement tells JavaScript how it should behave when a certain condition is met.

For example, if a user visits your website and their preferred language is French, you could use a JavaScript conditional statement to determine the user’s preferred language is French, and then display the content of your website in French to them.

The best part? You aren’t limited to a single condition, you can repeat this approach for any number of conditions — if the user prefers German, display the page in German, if they prefer Russian, display it in Russian.

An interesting thing about conditional statements is how simple they are. A conditional statement really has only two parts:

  1. the condition
  2. the action to perform once the condition is met

In the language examples above, the condition would be the user’s language preference, and the action to perform would be to display the content in the preferred language.

Another way to think of a conditional statement is to compare it to how you’d make a decision about what time you’ll wake up.

Let’s imagine you had a job that required you to arrive at work by 9 a.m. from Monday to Friday.

Let’s also imagine that you needed to wake up two hours before 9 a.m to arrive to work on time.

The conditions in this example would be pretty simple:

If it’s Monday, Tuesday, Wednesday, Thursday or Friday, you’ll need to wake up at 7 a.m., otherwise, you can wake up any time you’d like.

Let’s take a look at JavaScript conditional statement structure and syntax to get a better grip on how it works.

JavaScript conditional statement structure and syntax

Conditional statements in JavaScript rely on a set of three basic syntax keywords: if, else and else if.

Here’s what this looks like:

if (condition === true) {
  //execute this code
}
else if (alternative condition === true) {
  //execute this code
}
else {
  //execute this code
}

Let’s break down what’s actually going on here:

  1. You specify a condition to match within the opening ( and closing ) with the keyword if.
  2. JavaScript checks if the condition is matched.
  3. If the condition is matched, JavaScript identifies the condition as true.
    • JavaScript then executes the code within the opening { and closing } associated with the condition which is true.
  4. If the condition is not matched, JavaScript identifies the condition as false.
    • JavaScript skips the code associated with the condition which returned false and proceeds to check if the condition within the next else if statement is true.
      • If the condition is matched, JavaScript identifies the condition as true and executes the code within the associated opening { and closing }.
      • If the condition is not matched, JavaScript identifies the condition as false.

The process above is repeated until each condition is checked.

If none of the conditions return true then the final else statement will run.

Once a condition is matched as true the conditional statement stops running. Only if the condition is false will JavaScript proceed to the next condition.

Let’s dissect the syntax.

The if keyword tells JavaScript which condition it should listen for.

The content within the opening ( and closing ) is the specific condition that must be matched. They will return as either true if matched and false if not matched.

The code between the opening { and closing } will run if the preceding condition is true.

The else if keyword tells JavaScript what to do when the previous condition is false, and the associated opening { and closing } is the code JavaScript will then execute.

The else keyword tells JavaScript what to do when none of the previous conditions are true. The code within the associated opening { and closing } is the code JavaScript will then execute.

Let’s take a look at another example using our alarm clock where the if condition is Monday, Tuesday, Wednesday, Thursday or Friday.

Here’s what this looks like:

if (Monday, Tuesday, Wednesday, Thursay or Friday === true) {
  //execute this code
  console.log("Time to wake up!");
}
else {
  //execute this code
  console.log("It's ok, you can sleep in");
}

To reiterate, when it is Monday, Tuesday, Wednesday, Thursday or Friday, the if condition will return as true.

When the if condition is true JavaScript will execute the code within the associated opening { and closing }. In the code example above, this is console.log("Time to wake up!");

Otherwise, if the condition is false, and it is not Monday, Tuesday, Wednesday, Thursday or Friday, JavaScript will skip the associated code within the opening { and closing } and instead execute the code within the opening { and closing } which follows the else keyword.

Additionally, as mentioned, you are not limited to two conditions, you can add as many conditions as you’d like with else if.

Here’s what this looks like:

if (Monday === true) {
  //execute this code
  console.log("It's Monday, time to wake up!");
}
else if (Tuesday === true) {
  //execute this code
  console.log("It's Tuesday, time to wake up!");
}
else if (Wednesday === true) {
  //execute this code
  console.log("It's Wednesday, time to wake up!");
}
else if (Thursday === true){
  //execute this code
  console.log("It's Thursday, time to wake up!");
}
else if (Friday === true){
  //execute this code
  console.log("It's Friday, time to wake up!");
}
else {
  //execute this code
  console.log("It's ok, you can sleep in");
}

Clear as mud?

Don’t worry, let’s practice by building a working alarm clock, it’s the perfect way to get a real understanding of conditional statements.

Writing a program with JavaScript conditional statements

Let’s start by creating a few variables in your JavaScript developer console to get the current day of the week.

var currentDate = new Date();
var dayOfWeek = currentDate.getDay();

The variable currentDate uses the new Date() constructor to tell your web browser what date it is.

The variable dayOfWeek then applies the getDay() method to currentDate and returns an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, 3 for Wednesday, 4 for Thursday, 5 for Friday and 6 for Saturday.

Let’s add a conditional statement to alert us if it’s a day of the week.

var currentDate = new Date();
var dayOfWeek = currentDate.getDay();

if (dayOfWeek === 0 || 1 || 2 || 3 || 4 || 5 || 6 ) {
  alert("It's a weekday, make sure you are awake by 7 a.m.");
}

Notice the use of ||, called an OR logical operator, within the opening ( and closing )?

This tells JavaScript that it can match 0 or 1 or 2 or 3 or 4 or 5 or 6.

They are really useful and allow you to specify multiple conditions for a single set of actions. In the example above, it allows us to specify each day of the week.

Ok, now let’s add an else keyword to our code to tell JavaScript what to do when it’s a weekend and the conditions above are not met.

var currentDate = new Date();
var dayOfWeek = currentDate.getDay();

if (dayOfWeek === 0 || 1 || 2 || 3 || 4 || 5 || 6 ) {
  alert("It's a weekday, make sure you are awake by 7 a.m.");
}
else {
alert("Relax, you can sleep in, it's the weekend!");
}

Now, let’s make this a bit more robust, let’s add an additional condition for Wednesday, when you work from home, with the use of else if keyword.

We’ll need to remove Wednesday from our first if condition and then add it to a a newly created else if condition.

var currentDate = new Date();
var dayOfWeek = currentDate.getDay();

if (dayOfWeek === 0 || 1 || 2 || 4 || 5 || 6 ) {
  alert("It's a weekday, make sure you are awake by 7 a.m.");
}
else if (dayOfWeek === 3) {
alert("You work from home today, you can wake up a bit later at 8 a.m.");
}
else {
alert("Relax, you can sleep in, it's the weekend!");
}

And voila, you now have a working alarm clock in your JavaScript console that knows the difference between weekdays, weekends and when you work from home.

Pretty neat right?

Hopefully, now you understand why conditional statements give intelligence to your programs. And how this adds a powerful layer of sophistication to your JavaScript program.

Next up, let’s take a look at JavaScript objects, the most powerful concept in JavaScript programming.

Categories
HTML JavaScript Marketing

Collecting all the email addresses or links on a webpage with JavaScript

Have you ever wanted, or needed, to collect all of the email addresses or links on a website?

Have you ever tried to do this manually?

I have. It’s incredibly tedious.

There’s nothing quite as dehumanizing as robotically copying and pasting hundreds of email addresses or links from a webpage to an excel sheet over and over again.

So let’s make sure you never have to do that again.

In this guide, I’ll show you how to use JavaScript to collect all of the email addresses or links on a webpage.

It’s actually pretty easy. So let’s get started.

Thinking before writing your code

Before we begin writing our program, it’s always useful to think about what we’re trying to accomplish, this helps us write a more coherent program.

Here’s what we know we’ll need to do for this program:

  1. Search through the content of the webpage for email/links.
  2. Collect the email/links.

Seems pretty straightforward right? It is!

Now let’s break down each of the steps above into actual statements that we’ll need to write to complete the task of collecting emails from a website.

Here’s what we need to do:

  1. Create an empty array to populate with email/links.
  2. Specify where in the DOM we want JavaScript to search.
  3. Convert the content of the DOM to a string.
  4. Use the .match method to specify what we’re searching for.
  5. Add the matched items to our array.

Also pretty straightforward, so let’s start writing some code.

I created a test page for you to practice with. Please open this page in a new window beside this one, activate your developer console, and follow the instructions below.

Collecting all the email addresses on a webpage

Once you’ve opened up this page and turned on your JavaScript developer console, you’ll need to create an empty array to store the email addresses.

Please type this into your JavaScript developer console:

var listOfEmails = [];

Great, now let’s determine where we want JavaScript to look for these email addresses.

In the test page I created for you, the email addresses are within the opening <body> and closing </body> HTML tags of the page.

Let’s write a variable and assign the content within these tags to it:

var contentToSearch = document.body.innerHTML;

Now let’s verify the content assigned to our variable is correct by typing the following in our JavaScript developer console:

contentToSearch;

Did you see the HTML content of the page appear in your developer console? Excellent.

Now we need to convert the content from HTML to text so we can search it. To do this we’ll use the .toString method and apply it to our contentToSearch variable, which will convert all the HTML to text:

var contentAsText = contentToSearch.toString();

All of the content within the opening <body> and closing </body> HTML tags have just been converted to text and assigned to the variable contentAsText.

Let’s now search through it for the email addresses.

To do this we’ll use the .match method on the variable contentAsText in conjunction with a regular expression which matches some standard email address patterns:

listOfEmails = contentAsText.match(/([a-zA-Z0-9._-][email protected][a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);

Now, to access the list of emails you just need one final step, type the following in your browser console:

listOfEmails

You should see your list of emails! Well done!

Here’s the entire program we just wrote.

Final program for collecting all the email addresses on a webpage

var listOfEmails = [];
var contentToSearch = document.body.innerHTML;
var contentAsText = contentToSearch.toString();
listOfEmails = contentAsText.match(/([a-zA-Z0-9._-][email protected][a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);

Collecting all the links on a webpage

This will be pretty similar to the program we wrote for collecting all the email addresses.

Please open this page in a new window beside this one, activate your developer console, and start by creating an array to store our links:

var listOfLinks = [];

Now let’s collect all the links on the page.

Lucky for us, there’s a default JavaScript method called .links which can collect all the links on a page for us, without the need for writing a custom function.

Let’s write a variable to use the .links method:

var collectLinks = document.links;

Now we’ll need to loop through the links one by one and add them to our array.

Let’s do this with a JavaScript loop which utilizes the .push method:

for(var i=0; i<collectLinks.length; i++) {
  listOfLinks.push(collectLinks[i].href);
}

Did you see the number 12 in your developer console?

If you did, congratulations, you’ve just collected all of the links on the page.

Now let’s take a look at the content of our array by typing the following:

listOfLinks;

Notice it collected all the email addresses and links?

That’s perfectly normal since both email addresses and links use the HTML tag a href.

Well done!

Here’s the entire program we just wrote.

Final program for collecting all the links on a webpage

var listOfLinks = [];
var collectLinks = document.links;
for(var i=0; i<collectLinks.length; i++) {
  listOfLinks.push(collectLinks[i].href);
}

Why this works

You might be wondering how this is possible, considering you don’t have the ability to edit the JavaScript files on a website you are visiting.

Well, you don’t actually need to edit a website’s JavaScript files directly as you can run the JavaScript program in your web browser’s developer console. This is actually one of JavaScript’s best features!

So, with only our web browser and a little bit of JavaScript know how we were able to collect all the email addresses and links on a webpage.

Pretty handy right?

Next, let’s learn how to add some intelligence to our programs with conditional statements which let our program make decisions on their own.

Categories
JavaScript

Beginner’s guide to JavaScript loops

Repeating yourself can be a hassle, but sometimes you’ve got to do it you’ve got to do it.

There’s nothing wrong with a bit of repetition. Many of the things we love are the byproduct of meticulously constructed repetition.

A recipe, for example, is a set of repeating steps. A song? The chorus is the best part! Sunrise and sunset? Both repeat! And who doesn’t love sunrises and sunsets!

Repeating statements in JavaScript are called loops, and loops are incredibly useful.

This guide will help you understand loops in the JavaScript language. Specifically, it will help you understand loop syntax and how to write and use the loops you create.

What is a JavaScript loop?

Imagine you wanted to purposefully repeat an action, for example, let’s say you wanted to count from 1 to 10.

There are a few ways you could do this in JavaScript.

Here’s the worst way to do it.

console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);
console.log(6);
console.log(7);
console.log(8);
console.log(9);
console.log(10);

This is… not ideal at all.

Not only is typing out a statement ten times tedious, but it doesn’t count down in sequence.

Let’s look at a better way to repeat an action in JavaScript with loops!

Using the original example above, let’s imagine we wanted to count from 1 to 10 in the JavaScript console.

Here’s what a JavaScript loop that does that would look like:

for (let i = 0; i <= 10; i++) {
console.log(i);
}

Try to run the loop above in your console. You should see something like this:

Pretty neat how JavaScript took care of all the repetition for you right?

You’ll be amazed how many repetitive things you can automate with JavaScript.

Let’s start by taking a look at loop syntax.

JavaScript Loop syntax

Let’s disassemble the loop we used to count from 1 to 10 to better understand the loop syntax.

Here’s the loop:

for (let i = 0; i <= 10; i++) {
console.log(i);
}

There are a number of different types of loops, in this example, we’ll be using the for loop.

The for loop tells JavaScript to repeat an action according to the rules within the ().

Between the opening ( closing ) is where you write the rules which the for loop follows.

In the example above we’re telling JavaScript to repeat the loop 10 times. Let’s take a look at how the rules within the () tell the loop to do this.

There are three conditions within the () that provide instructions on how the loop should function.

The let i = 0; statement is the first condition called the initial expression. We use it to declare a starting point for the loop.

let i = 0 tells the loop where it should start. let i = 0 tells the loop to start at 0. You could start at any number below 10 for this example and the loop would count up from that number until it reaches 10.

i <= 10; statement is called a condition. The for loop refers to this condition every time it finishes running the statements withing the opening { and closing } (more on these below) to determine if it should continue to repeat the loop. In the for loop example above, the loop will repeat for as long as the i is less than or equal <= to 10.

i++; statement is called an increment expression. The for loop looks at the increment expression each time the loop runs. The increment expression tells JavaScript to increment the variable i by 1 each time the loop runs.

The statements within the { and closing } will be executed each time the loop runs.

console.log(i) will log the i value each time the loop runs and the i value will increment by one each time the loop runs.

Looping through items in an array

Let’s try using the loop with a more practical example. We’ll loop through a list of grocery items in our console.

Begin by opening up this page in a new browser window and placing it beside this window with the JavaScript console open.

We’ll start by creating an array of grocery items.

Type the following in your JavaScript console:

var groceryList = [
"bread", 
"milk", 
"cheese", 
"eggs", 
"salad", 
"butter", 
"chicken"
];

Now let’s use a loop to cycle through each item and display them in the console.

After declaring your groceryList array type the following:

for (i = 0; i < groceryList.length; i++) {
console.log(groceryList[i]);
}

You should see something like this:

You’ll notice that the loop condition was slightly different than the one we used to count from 10 to 1. Specifically, instead of i = <10 we used i < groceryList.length.

i < groceryList.length tells the loop to repeat for as long as i is less than the length of the groceryList array.

Using the .length property on an array returns the total number of items in the array.

So, the for loop condition i < groceryList.length will count the total number of items in the array and repeat the loop for each item in the array.

console.log(groceryList[i]) will display each item in the array in your console.

If you recall my guide on JavaScript arrays, you’ll remember that each item in an array has a numerical position.

For example, the groceryList array we created will have 6 numerical positions for each item in the array.

Position 0 is “bread”, position 1 is “milk”, position 2 is “cheese”, position 3 is “eggs”, positon 4 is “salad”, position 5 is “butter”, position 6 is “chicken”.

You’ll also recall that you can access each item in the array in the JavaScript console by typing the array name followed by the numerical position.

So, if I wanted to access eggs I’d type the following in my console:
groceryList[3]

With console.log(groceryList[i]) we used [i] instead of a numerical position.

This allows the for loop to substitute the i with the numerical position of each item in the array, which it then logs to the console and then increments by one (remember this is what the i++ does).

Getting all the links on a page with JavaScript

Let’s try another practical example that you might find useful. We’re going to JavaScript to loop through all the links on a page.

Begin by opening up this page in a new browser window and placing it beside this window with the JavaScript console open.

Type the following in your console:

var getAllLinks = document.getElementsByTagName("a");
for (let i = 0; i < getAllLinks.length; i++) {
console.log(getAllLinks[i]);
}

You should see something like this:

You’ll notice the console uncovered five hidden links on the page. Let’s examine the JavaScript code we ran to understand how a loop allowed us to uncover these links.

Here’s the code again:

var getAllLinks = document.getElementsByTagName("a");
for (let i = 0; i < getAllLinks.length; i++) {
console.log(getAllLinks[i]);
}

document.getElementsByTagName("a"); is a method which will find all HTML tags specified within the (). In this instance, we’ve asked JavaScript to find every a tag, otherwise known as a link. The method returns an array with every link it finds. We assigned this method to the variable getAllLinks.

Next, we set up a for loop that has:

An initial expression of let i = 0;.

A condition of i < getAllLinks.length;.

And an increment expression of i++.

Finally, we logged each item in the getAllLinks array to the console with console.log(getAllLinks[i]);.

Pretty handy right? I definately think so.

Whether you need to collect a bunch of email addresses from a web page, cycle through a newsfeed or even count down from 10 to 1, loops are an essential tool for any JavaScript developer who needs to repeat something, who needs to repeat something.

Next up, let’s try some practical programming by collecting all the email addresses or links on a webpage with JavaScript.

Categories
JavaScript

Beginner’s guide to JavaScript arrays

Lists are underrated. From items to purchase on a shopping trip to essential steps in a life-saving surgery, lists are extremely helpful for making sure you don’t forget anything.

They are useful too, especially in JavaScript

I know what you are thinking. Lists? Wow, who cares?

Well, I didn’t.

Until I learned about them and discovered an endless array of applications (there’s a joke you’ll only understand after you finish reading this guide).

And, once you learn about lists in JavaScript you’ll be surprised at how many applications they have.

This guide will help you understand how to read, write and use lists in JavaScript.

An array is a list

A list of items in JavaScript is called an array.

An array allows you to group items and store them in a single variable.

Here’s what an array looks like with items in a shopping list:

var groceryList = [
"eggs", 
"butter", 
"milk", 
"bread"
];

Without an array, you’d need to write out something like this, which is not practical when you have hundreds of items:

var groceryListItem1 = "eggs";
var groceryListItem2 = "butter";
var groceryListItem3 = "milk"; 
var groceryListItem4 = "bread"; 

An array can contain a mix of data types, it’s not limited to strings as in the example above.

Here’s what an array looks like with mixed data types (strings and numbers):

var groceryList = [
"eggs", 
12, 
"butter",
 1, 
"milk", 
1, 
"bread", 
1
];

You can also create an empty array and populate it with items later.

Here’s what creating an empty array looks like:

var groceryList = [];

And you can also put arrays within arrays, here’s what this looks like:

var groceryList = [
"eggs", 
12, 
"butter", 
1, 
"milk", 
1, 
"bread", 
1, 
["chicken","steak","pork"] 
];

Array Syntax

The nice thing about arrays is they are pretty straightforward and their syntax is not too complicated. At most you’ll need to remember a few rules.

Let’s take a look at the syntax of an array by deconstructing our grocery list from the example above.

var groceryList = [
"eggs", 
12, 
"butter",
 1, 
"milk", 
1, 
"bread", 
1
];

var groceryList = creates, names and assigns the array to the variable named groceryList.

The square brackets [ ] define the array body — everything contained within the start bracket [ and end bracket ] are part of the array. Within the array body, each item is separated by a comma.

Next, let’s take a look at writing an array and accessing the data within it.

Writing an array and accessing the items in it

The best way to become familiar with a concept is to practice it. So let’s write an array and access the data in it.

Begin by opening up this page in a new browser window and placing it beside this window with the JavaScript console open.

First, let’s create an empty array.

Type the following statement in your console and press enter:

var myFirstArray = [];

You should see something like this:

Now let’s add five, string data types, to the array.

Type the following statement in your console and press enter:

myFirstArrayOfColours = [
"red", 
"blue", 
"green", 
"yellow"
];

You should see something like this:

Congratulations, you just created an array and populated it with items!

Accessing items in the array

Let’s take a closer look at what happened when we added items to our array “myFirstArrayOfColours.

Did you notice how your JavaScript console displayed some additional information?

Let’s take a closer look at this, click on the grey arrow ▶ to expand the information.

Notice how each of the string data types "red", "blue", "green", "yellow" has a number to the left of it?

When you add items to an array they are assigned a numerical position value starting at 0.

These numerical positions allow you to reference specific items within the array. To do so you use the array name followed by the position number.

Here’s the statement I would type to access the colour green:

myFirstArrayOfColours[2];

And what about arrays within arrays, how would you access those?

Let’s take a look at the example from the beginning of this guide:

var groceryList = [
"eggs", 
12, 
"butter", 
1, 
"milk", 
1, 
"bread", 
1, 
["chicken","steak","pork"] 
];

Let’s say I wanted to access steak from the groceryList array, here’s what I would type:

groceryList[8][1]

The [8] corresponds to the position of the second array within the grocertList array.

The [1] corresponds to the position of steak.

Don’t forget that each array starts at 0. So when you are counting to the position you’d like to access you need to remember to start at 0.

Ok, that’s it for arrays, hopefully, you now understand the joke at the start of this guide: “an endless array of applications…”

Next up we’ll explore how to use JavaScript loops to cycle through each of the items in an array and do some other neat stuff.

Categories
JavaScript

Beginner’s guide to JavaScript functions

One of the most useful concepts to learn and master in the JavaScript programming language is functions.

Once you understand how they work, everything else in JavaScript becomes relatively easy.

This guide will help you understand functions in the JavaScript language, specifically function syntax and how to write, name and call the functions you create.

What is a function?

Functions are a way to keep your statements organized reusable and easy to reference.

In JavaScript, you’ll usually have to write a number of statements to arrive at a desired result.

For example, if I wanted to ask a visitor to my website their first name and then write their name in a popup box I’d need to write a few statements.

Here’s what the statements would look like:

var userName;
userName = window.prompt("What is your name?");
alert(username);

Each of the statements, or lines, in the code snippet above, is working together to accomplish the task of getting the user’s name and then displaying it in a popup box.

Since the goal of each statement is the same, they would be suitable to group into a function.

Here’s what they would look like grouped together as a function:

var myFirstFunction = () => {
var userName; 
userName = window.prompt("What is your name?"); 
alert("Hello" + userName);
};

Adding a function to these statements was as simple as wrapping them in the function syntax. In this instance, we wrapped the statements in a function named myFirstFunction.

The function syntax extracted from the example above looks like this:

var myFirstFunction = () => {
};

The above syntax wrapped around the statements turning them into a function.

As mentioned, functions help keep your statements organized reusable and easy to reference. We just saw how they help keep your statements organized and easy to reference. But how do we use them?

To use the statements in the function above you’ll need to call the function. When you want to execute the statements in a function this is referred to as calling the function.

To call the function you use the name you gave the function followed by ().

Let’s try to create and call this function in your browser console.

First, copy-paste the code below into your JavaScript console:

var myFirstFunction = () => {
var userName;
userName = window.prompt("What is your name?");
alert("Hello" + userName); 
};

Then call the function by typing this into your console and pressing enter:

myFirstFunction()

You should see something like this:

Why use functions?

Functions have many benefits, not only do they keep your statements organized, reusable and easy to reference, but they also make your code easier to maintain, faster to write and simpler to debug.

Here are two reasons, with associated examples, as to why functions are extremely useful.

Reusable

Functions allow you to execute the collection of statements by calling the function instead of having to write the statements over and over again.

Using our previous example, imagine you had the following group of statements.

var userName;
userName = window.prompt("What is your name?");
alert(userName); 

Now imagine you wanted to add these statements to multiple pages on your website.

With a function, you’d simply wrap the statements in the function syntax and then call them where you’d like them to run:

Wrapping the statements in a function:

var myFirstFunction = () => {
var userName;
userName = window.prompt("What is your name?");
alert("Hello" + userName); 
}; 

Calling the function:

myFirstFunction();
myFirstFunction();
myFirstFunction();

Without a function:

var userName;
userName = window.prompt("What is your name?");
alert(userName);

var userName;
userName = window.prompt("What is your name?");
alert(userName);

var userName;
userName = window.prompt("What is your name?");
alert(userName);

Easier to maintain

When you adjust the statements within a function, every single instance where the function was called will have the same adjustment.

This is extraordinarily handy as it means you only need to adjust the code in a single location.

Imagine you had a website with hundreds of pages and imagine you had the following JavaScript statements that you needed to execute across them all:

var welcomeToMyWebsite;
welcomeToMyWebsite = alert("Welcome to my website!");

And let’s say you wanted to change the alert from "Welcome to my website!" to "Thanks for visiting my website!"

If you had the above statement written out hundreds of times across hundreds of pages you’d need to change every instance of the code in the hundreds of places it appears across your website.

This would take days and would be incredibly tedious.

If you had used a function, you’d only need to change the code once, in the function, and have it change everywhere the function was called across your website.

In other words, making the change from:

var welcomeToMyWebsite;
welcomeToMyWebsite = alert("Welcome to my website!"); 

to:

var welcomeToMyWebsteFunction = () => { 
var welcomeToMyWebsite;
welcomeToMyWebsite = alert("Thanks for visiting my website"); 
};

would cause every instance where the function below is called to change.

 welcomeToMyWebsteFunction()

Function syntax in ES6

ES6 is short for ECMAScript6. ECMAScript is the standardized form of JavaScript.

Don’t let this terminology confuse you, it’s really just JavaScript.

There are two types of function syntax in JavaScript: ES6 and ES5. You’ll likely come across both, but I recommend you use ES6 as it is faster and more up to date than ES5.

As such, I’ll only cover ES6 functions in this guide.

Dissecting ES6 function syntax

This is the function we wrote earlier. It is written with ES6 syntax.

var myFirstFunction = () => {
var userName;userName = window.prompt("What is your name?");
alert("Hello" + userName); 
};

Let’s explore the parts of the function above to better understand function syntax.

First, let’s simplify things by removing the statements within this function since they are not necessary to understand function syntax.

This is what the function looks like without the statements.

var myFirstFunction = () => {
};

You should be familiar with the following line:

var myFirstFunction =

This is simply creating a variable named myFirstFunction.

Where things get interesting is the portion of the code below that follows var myFirstFunction = as it is the unique syntax related to functions in ES6:

() => {
};

() allows you to pass parameters into the function. You write the parameters between the (). There are no parameters in the function example we used above, so it’s empty and looks like this:

()

Here’s a function would look like with a parameter X added:

var myFirstFunction = (X) => {
};

Notice the X is within the (), this means parameter X can now be used when calling the function.

I’ll explain more about calling functions and calling functions with parameters later in this guide.

=> tells JavaScript that you want to create a function. That’s it. Nothing too complex here.

{} is the function body, everything between the opening { and closing } make up the function. You can put any kind of statements within the function body, from logic to variable declarations and more. When you call the function the browser will execute each line within the {}.

Calling a function in ES6

After you’ve written your function you’ll now need to tell your browser how to execute the function, you do this by calling the function with the function name followed by a ().

Here’s what you would type if you wanted to call the function we created previously named myFirstFunction:

myFirstFunction()

That’s it, pretty simple.

Here’s what you would type to call it with a parameter of 5:

myFirstFunction(5)

Practicing writing and calling a function in ES6

Now that we’ve dissected the syntax of a function and how to call it, let’s write a function line by line and call it in our console.

I’m thinking a function that pops up a simple welcome message will be a good example. Let’s write this function.

Begin by opening up this page in a new browser window and placing it beside this window with the JavaScript console open.

Type the following function in your console and press enter. Don’t forget the spaces after Hello and before welcome to my website!

var welcomeMessage = (x) => {
alert("Hello " + x + " welcome to my website!");
};

You should see something like this:

Ok, let’s now call the function with a parameter passed into it.

Type the following into your console and press enter:

welcomeMessage("Dan");

You should see something like this:

Pretty straightforward right?

I know the function syntax can seem confusing at first, but writing enough examples out will ensure you master this concept.

If you now feel comfortable with functions, congratulations! You are now well on your way to an intermediate level of JavaScript knowledge.

If you are still unclear about some aspects of the function syntax I’d suggest having another read of this guide, otherwise post any questions you may have in the comment section below and I’ll be happy to assist.

Next up, let’s take a look at lists in JavaScript. An underrated but extremely useful data type.

Categories
JavaScript

Adding JavaScript to your webpage

Websites are a mosaic of interconnected technology which your web browser weaves into a webpage.

From Google to Amazon, Facebook to Twitter, each site is seamlessly crafted from three components: HTML, CSS and JavaScript.

To be able to craft the sites you love, your browser must have access to HTML, CSS and JavaScript. And to access HTML, CSS and JavaScript, your browser must know where the files are located and how they were added to the website.

This post will help you understand how and where to add JavaScript to your website.

If you are new to JavaScript I’d strongly suggest you read my beginner’s guide to JavaScript basics followed by Getting started with JavaScript variables before reading this guide.

Otherwise, let’s begin. 

Adding JavaScript to your HTML

JavaScript is referenced from your HTML files, and there are three locations to add JavaScript within it.

  1. the <head>
  2. the <body>
  3. after the </body>

Each placement has different use cases and there are two things to keep in mind while making a decision about where to place your JavaScript:

  • your browser loads HTML from top to bottom
  • JavaScript takes time to load

Because of these reasons you want to make a decision to place your JavaScript within the HTML based on :

  • what the JavaScript needs to access within the HTML
  • how long the JavaScript file is

The good news is if you are adding JavaScript to your site as part of a GitHub package or a widget/component, there will usually be instructions telling you what the ideal positioning of the JavaScript is.

Otherwise, here are the three locations available for you to add JavaScript to your HTML.

In the <head>

Use this location if you’d like your JavaScript to load before the HTML content within the <body> tag.

Scripts placed here will usually execute before the Document Object Model loads.

This placement is useful for scripts like the Google Analytics tracking script which you’ll want to load quickly and before the rest of the content on the page loads (so you can track users).

This is a bad location for scripts that interact with the DOM as they will execute before the DOM is created or finished loading.

For example, if your JavaScript needs to access a paragraph tag <p> and is in the <head> it will likely return an error as it will not be able to locate the <p> tag (it hasn’t loaded yet!).

The error above will occur because your browser builds a web page top to bottom. So when it reads the JavaScript instructions that reference a <p> tag before the <p> tag is created, it will return an error.

Within the <body>

This location is useful for JavaScript that you want to load at a very specific location in the DOM.

For example, if you’d like to load your JavaScript only once a specific HTML element on the page is loaded, you might consider placing it within the body after the specific element.

Usually, scripts do not require this level of specificity.

Also, this placement is bad for long scripts as the browser will need to finish reading the script before it can load the rest of the webpage. This will make the website load noticeably slower for the user.

I usually recommend this placement for advanced users.

If you are a beginner I’d suggest using the after the <body> placement.

After the <body>

This location is useful for JavaScript that needs to interact with the DOM.

Since scripts in this position only execute after the DOM is fully loaded, this JavaScript placement is ideal for beginners.

This placement is bad for scripts that need to load before the DOM.

For example, Google Analytics tracking scripts are not ideally suited for this position as they will only load once the entire page is loaded, and if you have a large page, you may lose some data as the analytics script only begins tracking after the page is loaded.

Ways to add JavaScript to HTML

After you’ve decided where you’d like to add JavaScript in your HTML, There are two ways to add JavaScript to your webpage. You can:

  1. add the JavaScript into the HTML directly
  2. link to a separate JavaScript file.

While many seasoned web developers will argue about the advantage of one approach over another, the bottom line is that both methods have their appropriate use case scenarios.

Inline JavaScript

This approach involves writing your JavaScript within the HTML directly within a <script></script> tag.

This approach is often called inline JavaScript and it looks like this:

<script>console.log("Hello world!");</script>

Placed within the <head> it looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dan's website</title>
    <script>
    console.log("Hello world!");
    </script>
</head>
<body>
    <h1>My website</h1>
    <p>Welcome to my website!</p>
</body>
</html>

Placed after the <body> it looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dan's website</title>
</head>
<body>
    <h1>My website</h1>
    <p>Welcome to my website!</p>
    <script>
    console.log("Hello world!");
    </script>
</body>
</html>

Place after the </body> it looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dan's website</title>
</head>
<body>
    <h1>My website</h1>
    <p>Welcome to my website!</p>
</body>
    <script>
    console.log("Hello world!");
    </script>
</html>

As a Separate JavaScript file

This involves writing the JavaScript in an external file to the HTML and then referencing it in the script tag. It looks like this:

<script src="my-JavaScript-file.js"></script>

As you can see the <script></script> tag is not wrapped around anything.

This is OK as you only need to point the browser to the JavaScript file.

Do keep in mind that your path to the .js file will vary depending on its location.

You’ll need to link the file based on its reference to the HTML file.

For example, if the .js file was in a subfolder called Javascript, your path might look like this:

<script src="javascript/my-JavaScript-file.js"></script>

Or, if you were linking a JavaScript file on another website, your path might look like this:

<script src="http://www.danielpuiatti.com/javascript/external-JavaScript-file.js"></script>

Here’s what it would look like placed within the <head>:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dan's website</title>
    <script src="my-JavaScript-file.js"></script>
</head>
<body>
    <h1>My website</h1>
    <p>Welcome to my website!</p>
</body>
</html>

Placed after the <body> it looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dan's website</title>
</head>
<body>
    <h1>My website</h1>
    <p>Welcome to my website!</p>
    <script src="my-JavaScript-file.js"></script>
</body>
</html>

Place after the </body> it looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dan's website</title>
</head>
<body>
    <h1>My website</h1>
    <p>Welcome to my website!</p>
</body>
<script src="my-JavaScript-file.js"></script>
</html>

Which way should I add JavaScript to my website?

The answer is it depends. As mentioned, each of the approaches above has their own use case scenarios.

If you are a beginner and just want to get started, I’d suggest adding your JavaScript after the </body> tag and linking it to an external JavaScript file.

Doing this will ensure that your JavaScript does not interfere with the loading of the webpage and that it has access to the DOM.

The only two exceptions to this suggestion for beginners is the Google Analytics tracking tag, which should be placed in the <head> tag and any JavaScript that has specific instructions about where it should be placed in the HTML file.

Ok, you should now be able to add JavaScript to your HTML file as well as determine the best location to add it.

Next up, it’s time to learn about one of the most powerful concepts in JavaScript. Functions.

Here’s my beginner’s guide to JavaScript functions.

Categories
JavaScript

Writing JavaScript code in your web browser’s developer console

One of the best ways to become familiar with a language is to use it. Lucky for you, you’ve already got everything you need to start using JavaScript.

In this guide I’ll introduce you to the JavaScript console as well as show you how to run some really neat JavaScript in it.

This is probably my favourite part of learning a subject: applying it. It’s where all your learning comes together and where you’ll start seeing practical ways to implement the new skills you’ve picked up.

If you are new to JavaScript and haven’t already done so, I’d recommend you read my beginner’s guide to JavaScript basics followed by Getting started with JavaScript variables before reading this guide.

Otherwise, let’s begin. 

Your console and you

Writing JavaScript is only half the fun of JavaScript — there’s a whole other dimension of problem-solving that only becomes apparent after you try to run your code.

From figuring out why it won’t run to testing cross-browser compatibility and more, you’ll need to consider more than just proper syntax and best practices when crafting your code.

But first, you’ll need somewhere to run your JavaScript.

Luckily for you, every modern web browser comes with a set of developer tools to do just that. These tools allow you to interact with the three front end technologies used to create websites: HTML, CSS and JavaScript.

The specific tool we’ll be focusing on in this guide is the JavaScript console watch allows you to write and run JavaScript right here in your web browser.

Setting up your workstation

Before we start writing some JavaScript let’s take a moment to set up our workspace to make this guide easier to follow.

Open up this page in a new browser window and place it beside this window as demonstrated in the screenshot below.

In the new browser window, follow the instructions below to open your JavaScript console.

Chrome

  • To open the developer console window on Chrome, use the keyboard shortcut Ctrl + Shift + I (on Windows) or Ctrl + Option + J (on Mac).

Safari

  • Follow these steps and then use the shortcut below.
  • Cmd + Opt + C

Edge

  • To open the console on Edge, hit F12 to access the F12 Developer Tools. Once in the F12 Developer Tools, navigate to the Console tab.

Firefox

  • To open the console on Firefox, use the keyboard shortcut Ctrl + Shift + K (on Windows) or Ctrl + Option + K (on Mac). The toolbox will appear at the bottom of the browser window, with the Web Console activated.

You should now see a similar layout to this screenshot below.

Writing JavaScript in the console

Ok, now that we’re all set up, let’s start with something fun. We’re going to teach your web browser what your name is. To do this we’ll need to first declare a variable to store your name. Let’s do that by creating a variable called hiMyNameIs.

Please type the following in your JavaScript console and press enter:

var hiMyNameIs;

Your console should now look something like this:

Now, let’s create a way for you to tell the web browser what your name is. We’ll use a prompt to do this, and we’ll store the value of the prompt in the variable we just created.

Please type the statement below into your console and press enter:

var hiMyNameIs = window.prompt("Hi, what is your name?");

You should get a little popup (called a dialogue box) that asks you for your name.

Go ahead and type your name. When finished, press OK.

Let’s now confirm that your name was stored correctly by calling the named variable we just created. We can do this by using the name we gave the variable.

Please type the statement below in your console and press enter:

hiMyNameIs;

Did you see your name in the console?

Excellent, that means your browser now knows what your name is and you’ve successfully created a variable named hiMyNameIs and assigned a text string (your name) to it.

Well done!

Let’s try something more interesting. Let’s get the web browser to use your name in a greeting.

Type the statement below in your console and press enter:

alert("Hello! " + hiMyNameIs + ", It\'s nice to meet you");

Hopefully, you got a little pop up like in the screenshot below.

Let’s review what happened here.

When you typed alert("Hello! " + hiMyNameIs + ", It\'s nice to meet you"); you told JavaScript you wanted it to perform a function: the alert function.

When you tell JavaScript you want it to perform a function, this is referred to as calling a function. In this instance, you called the alert function which displays a popup dialogue box on the screen.

But how did JavaScript know what to display in the popup dialogue box? Easy. You told it what to display.

The content that follows alert, specifically ("Hello! " + hiMyNameIs + ", It's nice to meet you"); tells the browser that you’d like it to display everything within the () within the alert box.

The content within the () is called a parameter.

In the example:

alert("Hello! " + hiMyNameIs + ", It\'s nice to meet you");

The parameter is

"Hello! " + hiMyNameIs + ", It's nice to meet you"

There is some additional syntax at play with the alert box. Specifically, you’ll notice a few interesting parts of the content within the ().

  • The quotations tell the browser you want it to display text, specifically the text between the two "".
  • The + tells the browser you want to combine the content on either side of the plus symbols.
  • hiMyNameIs tells the browser to use the data stored in the variable named hiMyNameIs.

Notice how you added words together? Pretty interesting right? This is called concatenation and it’s not adding words together, it’s combining them. Try it yourself:

alert("Hello my friend" + "It's very nice to meet you");

Did you notice anything weird? Did you perhaps notice that there was no space between "Hello my friend" and "It's very nice to meet you"?

Well, you should have, because there was no space.

When you are concatenating words in JavaScript you must provide all the characters you’d like JavaScript to combine. This includes spaces.

If you want spaces between words, you’ll need to add them. You can do so by adding the space between the + or at the end of each part of the text you are concatenating.

alert("Hello my friend" + " " + "It's very nice to meet you");

Or, you could do this:

alert("Hello my friend " + "It's very nice to meet you");

By now your console is probably getting pretty full of stuff, let’s clear it out.

Please type the statement below in your console and press enter:

clear()

Let’s have some more fun with the content on the page. Let’s change the word sandbox on the page to jungle.

First, use the document.QuerySelector method to search the page for the ID called #textSelector.

Type the statement below in your console and press enter:

document.querySelector("#textSelector");

Now use the innerHTML method to select the HTML within the #textSelector ID

Type the statement below in your console and press enter:

document.querySelector("#textSelector").innerHTML;

Now set the innerHTML of the #textSelector ID to the text "jungle"

Type the statement below in your console and press enter:

document.querySelector("#textSelector").innerHTML = "jungle";

Pretty cool right? We used a querySelector to select a specific part of the HTML and then change it.

Manipulating HTML with JavaScript is incredibly powerful. But this is only the beginning. So far we used two actions that come by default with JavaScript. But there’s more to JavaScript than the actions that come with it.

That’s right, you guessed it. You can create your own actions, with your own set of instructions, that you can run whenever you like. You are not limited to the actions predefined by JavaScript. These custom actions are called functions, and we’ll be covering them with my next guide.

But first, let’s explore how to add JavaScript to your website.

Categories
JavaScript

JavaScript basics: syntax, semantics and best practices

JavaScript is the most powerful of the three front end technologies and is an essential component of every modern website.

If you are considering a career in digital media, web development, online marketing or are just interested in learning something — learning JavaScript will change your life. Not only will you uncover how to leverage the power of computing to become more efficient, accurate and useful at work, but along your coding journey you’ll also unlock new ways of thinking that will help you solve problems, learn faster, meet new people and contribute to world-changing open-source projects.

But first, you’ll need to learn how to read JavaScript. This post will help you do just that. Specifically, it will focus on syntax, semantics and best practices

If you are just getting started or if you’ve followed the traditional learning path for web development you’ve probably already familiarized yourself with HTML and CSS. If not, I’d strongly suggest doing that before you begin learning JavaScript. Here’s my beginner’s guide to HTML and the consecutive beginner’s guide to CSS. You should at very least be familiar with the aforementioned guides before you read this guide.

Trust me, it’ll make your learning experience much easier.

Anywho, let’s get started.

Your web browser speaks JavaScript

Your web browser is a program and programs only understand certain languages. One of the languages your web browser understands is JavaScript.

Just like English, JavaScript has rules about how it must be written. Sentences for example, in English, start with a capital and usually end with punctuation. These rules are called the syntax of the language.

Below are the rules you must follow when writing instructions to your web browser in JavaScript.

Understand them and you’ll understand how to read JavaScript. 

JavaScript syntax

A program is a series of written instructions written in a programming language. In JavaScript, every line of instruction is called a statement.

This is what a statement looks like in JavaScript:

alert("Hello World!");

Multiple statements create a program:

alert("Hello World!");
console.log("Hello Console!");

There are many statement types in JavaScript, each with their own nuanced usage and syntax. As an introduction, we’ll focus on a simple statement that creates, names and assigns data to a variable. This what that looks like:

var helloWorld = "Hello World!";

The statement above creates a variable, names the variable helloWorld and then assigns some text data "Hello World!" to the variable.

Let’s break down the component parts of this statement further.

The statement above is comprised of five parts:

  1. the variable var
  2. the variable name helloWorld
  3. the variable assignment operator =
  4. the data assigned to the variable "Hello, world!"
  5. the closing semicolon ;
  1. When you start a statement with the word var it tells JavaScript that you’d like to create a variable. A variable is used to store data.
  2. helloWorld is the name you choose for the variable you just created. You cannot use var alone to create a variable, you must assign the variable a name. This name is what you’ll use to reference the variable.
  3. The assignment operator = assigns data to the named variable you created in 1 and 2. The = tells JavaScript to assign the data on the right of the = to the named variable on the left. The = does not mean the content to the left of the = is equal to the content on the right. 
  4. This is the specific data assigned to the variable helloWorld. In this case the data is some text that says "Hello, world!". This data can now be accessed by typing helloWorld in the JavaScript console.
  5. The closing semicolon ; denotes the end of the statement. It tells your browser that anything after the semicolon is no longer part of the same statement.

Let’s try to rework the example above to demonstrate the concepts.

If I wanted a different name for my variable I’d write this:

var learningJavaScript = "Hello World!";

If I wanted to assign different data to my variable I’d write this:

var learningJavaScript = "I'm learning JavaScript!";

Now that we’ve broken down the components of a statement, let’s explore the syntax rules used when constructing statements. Knowing these will allow you to read JavaScript and write it appropriately.

JavaScript rules

JavaScript is case sensitive

If you accidentally use a capital or a lower case when the program is expecting the opposite, the program will not run.

  • var not Var
  • console.log not Console.Log

This also applies to variable names. If you name something helloWorld then HelloWorld will not work.

Explicitly named variables and camelCase

JavaScript developers have adopted two styles that have become standard best practices for the JavaScript programming language: explicit variable names and camelCase.

Explicitly named variables

When naming your variables, try to be as explicit as possible about what this variable is when choosing a name.

Do this:

var websiteWelcomeMessage = "Hello, welcome to my website!";

Not this:

var x = "Hello, welcome to my website!";

camelCase

Always write your variable names in camelCase.

Do this:

var helloWorld = "Hello World!";

Or this:

var helloWorldLongerExample = "Hello World!";

Don’t do this:

var helloworld = "Hello World!";

Or this

var Helloworld = "Hello World!";

Semicolons end statements

Just like in English, JavaScript uses a punctuation mark to denote the end of a statement. Always use a semicolon ; to end a JavaScript statement.

Do this:

var helloWorld = "Hello World!";

Not this:

var helloworld = "Hello World!"

Each statement should be on its own line

To keep your JavaScript easy to ready and easy to maintain you should always write every statement on its own line.

Do this:

var helloworld = "Hello World!"; 
var websiteWelcomeMessage = "Hello, welcome to my website!"; 

Not this:

var helloworld = "Hello World!"; var websiteWelcomeMessage = "Hello, welcome to my website!"; 

JavaScript is the most powerful of the front end technologies because it can understand extremely complex instructions, unlike HTML or CSS. Complex instructions require precise and accurate instructions. Just like a human language!

One of the best ways to become more familiar with JavaScript syntax is to learn how to declare variables and assign value to these variables

My guide to getting started with JavaScript variables is the perfect place to start.