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 HTML JavaScript

How a web browser builds a website

If you want to learn how to build websites, program in JavaScript, become a front end web developer or are just genuinely curious about how websites work  —  you need to understand how a web browser (browser) builds a website.

This post will help you do just that.

Have you ever read something online? I’m willing to bet you have. Was it a news article or a long-form travel story? A Wikipedia article or maybe a serialized choose your own adventure Harry Potter fan fiction? Perhaps it was this very blog post?

Regardless, do you remember when it was written and what it was about? Do you remember how it looked and who wrote it? Or, better yet, can you tell me what wrote it?

That’s right, what.

Not sure? Here’s a hint: when you look at a blog post, news article, or any written content on your browser you are looking at the end result of a set of precisely followed instructions. These instructions tell your browser how to build, present and interact with the content on your screen. So, in answer to the question, your browser is the what. The who, I’ll leave to you.

The how? The precisely followed instructions!

These instructions come in three flavours: HTML, CSS and JavaScript, each of which contains directions that your browser follows to build a webpage. Coincidentally, someone who specializes in the three aforementioned technologies is called a front end developer or a web developer (I guess I didn’t leave the who to you after all).

Let’s take this one step further by using an analogy.

Imagine for a moment that your browser is a construction worker who needs to build a house. The house, in this case, is a website, and HTML, CSS and JavaScript are the blueprints for different parts of the house: the architecture, the style and the interactivity.

HTML (hypertext markup language)

This is the architecture of your house — it tells your browser how to organize the content on the page and what that content is.

It also tells your browser where it can find the other resources necessary to finish building the page, specifically the location of the CSS and JavaScript files. 

HTML is the first thing a browser reads when building a website and while it has has a specific initial structure, this structure can be expanded, reduced or transformed by CSS and JavaScript, in the same way you can add rooms, remove them or transform them on a blueprint. A kitchen can become a living room after all — especially on a blueprint.

HTML tells your browser the semantic meaning of the content on your website. This is similar to a legend on a map. Without this legend, your browser would not be able to distinguish the difference between content types on your web page (paragraphs, lists, titles, etc.). Consequentially, without this legend, your brows would not be able to correctly assign the styles and behaviours that distinguish one content type from another. You don’t want your lists displaying as paragraphs, do you?

In other words, HTML provides a reference so the browser can understand what the content is:

That content is a paragraph.

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

HTML provides the distin level of detail so your browser can distinguish the content types.

For these reasons, I like to think of HTML as the architectural blueprint of your house.

CSS (Cascading Style Sheets)

This is the style of your house  —  from the carpet to the curtains, wallpaper to shingles, CSS is responsible for telling the browser how your web page should look and, if you desire, how it should transform.

CSS builds upon the architecture which HTML provides and references it to know which items it needs to apply styles to. Things like colours, spacing, animation and layout are controlled by CSS — without it, your webpage is boring.

Progressively, after the HTML is loaded, your browser then consults with CSS to understand how it should style all of the architecture laid out by HTML. Specifically, your browser references CSS to determine what the content defined in HTML should look like.

Everything from how the page should look on a phone, tablet or laptop to the colour of text, the spacing between lines and, as mentioned, the animation is provided by CSS.

For these reasons, I like to think of CSS as the style blueprint for your house.

JavaScript

This is the interactivity of your house — from when the lights should turn on to when the thermostat should lower, what time your alarm clock goes off to what temperature your oven should pre-heat to.

If it’s something that you can interact with, it’s probably governed by JavaScript.

Like CSS, JavaScript builds upon the architecture that HTML provides, and after the architecture of your house is built and styled, JavaScript goes to work defining what can be interacted with and how.

JavaScript governs interactions through event triggers and outputs:

An event trigger is something that needs to happen before an output can take place. JavaScript can tell your browser to listen for a specific event trigger (perhaps a click or a scroll), and when this trigger takes place, to perform a specific action.

An output is the action that happens after the trigger is activated. For example, let’s say someone pressed the doorbell at your house (event trigger) the output would be the specific sound that plays. Another example: you turn your stove on. The temperature which it rises to before turning off is the output.

Like cause and effect — the web browser equivalent is JavaScript — and through event triggers and outputs, JavaScript brings interactivity to your page. And interactivity is an absolutely essential component of modern websites

For these reasons, I like to think of JavaScript as the blueprint for the interactivity of your house.

Wrapping it all up: HTML, CSS and JavaScript

  • HTML is the architecture
  • CSS is the style
  • JavaScript interactivity
  • Each of these technologies makes up the front end of your website and each is essential to what most users expect from a modern website.
  • Your web browser follows the blueprints laid out in HTML, CSS and JavaScript to determine how to build a webpage, how this webpage should look and how you’ll be allowed to interact with it.
  • Someone who specializes in these technologies is called a web developer or front end developer.

So, hopefully after reading this post you now feel more familiar with how your browser constructs a web page.

Next, it’s time to learn about HTML, the most important part of a website.

Categories
JavaScript

Beginner’s guide to JavaScript variables


