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:

A screenshot demonstrating JavaScript arrays.

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:

A screenshot demonstrating JavaScript arrays.

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?

A screenshot demonstrating JavaScript arrays.

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

A screenshot demonstrating JavaScript arrays.
A screenshot demonstrating JavaScript arrays.

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:

A screenshot demonstrating JavaScript functions.

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, 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 statement 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:

A screenshot demonstrating JavaScript functions.

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:

A screenshot demonstrating JavaScript functions.

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 from 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 which 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://159.203.35.169/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 its 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 favorite 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 the 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:

A screenshot demonstrating the JavaScript developer console.

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.

A screenshot demonstrating the JavaScript developer console.

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!

A screenshot demonstrating the JavaScript developer console.

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.

A screenshot demonstrating the JavaScript developer console.

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 text on the page to I love JavaScript!

First, use the document.QuerySelector method to search the page for the ID called #site-content.

Type the statement below in your console and press enter:

document.querySelector("#site-content");

Now use the innerHTML method to select the HTML within the #site-content ID

Type the statement below in your console and press enter:

document.querySelector("#site-content").innerHTML;

Now set the innerHTML of the #textSelector ID to the text "I love JavaScript"

Type the statement below in your console and press enter:

document.querySelector("#site-content").innerHTML = "I love JavaScript";

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 in 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, or 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 the 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 its 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 is 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 lowercase 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 read 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.

Categories
CSS

CSS basics: syntax, semantics and best practices

CSS makes webpages unique — it allows web developers to tailor their page to stand out from the millions of other websites on the internet.

CSS brings webpages to life — it allows web developers to animate and transform the page, to give it vitality and a sense of energy.

CSS makes webpages responsive — it allows web developers to ensure the page looks as intended on an innumerable number of screen sizes: from tablet to smartphone, desktop to kiosk display.

And in a world where websites users expect a website to be unique, seamless, visually interesting and responsive — an understanding of CSS is essential for any aspiring web developer.

This post will help you understand how to read and write CSS. Specifically, it will focus on syntax, semantics and best practices.

If you are just getting started with web design and development and are not familiar with HTML I’d strongly suggest familiarizing yourself with HTML before you read this post.

Otherwise, let’s begin.

A world without CSS

Have you ever seen a website without CSS? It’s pretty bleak. Utilitarian even. I don’t recommend it. In fact, I recommend against it.

But you…

You are curious — aren’t you?

Yes, you are.

Ok then. But don’t say I didn’t warn you.

The Horror of unstyled HTML

That was awful right? I hope you didn’t spend too long there.

What you were looking at was pure HTML without any custom CSS. Every browser has a default style sheet that it will use when it cannot locate any custom styles. This is the default CSS.

Default CSS is ugly. Don’t use default CSS.

How do you make sure your website doesn’t use default CSS? How do you make your website look nice? Like this one, for example?

I’ll tell you how.

But first, a little bit of information about how much work goes into making a website look nice.

When you visit a website that looks nice. Like this one! Your browser reads through many lines of custom CSS to determine how each thing on the page should look.

There is literally a style that someone had to write for almost everything on this page.

From the colour of the text to the size of characters, the spacing between paragraphs to the height between lines. It is all meticulously and lovingly written CSS.

Perhaps you never realized how much attention to detail, testing, and rewriting was required to make a site look so good (yes, like this one!).

Here’s a screenshot from the CSS file for this website to illustrate.

There are over 6000 lines of CSS on this webpage!

But isn’t it worth it? Especially after that nightmare, you encountered above.

It’s worth it.

So, if you want to understand why your website looks the way it does, and if you want to learn how to make it look the way you want, then you’ll need to understand how to read CSS.

CSS syntax

CSS consists of rule-sets that provide instructions to the browser about how to style an element.

This is a rule set for a paragraph element:

p {
color: red;
text-align: center;
}

Rule-sets contain four parts:

  1. a selector 
  2. a declaration block 
  3. the property 
  4. the value

Here’s how this applies to the example above.

  • the selector: p
  • the declaration block: everything contained within { }
  • the property: color:/ text-align:
  • the value of the property: red;/center;

The p in this rule-set tells the browser that every HTML p element should have the colour of red and should have center alignment.

In other words, the selector references the element you’d like to style. The declaration block contains the styles you’d like to apply to the element. And the property/values provide the specific styles to use.

Like HTML, CSS has specific syntactic rules that must be followed. When this syntax is followed a browser can correctly determine which element to apply the style to and what the properties and values of this style are.

For example:

This is a rule-set:

p {
color: red;
}

This is not a rule-set: 

p {
color: red;

This is not a rule-set:

p color: red;
}

This is not a rule-set:

{ p
color: red;
 }

CSS Rules

Case Sensitivity

CSS is and is not case-sensitive.

When you are writing which element you’d like to select you can use either uppercase or lowercase. But you should always use lowercase.

Example:

Do this:

p {
color: red;
}

Not this:

P {
color: red;
}

Even though uppercase and lowercase are interchangeable, you should always use lowercase.

The only time when case matters is when you are selecting an element with an id or class that has a name that uses uppercase and lowercase.

For example, if you wanted to style the HTML elements below.

<p id= "customElementByID">My element ID</p>
<p class= "customElementByClass">My element class</p>

And you wanted to select the elements by their class instead of their tag type, then case sensitivity matters.

By ID do this:

#customElementByID {
color: red;
}

Not this:

#customelementbyid {
color: red;
}

By Class do this:

.customElementByClass {
color: red;
}

Not this:

.customelementbyclass {
color: red;
}

CSS can have many properties and values within the declaration block. Every property value should be written on its own line and end with a semicolon

Do this:

p {
color: red;
size: 20px;
}

Not this:

p {
color: red; size: 20px
}

You can apply the same style to many selectors

For example:

h1, h2, h3, h4, h5 {
size: 200px;
}

CSS cascades

One of the most important rules of CSS is that it cascades.

If you have multiple styles targeting the same element, the style that is closest or most specific to the element will apply.

For example, if I select the same p element twice, once with the p tag selector and once with the id tag selector, the style using the id tag will be used.

Here’s what that would look like. Imagine this is the element I’m trying to style:

<p id="introParagraph">This is my intro paragraph</p>

Imagine I wrote the two CSS rule-sets below:

p {
color: red;
}
#introParagraph {
color: blue;
} 

The second rule-set, with the #introParagraph id selector will be applied and it will overwrite the color: red of the p and replaces it with color:blue.

Cascading may be a bit confusing but don’t get caught up on this for now as I’ll cover it in greater detail in another blog post. Just keep in mind that the closer in proximity a CSS rule-set is to the element it’s trying to style, the more likely it will be applied.

There are many CSS property value combinations, each with varied nuances about how they act and display on the page. w3schools schools have a handy CSS reference available, I recommend taking a moment to read up on the various types.

Ok, I hope this post will help you understand how to read CSS and that you now have a better grasp of CSS syntax, semantics, and best practices.

Next up, I suggest you start moving on to the most exciting aspect of front-end web development: JavaScript.

Here’s my guide to JavaScript basics: syntax, semantics, and best practices.

Categories
HTML

HTML basics: syntax, semantics and best practices

HTML is in many ways the most important of the front-end languages used to build websites (HTML, CSS, and JavaScript). Not only does it provide the architectural blueprints for how your site is structured, but it also tells your web browser what each content type on the page is (lists, headings, pull quotes, etc.).

This post will help you understand how to read HTML. Specifically, it will focus on HTML syntax, semantics, and best practices.

HTML stands for HyperText Markup Language which basically means versatile text. And it is versatile — more versatile than text you read in a book, at least. And it has many features that standard book text cannot provide: links are one of these.

Links look something like this in HTML:

<a href="www.danielpuiatti.com" target="_blank">This is my website!</a>

You are probably familiar with some parts of the HTML link above. I’m certain you recognize the URL part: www.danielpuiatti.com. But what about the < > and </a> or the target=“_blank”, what’s that doing?

To read HTML you must understand its syntax. These aforementioned parts of the link make up its syntax.

What’s syntax?