One of the most useful capabilities of JavaScript is that it lets you manipulate almost anything on a webpage, even if you don’t have access to the HTML or CSS.

What’s the use of manipulating something on a webpage? Well, if you can manipulate something on a webpage you can change the webpage. 

Need to build an email form to collect emails for your event? Create an image gallery that allows people to share your pictures? Make the page dance, sing, and be merry?

Whatever you need to do, you can almost always do it with JavaScript. This is why it’s one of the most popular programming languages today, its versatility and flexibility allow you countless opportunities to change a website as you desire.

When programming with JavaScript you will inevitably be interacting with data, usually, but not always, you’ll be trying to change this data somehow.

Here’s an example of a data interaction with JavaScript: think of a news website that publishes stories about apartments. Perhaps they have a style guide that says every time the words “tenant association” appears they should be capitalized.

Let’s say the news website also works with hundreds of writers and not all of these writers remember to capitalize tenant association.

In this instance, as a savvy JavaScript programmer, you’d want to use JavaScript to automatically capitalize tenant association every time it appears on your webpage, regardless of if the writer remembers to or not.

In this example the words “tenant association” are data (text data is called a string in JavaScript) and uppercasing the words is a form of interacting with the data, specifically changing it. 

Before you can interact with data in JavaScript you’ll need to store it somewhere and provide a reference to it. To store data and reference it you’ll use something called a variable.

Variables are one of the most frequent tools you’ll be using as a JavaScript programmer and they allow you to store data and reference it. While there are many reasons why you must do this, for the sake of keeping things simple you’ll have to take my word for it.

Storing data and creating a reference to it in JavaScript is called declaring a variable and variables are, as mentioned, one of the core building blocks of JavaScript programming.

There are three parts to creating a variable in JavaScript: creating and naming the variable, assigning some data to the variable, and referencing the variable.

Creating and naming the variable

To create and name a variable in JavaScript you use the following syntax.

var nameOfVariable;
  1. var tells JavaScript that you want it to create a new variable.
  2. nameOfVariable tells JavaScript the name you want it to assign to the new variable.

All JavaScript variables must be given a unique name, and generally, the rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs
  • Names must begin with a letter
  • Names can also begin with $ and _ (this is not recommended)
  • Names are case sensitive (y and Y are different variables)
  • Reserved words (like JavaScript keywords) cannot be used as names
  • camelCase is preferred
  • Try to be descriptive when naming your variables. This makes your code easier to read. 

Try following the steps below to create a variable named myVariable in your browser console now. If you need some help accessing your browser console this guide will show you how.

  1. Navigate to your browser’s JavaScript console
  2. Type var myVariable in the console window
  3. Press enter

You should see something similar to this:

Congratulations, you’ve just created your very first JavaScript variable.

This may seem trivial, but it’s one of the most important steps in JavaScript programming, and now that you’ve created your variable it’s time to assign some data to it.

Assigning data to the variable

To assign data to the variable you just created using the following syntax:

var nameOfVariable = data;
  1. var tells JavaScript the name you want it to assign to the new variable.
  2. nameOfVariable tells JavaScript the name you want it to assign to the new variable.
  3. = tells JavaScript to assign everything to the right of the = to the variable. This is called an assignment operator.
  4. data tells JavaScript the specific data you want to assign to the variable.

Try following the steps below to assign the word "Hello" to the variable you created called myVariable.

  1. Navigate to your browser’s JavaScript console
  2. Type var myVariable = "Hello" in the console window
  3. Press enter
  4. Type myVariable (without the var this time)
  5. Press enter

You should see something similar to this:

Congratulations again, you’ve just assigned data to your very first JavaScript variable.

In this case, you’ve assigned a string to myVariable.

You are now well on your way to using JavaScript to do some incredible things. And just so you know, you can assign more than strings to variables. Data types can also be numbers, boolean, null, undefined, and symbol.

This guide from W3C provides an overview of datatypes in JavaScript.

Referencing the variable

When you named your variable a few moments ago you created a way to reference it, and referencing it makes changing the data stored within it much easier.

Referencing your data in JavaScript is pretty straightforward, you just use its name. Try the following example in your browser console to reference your variable:

  1. Navigate to your browser’s JavaScript console
  2. Type var myVariable = "Hello" in the console window
  3. Press enter
  4. Type myVariable (without the var this time)
  5. Press enter
  6. Type alert(myVariable)

You should see something similar to the screenshot from the previous step with one difference: a popup should appear that says "Hello".

What happened here? Magic!

When you typed alert(myVariable) you told JavaScript you wanted it to create a popup with the text "Hello", but instead of writing "Hello" you referenced the variable you created with the name myVariable.  In essence, the name you give to a variable with data is the data, and using named variables helps you add meaning to your code, and keeps it cleaner and easier to manage. 

Here’s another example, imagine you wanted to calculate the age of someone born in 1950. Without a named variable you’d do the following:

2020 - 1950 = 70;

Now imagine you had ten different age calculations. You’d have to write something like this:

2020 - 1950 = 70;
2020 - 1954 = 66;
2020 - 1990 = 30;
2020 - 1967 = 53;
2020 - 1989 = 31;
2020 - 1988 = 32;
2020 - 2001 = 19;
2020 - 2004 = 16;
2020 - 1963 = 57;
2020 - 1999 = 21;

As you can see, there’s lots of repetition and by using a named variable you can greatly simplify this process. Here’s what the above looks like using a variable named currentYear.

var currentYear = 2020;
currentYear - 1950 = 70;
currentYear - 1954 = 66;
currentYear - 1990 = 30;
currentYear - 1967 = 53;
currentYear - 1989 = 31;
currentYear - 1988 = 32;
currentYear - 2001 = 19;
currentYear - 2004 = 16;
currentYear - 1963 = 57;
currentYear - 1999 = 21;

At first, it may seem odd to subtract a word from a number, but remember, you are actually subtracting data, the words are simply the reference you gave to the data through a variable. 

Don’t get caught up on the example above which is very simple and not a great use case for variables, it’s only an example. The real magic of named variables becomes evident when you are dealing with thousands of lines of code. 

Go ahead and try subtracting two named variables in your console.

  1. type var currentYear = 2020;
  2. press enter
  3. type var yearOfBirth = 1950;
  4. press enter
  5. type currentYear - yearOfBirth;
  6. press enter

You should see something similar to this:

Pretty cool, right?

Alright, so now you know how to create, name, and reference variables. Here’s a recap to help you solidify your understanding of JavaScript variables.

Recap

  • When programming with JavaScript you will often be interacting with data
  • Before you can interact with data in JavaScript you’ll need to store it somewhere and provide a reference to it
  • To store data and reference it you’ll use a variable.
  • Variables allow you to store data and reference it
  • To create and name a variable in JavaScript you use the following syntax.
    • var myVariable
  • To assign data to the variable use the following syntax
    • var myVariable = “Hello”

Now let’s learn how to start applying what we’ve learned so far. Let’s write and execute some code in our JavaScript console!

Categories
JavaScript

Why should I learn JavaScript?

Learning to program in JavaScript has been one of the most interesting decisions of my life.

Almost every day I find something that can be improved with a few lines of code, and the more I learn how to code, the more I realize how many things I have been doing inefficiently. 

If you are considering a career in digital media, web development, online marketing or are just interested in learning something — learning to program 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.

Sounds great, right? Well, it is pretty great! Except…

Programming is not something you can pick-up in a few days with a crash course (trust me, I have tried plenty of crash courses). It takes commitment — and the learning curve can be unforgiving.

So, to ensure the best use of your time you’ll want to start with a programming language that is:

  • Well documented: meaning lots has been written about how to use it to solve problems.
  • Widely used: meaning many websites use the programming language and it’s likely to be around for a long time.
  • Easy to apply: meaning you don’t need any fancy or expensive software to get started.

JavaScript is well documented

One of the challenges of learning something new is figuring out the stuff that your guide or tutorial didn’t tell you.

Classes and textbooks are wonderful, but none are complete on their own, so having access to extensive collections of writing, tutorials, and guides that cover everything from practical application to theoretical concepts is extremely helpful.

The JavaScript category on Stack Overflow — the most widely used user-generated programming reference in existence — has over a million questions and answers.

If you are ever struggling to solve a JavaScript programming problem you can bet someone has probably already documented and solved the exact same issue. It’s so likely that I now make it a habit to search Stack Overflow for the problem before I try anything else. Ninety percent of the time I’m able to find a solution in under 15 minutes.

Well documented? Check.

JavaScript is Widely Used

According to w3techs.com approximately 95% of all websites use JavaScript.

If we estimate that there are more than 1 billion websites (there are probably more) that gives us around 950,000,000 websites using JavaScript. 

950,000,000 is a lot, so — widely used? Check.

JavaScrip is easy to apply

JavaScript doesn’t need any fancy programs or expensive software to run — you can run it in your browser, any browser. You don’t need to spend money on development environments to get started.

Here, let me show you how easy it is to get started.

Please select your internet browser below and follow the instructions.

Step 1: Activate your browser’s 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.

Step 2: Type the following in your browser console

alert("Hello World")

After you’ve typed the above in your console press enter. You should get a little message box that pops up and says "Hello World".

Pretty neat huh?

I think so!

At this point, if I have done a good job of writing this post then you’ll be thinking to yourself: yeah Dan! I wanna learn JavaScript!

Alright then, I’m here to help.

Every week I’ll provide an overview of some core concepts in JavaScript and progressively I’ll show you how can use it to not only do some cool stuff but also how to build tools that can help you leverage the power of your computer to automate, enhance and improve many aspects of your personal and professional life.

I hope you are as excited about this learning opportunity as I am, and I hope you’ll join me as I develop this guide to programming in JavaScript for non-technical types — like you.

Oh, by the way, my name is Daniel Puiatti, you can call me Dan.

I have over a decade of experience in digital media. From responsive website design to search engine optimization, social media marketing to accessibility. My experience has allowed me to build, grow and optimize many digital campaigns and products. And like you, I don’t have a technical background.

Now let’s get learning. The next guide to read is my introduction to how a web browser builds a website.