It’s how to properly structures sentences in a written language. From punctuation to capitalization, the proper syntax allows you to easily understand a sentence.

Here’s an example of incorrect English syntax:

.hellO nice to Meet yoU

The structure of the sentence above is syntactically wrong. The period is at the start when it should be at the end, and there is random capitalization strewn about. These errors make the sentence difficult to read.

To be syntactically correct it should look like this:

Hello nice to meet you.

Whether English or Inuktitut, every written language has syntax. HTML included. Without correct syntax, a browser cannot properly read your HTML.

HTML syntax

For HTML, syntax relies on tags. These tags wrap around content and when the syntax is correct it allows the browser to

  1. determine what the content is
  2. understand the meaning of content.

In other words, meaning (semantics) and type are derived from the browser’s ability to understand tags, and it can only understand tags if they are semantically correct.

Let’s look at an example.

This is an example of a paragraph tag wrapped around some text:

<p>This is a paragraph, hooray!</p>

When the browser looks at the example above it reads the opening <p> tag and thinks to itself: “Ah-ha! This is the start of a paragraph, the content within this tag should be presented and structured as a paragraph.”

The browser then moves through the content until it reaches the closing </p> tag at which point it says: “Ah-ha! This is the end of the paragraph. I’ll conclude by presenting the content within as a paragraph and look for what tag is next.”

Every paragraph on this page, even this one right now, is wrapped in paragraph tags.

HTML from this page

Notice that every paragraph has three distinct parts:

  1. the opening tag: <p>
  2. the closing tag: </p>
  3. the content within the tag: This is a paragraph, hooray!

The correct syntax for a paragraph in HTML is an opening and closing tag wrapped around some content.

When this syntax is correctly written it is referred to as an element. Elements allow the browser to determine the type of content on the page and also help it to derive the meaning of the content (semantics).

This is a paragraph element: <p>Hello world!</p>
This is not a paragraph element: <p>Hello world!
This is not a paragraph element: Hello world!</p>
This is not a paragraph element: <p></p>

HTML Rules

HTML is not case sensitive

<p>This is a paragraph, hooray!</p> is the same as:<P>This is a paragraph, hooray!</P> is the same as
<p>This is a paragraph, hooray!</P> is the same as
<P>This is a paragraph, hooray!</p> is the same as`

It’s extremely bad form to use uppercase, and absolutely no one mixes capitals with lowercase.

My suggestion is to always use lowercase, otherwise, developers will look at you funny.

HTML tags must have the correct syntax

The examples below will not work:

<p>This is bad HTML
<p>This is also bad HTML</p
`<p>This is bad HTML<p>

Tags on their own are sort of meaningless, but when wrapped around content, like in the example above, they tell the browser: “Hey! Browser! Listen up, this is a paragraph! So you should make it look and act like a paragraph”.

The browser has no choice but to obey the instructions HTML gives it, and as such, displays and lets you interact with it as a paragraph.

HTML tag attributes

HTML tags can have attributes. These provide additional information about an element.

Attributes are always specified in the start tag and come in name/value pairs like target=“_blank”. Where target is the name and _blank is the value.

Here’s an example of a link with attributes:

<a href="www.danielpuiatti.com" target="_blank">This is my website!</a>

Here’s an example of a list with attributes:

<ul style="list-style-type:disc;">
<li>List item one</li>
<li>List item two</li>
<li>List item three</li>
<li>List item four</li>
<li>List item five</li>
</ul>

Attributes are always wrapped in quotes and must be contained within the start tag. These examples will not work:

<a href="www.danielpuiatti.com">My site <target="_blank" />
<a href="www.danielpuiatti.com" target=_blank>My site</>

Tag types

Since there are multiple content types on a website (paragraphs, lists, titles, links, etc.) you must wrap your content in tags for the browser to understand what each one is, otherwise, it has no way to know which is which. For example:

This content is a paragraph.

  • This content over here?
  • It’s different from the paragraph!
  • It’s a list!

And this? It’s a blockquote!

There are many HTML tags, each with a specific semantic meaning and proper syntax. w3schools has a fantastic guide on HTML tags. I recommend taking a moment to read up on the various types, some good ones to get started with: are lists, links, headings, and paragraphs.

Ok, I hope this post will help you understand how to read HTML and that you now have a better grasp of HTML syntax, semantics, and best practices.

Here’s a handy image I found that brings everything together from this post.

Image result for html element syntax
source: Wikipedia

If you are ready for the next step, I’d suggest reading my beginner’s guide to CSS basics: syntax, semantics and best practices.

Categories
Marketing

Reaching your target audience with content marketing

This is the third installment of my building a brand from scratch series. It focuses on reaching your brand’s target audience. This series is most effective when read in sequence. Here’s the first part of the series if you’d like to start from there.

Any seasoned brand-builder will tell you that knowing your target audience is not enough. You must also reach them. And if you can consistently reach them, then you are well on your way to building a brand.

After I had defined my target audience’s demographics and psychographic characteristics with help from the Facebook Audience Insights tool, I started to think about how to put this information about my target audience to work.

I needed a way to reach my target audience that was affordable, sustainable, and expandable.

The most obvious application was content marketing.

Content Marketing? What’s Content Marketing?

“Content marketing is a strategic marketing approach focused on creating and distributing valuable, relevant, and consistent content to attract and retain a clearly defined audience — and, ultimately, to drive profitable customer action.”

Content Marketing Institute

In other words, if you are creating blogs, photos, videos, podcasts or social media posts with the goal of getting the attention of your target audience you are content marketing.

How does the content you create help get attention for your brand?

Think of a social media feed. Think of how content appears in the feed. Usually, it’s something like this:

Notice what’s attached to the content in the feed: a profile. Often, a brand profile.

So if people are paying attention to your content, they are paying attention to your brand. And if you are creating content to get the attention of your target audience, then you are content marketing.

How you can start content marketing

As mentioned there are many ways to do content marketing: blogs, photos, videos, podcasts, social media posts, etc., and each of these methods has its own pros and cons. My approach uses images and is built on three proven business principles: easy, affordable, and expandable.

Images are the time-tested favorite as they meet all three of the above criteria and the process I use is the result of hundreds of hours of building brands from scratch and developing content marketing processes. If you follow my approach to content marketing I guarantee you will save time, money, and a good deal of sanity.

But how do I make content that my audience will think is awesome?

The demographic and psychographic information Facebook Audience Insights tool revealed about your target audience in part two will help you make content that your audience will think is awesome.

We’ll use my t-shirt brand Danskii (now defunct) as an example.

For Danskii my target audience is composed of 25-34-year-old females with a college education and a preference for travel and photography.

So… how do I use this information to do that?

Hmm.

Travel and photography…

Travel and photography?

Travel and photography!

Bingo.

Here’s how I make content to get my audience’s attention. I’ll need to create images that focus on travel.

Ok, so admittedly figuring out what will appeal to your target audience step is always pretty easy.

Creating photos that appeal to your target audience is where the real work comes in.

Lucky for you I’m going to outline exactly how to do this.

Categories
Marketing

Starting a brand from scratch

The first step to building a brand from scratch is failure.

At some point in December 2017, I decided I would try and sell products online. Real original, I know.

I think the idea took hold when I came across a Shopify advertisement promoting something called drop shipping as a way to generate income through eCommerce.

The idea Shopify advertised was seductively simple.

First, you start up a trial eCommerce store with Shopify. Second, connect your eCommerce store to an automated dropshipping product, and finally, run some ads to drive traffic to your store and watch the money roll in.

Some money did roll in, but it was far less than was rolling out.

I had no financial success with Shopify, but failure imparts its own value.

I had attempted to break into a market that was over-saturated with bigger and better product providers. Competing with the likes of Amazon and Ali Express provided too monumental a task.

Amazon and Alibaba are leading the world-wide e-commerce revolution, according to a study from Website Builder Expert (WBE). In their study, WBE mapped out the world’s top online marketplaces. By geographically outlining the top online marketers, the power struggle for e-commerce domination becomes clear.

Tech Republic

Nevertheless, I was optimistic that I might still be able to develop a profitable eCommerce business. So I started to consider some alternative products and approaches: baby product reviews, pet food newsletters, trading cards forums, you name it.

Almost every niche product has a market and a blog trying to convince you to monetize it.

However, with so many providers offering the same product I would need to rely on a different value proposition. Instead of better prices, faster shipping, or a sophisticated eCommerce system, I would need to develop a following of people who liked the idea of my business. I would need to develop a brand.

So…

I built a website from scratch to accompany this brand: Danskii.com (now defunct).

I integrated analytics, marketing, and business intelligence tools: Google Analytics, HotJar, and MailChimp. I set up social media profiles. 

Next, I needed to figure out who my target audience was and then convince them to follow me.

Categories
Marketing

Identifying your target audience

This is the second installment of my building a brand from scratch series. It focuses on reaching your brand’s target audience. This series is most effective when read in sequence. Here’s the first part of the series, starting a brand from scratch, if you’d like to start from there.

Whether you are selling high-end shoes, making dog yoga videos or writing about how you built a brand from scratch, knowing your target audience is absolutely essential.

I was feeling pretty good after completing my website and setting up the Instagram account for my t-shirt company.

There’s nothing as self-gratifying as the feeling of pulling up your new website and showing it off to your friends.

There’s also nothing quite like the feeling of knowing no one else is seeing it. 0-traffic-itis is painful. And since website visitors don’t manifest from the ether, I needed to start thinking about building traffic.

My target audiences

When I began my dropshipping business in December of 2018 I relied primarily on advertising to drive traffic. This worked just fine for sending people to my website and provided an added bonus of this really cool upward trending line.

But that upward trending line was the only thing the advertising did.

One of the major reasons for my initial dropshipping business failure was that I had not identified a target audience early enough.

This mistake caused my content and advertisements to be far too generic when they should have been tailored to a specific group of people.

I learned, through trial and error and many hours of research that the more tailored to an audience your content and advertising is, the more effective it will be.

The realization of my failure to effectively define a target audience crept up on me slowly.

While I had people visiting my site, the majority were not doing anything of value. No sharing, no shopping, nothing. Worse, I was burning through money at an alarming rate.

As you can imagine, my untargeted approach got very expensive very fast. And the results were minimal.

“One of the biggest mistakes that budding personal branders make is trying to appeal to everyone. Think about the game of darts: You have to aim in order to hit the board. (If you let your darts go without aiming them, you probably won’t be very popular.) If you hit the board, you score. And if your aim is very good and you hit the bull’s eye, even better!”

Quicksprout

However, advertising on Facebook introduced me to a unique and incredibly powerful tool: Facebook Audience Insights

Audience Insights was created by Facebook to allow advertisers to tap into the nearly infinite supply of demographic data that Facebook collects from every user: age, gender, occupation, likes, income, you name it.

“The more customer insights you have, the better you’re equipped to deliver meaningful messages to people. That’s the thinking behind Facebook Audience Insights, a new tool designed to help marketers learn more about their target audiences, including aggregate information about geography, demographics, purchase”

Facebook Audience Insights

Facebook Audience Insights

The Audience Insights tool was exactly what I needed to identify my target audience for my fledgling t-shirt company.

Here’s how I used the tool to do just that.

  1. Login to Facebook
  2. Navigate to the Audience Insights tools
  3. Think of a brand which is similar to your own (the brand you select must also have a Facebook page for this to work)
  4. Under the interests text input, type the brand name
  5. Make note of the details which have the highest percentages for each category:
    • Gender
    • Age
    • Relationship Status
    • Education Level
    • Page Likes
    • Location
    • Device Users

After spending some time with the Audience Insights tool, I eventually landed on a brand that was similar to my own.

After reviewing the brand, via the process listed above, I was able to quickly access an extremely detailed set of demographic data about my target audience. This was pure gold as it now gave me the information I needed to start tailoring my content.

“The more customer insights you have, the better you’re equipped to deliver meaningful messages to people…”

Facebook Audience Insights

So there it was, I had discovered my target audience and completed one of the most important steps to building a brand.

Now it was time to figure out how to reach them.