Explore Free JavaScript Tutorials – GameDev Academy https://gamedevacademy.org Tutorials on Game Development, Unity, Phaser and HTML5 Wed, 22 Feb 2023 21:14:27 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://gamedevacademy.org/wp-content/uploads/2015/09/cropped-GDA_logofinal_2015-h70-32x32.png Explore Free JavaScript Tutorials – GameDev Academy https://gamedevacademy.org 32 32 Create a Basic Quiz using JavaScript https://gamedevacademy.org/javascript-quiz-tutorial/ Mon, 19 Dec 2022 01:00:15 +0000 https://coding.degree/?p=809 Read more]]>

You can access the full course here: JavaScript Mini-Projects – Language Learning Game 

Also available for school usage via the Zenva Schools platform which offers online courses, classroom management tools, reporting, pre-made course plans, and more for teachers.

Showing a Question

In this lesson we will start by simply showing a single question on the web page. To do this we will represent the question in a JavaScript variable, then display the question in HTML.

JavaScript Spanish quiz with basic UI

Project Setup

Like any web development project we need two key tools: code editor and browser. You can use your favorite code editor or an online development environment together with Google Chrome, Firefox or any modern web browser. In this course we use the free and popular Visual Studio Code ( https://code.visualstudio.com/ ). In your code editor, create two files.

Code File Description
index.html Our website HTML code for structuring and displaying our app in a web page
script.js Our JavaScript code for app logic and functionality

Question – HTML Web Page

Let’s starting by setting up the structure of our web page to display our question and alternatives. Inside index.html add the following HTML DOM (Document Object Model) elements as well as a reference to our JavaScript code file, script.js

<div id="title"></div>
<ul>
    <li class="alternative"></li>
    <li class="alternative"></li>
    <li class="alternative"></li>
    <li class="alternative"></li>
</ul>

<script src="script.js"></script>
HTML Code Description
<div id=”title”></div> The <div> tag is a generic HTML element. We provide an id so we can uniquely reference this HTML element from within our JavaScript code and CSS styling
<ul></ul> An Unordered List ( <ul> tag ) is a HTML element used to wrap HTML List Item elements ( <li> tags )
<li class=”alternative”></li> Add four List Items ( <li> tags ) to hold the four alternatives we show the user to select from. We provide each List Item with a CSS class of alternative so we can reference them from within our JavaScript code and CSS styling
<script src=”script.js”></script> At the bottom of our index.html file we add a reference to our JavaScript code file, named script.js, which will be loaded by the browser when this HTML web page loads

Question – JavaScript Object

Let’s start coding inside script.js, setting up our question as a JavaScript Object.

// define the object for the question entity
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};
JavaScript Code Description
let question = { properties: values }; Using the JavaScript let keyword and the curly braces ( {…} ), we set the variable question to be equal to a JavaScript Object which can contain any number of property:value combinations. To complete the syntax, follow the curly braces with a colon
title: ‘gato’,
alternatives: [‘dog’, ‘cat’, ‘bird’, ‘fish’],
correctAnswer: 1
Using the JavaScript Object Property:Value syntax (property and value separated by a colon and each combination separated by a comma). Here we assign our question variable three properties: title (String), alternatives (Array) and the array index of the correctAnswer (Number)

Question – showQuestion() Function

To keep our code organized and flexible we will create a JavaScript Function to show the question ( showQuestion ). This will enable us to execute the function by calling it, passing in the question object.

// define the object for the question entity
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};

// function for showing the question
function showQuestion(q) {
  // code
}

// call the function
showQuestion(question);
JavaScript Code Description
function showQuestion(q) { // function code } Function Definition. We define a function named showQuestion and set it up to receive a parameter named q, which will represent the question inside the function block
showQuestion(question); Execute Function. We call the function named showQuestion passing it the question object previously defined as an argument

Working with the DOM

The DOM connects the web page to our JavaScript code. Inside script.js, we use DOM Methods on the Document (Object representing the currently loaded web page) to select DOM Elements. Working with the DOM from JavaScript is a two step process. First, we select the DOM Element then we modify the DOM element.

Question – Show on Web Page

In our case, the question word (Spanish word) is stored in the question Object under a String property called title. In the HTML we represented the question word as a <div> with an id of title. Inside the showQuestion function, add logic to select and modify this DOM element.

// existing code
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};

// modified code
function showQuestion(q) {
  // new code
  let titleDiv = document.getElementById('title');
  titleDiv.textContent = q.title;
}

// existing code
showQuestion(question);
JavaScript Code Description
let titleDiv = document.getElementById(‘title’); Using the DOM method getElementById(),  passing it the id as a String (in our index.html file we set this id to be title), we select the element storing a reference to it in a variable ( titleDiv )
titleDiv.textContent = q.title; With a reference to the DOM element stored in a variable (previous step), we can now modify it. To do this, we set the textContent property of the DOM element ( <div> with an id of title ) to be the title property stored in our question variable (received as parameter q inside our function)

The web page now shows our question followed by an empty Unordered List ( represented by default with bullet points ) which will hold our alternatives.

JavaScript quiz with unordered list for answers

Alternatives – Show on Web Page

In our case, the alternatives (English words) are stored in a question Object under an Array property called alternatives. In the HTML we represented the alternatives as an Unordered List ( <ul> ) containing List Items ( <li> with a class of alternative ). Inside the showQuestion function, add logic to select and modify these DOM elements.

// existing code
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};

// modified code
function showQuestion(q) {
  // existing code
  let titleDiv = document.getElementById('title');
  titleDiv.textContent = q.title;

  // new code
  let alts = document.querySelectorAll('.alternative');
  console.log(alts);
  alts.forEach(function(element, index){
    element.textContent = q.alternatives[index];
  });
}

// existing code
showQuestion(question);
JavaScript Code Description
 let alts = document.querySelectorAll(‘.alternative’); Since we are selecting DOM elements by class (multiple DOM elements returned) rather than by id (one unique element returned) as we did above, we use the DOM method querySelectorAll(),  passing it a CSS Selector (in this case, class name preceded by a period – ‘.alternative’). A list of matching elements is returned and we store a reference to these elements in a variable ( alts )
console.log(alts); Log the variable alts to the console (see image below). Notice that alts contains each List Item element ( <li> with class of alternative ) in an array-like ordered list called a NodeList
 alts.forEach(function(element, index) {
element.textContent = q.alternatives[index];
});
We can now modify each element to contain one element from our question variable alternatives array property. To do this, we set the textContent property using the JavaScript forEach method which loops over each element in the alts variable

Console shows a list of DOM elements which will contain our question alternatives (<li> with class of alternative ).

Console showing list of alternative quiz answers

The web page now shows our question followed by our list of alternatives.

Quiz questions with unordered list showing various answer options

Handling User Input

In this lesson we introduce the concept of handling user input. We will do this by adding an event listener to the alternatives List Items so we can check if the user picks the correct answer.

Event Listeners – Simple Button Click

Before we add the functionality for our user to choose the answer they believe is correct, let’s start with a simple example of using an event listener to know when a user has clicked a button. When the user clicks the button, we log the message Clicked! to the console. Starting with the code from the last lesson, add the following code below the showQuestion(question) function call.

// existing code
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};

// existing code
function showQuestion(q) {
}

// existing code
showQuestion(question);

// new code
let btn = document.getElementById('btn');
btn.addEventListener('click', function() {
  console.log('Clicked!');
});
JavaScript Code Description
let btn = document.getElementById(‘btn’); Select Button Element. Using the DOM method getElementById(),  passing it the id as a String (in our index.html file we set this id to be btn), we select the Button element storing a reference to it in a variable ( btn )
btn.addEventListener(‘click’, function() { console.log(‘Clicked!’); }); Add Click Event Handler. With a reference to the Button element ( btn ) which is known as the Event Target, we can now attach an event handler by calling the method addEventListener(), passing it a function with two arguments: a case-sensitive String representing the event type we are listening for ( ‘click’ ) and a function to call when the event occurs. When the event occurs, we run the code inside the function which in this case logs the word Clicked! to the console

Quiz with Click Me button under it

Note: you can optionally remove the code we just wrote as an example before continuing with the next section.

Event Listeners – Alternatives List

Next, let’s add event listeners to each List Item element ( <li> with a class of alternative ). As we did in the above Button example, we could assign each element an id, then select and add the event listeners one by one. However, since we already have a reference to this list from our last lesson (stored in the variable alts ), we can add the event listeners to each List Item element ( <li> with a class of alternative ) inside the existing alts.forEach() method. Recall that the function passed to the alts.forEach() method has two parameters, element and index. We can use the element parameter ( each alternative ) as our Event Target to attach the event handler to on each iteration of forEach. We can then use the second parameter, index, to check against our question’s correctAnswer property. If this comparison is true then we log Correct Answer! to the console else we log Wrong Answer!

// existing code
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};

// existing code
function showQuestion(q) {
  // existing code
  let titleDiv = document.getElementById("title");
  titleDiv.textContent = q.title;
  
  // existing code
  let alts = document.querySelectorAll('.alternative');
  
  // modified code
  alts.forEach(function(element, index){
    // existing code
    element.textContent = q.alternatives[index];
    // new code
    element.addEventListener('click', function(){
      if (q.correctAnswer == index) {
        console.log('Correct Answer!');
      } else {
        console.log('Wrong Answer!');
      }
    });
  });
}

showQuestion(question);

Click each alternative one at a time and notice the result in the console. The only one that returns true is in fact the correct answer! ( gato is Spanish for cat ).

JavaScript quiz showing clickability of answers in the Console

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Transcript

Showing a Question

In this lesson, we are gonna get started with creating our project. And we’ll concentrate on something simple, just showing one question on the screen. In particular, we’re gonna be looking at how to represent a question as a variable in JavaScript. And we’ll be showing a question which is composed of a question title, as well as the possible alternatives, possible answers on the HTML document.

Let’s head over to our code editor and get started. I’ve created a new project, which includes index of HTML as well as an empty script file. To represent the question in JavaScript, we’ll be using an object, as that allows us to store an entity with different properties in a variable.

Let’s create our variable, it’s going to be called question. We know that questions have a title, which is the word in Spanish. Let’s create a sample question here. The title will be Gato, which means cat. Then we’re gonna be showing to the user a list of possible solutions. And those we’re gonna call alternatives. The alternatives the user will see, let’s say that they will be dog, cat, bird, and fish.

We know that the correct solution here is cat, which is in position. If we start here, this is position zero, this is position one. And so we want to store the correct answer here, just so that we can check later on. And that’s going to be in position one. Optionally, you can store the actual word as the correct answer. And I do have to say that for everything that I do here, there are many other alternative solutions. So feel free to explore other architectures, if you want to get a bit deeper into the language.

Next, in order to show my question to the user, I’m gonna have to create some containers where the different information will be displayed. So let’s go to HTML, and add our code above the script inclusion. Normally, you always add your script inclusion at the bottom of your document right before the closing of the body tag. I’m gonna add a div for the question title, I’m gonna give it the ID of title. Let’s type in some sample code for now.

So I should be seeing in the browser, that word up here. Next, for the alternatives, we’re gonna be using a list, an unordered list, and each one of the list items will show a different possible response. We wanna duplicate this line many times. And to do so in Visual Studio, you can press Ctrl C, Ctrl V, or Command C, Command V on the Mac, like so. And that will show what this is looking like.

What we want to do now is of course, replace this data by our own data. So I’m actually going to delete this because I just want to show you what that was going to look like. We’re going to give our list items a class, which is going to be called alternatives, alternative like so. Great, so let’s now go to JavaScript and start by adding the title here of the word that we want to show, at the moment it’s all empty.

The first step here will be to select the DOM element that we want to modify. And we’re gonna store that in a variable. I’m going to call my variable title div. And we’re gonna select this by doing document dot get element by ID, and then enter the ID, which is title. Going to zoom out a little bit, there we go. So now that we’ve selected it, now we can modify it. Title div dot text content, will be equal to question dot title. And that should be enough to show that title there, great.

To keep my code organized, I’m gonna place all of these in a function so that then we can call that function multiple times. Start by typing function. The name here will be show question. And the parameter will be that question that we need to pass in. So let’s call this question Q. And let’s move all of this code inside of our function. And make sure to add some indentation just for readability. And instead of question the title, we’re going to do q dot title, as that will be gathered from here.

And then we if we want to call this function, we can just do show function, and we can pass in our question. So if I run this code, it should be the exact same result.

Great, well, now let’s address the last part, which is the alternatives part. If you’re wanting to select every one of these, one at a time, you could go and add a certain ID to each one of them. But since they all behave in the same way there is a different way of doing this, which is to select it all by the class, in this case alternative, and then work on an iteration and change all of them.

Let’s go and select them all. In this case, we’re gonna be selecting them by class. In CSS, when you select by class, you type dot alternative, or name of the class, and then you add certain CSS rules. That’s how CSS works. Well, the good thing about the DOM API is that there’s a way to select everything by using the same type of queries that you’ll use in CSS. So in this case, we’re going to be selecting by a query.

And for that, we are going to be using document dot query selector all. This will go and select all of the elements that satisfy a certain CSS query. In this case, it will be dot alternative. That is the same query that you would use in CSS. We definitely want to put this in a variable. So let’s call this alternatives like that, just an average of an average deviation.

So after we’ve selected this, it’s always a good idea to check in the console, to be sure that it’s working as expected. And you can see here that we have four Li nodes selected. So four list items. To go over each one of them, we’re gonna be using the for each method, which is part of the result that you get from when doing these queries. For each takes a function as a parameter. And we can pass in different parameters here, one of them is the element itself and the other one is the index the position of the element.

Let’s open the function body. And in the function body, if we call this element variable here, this will give us access to each one of these as the iteration progresses. So we can go and change their values. Let’s type element dot text content. And we could change the value to let’s say, a. You can see that they’re all being modified to a. But we don’t wanna modify them to a, we wanna modify them to the corresponding alternative. For that we can access our q variable, which contains the question we’re passing in and typing q dot alternatives.

And now what position is this going to be? Well, the good thing here is that we have that index parameter. So that will start from zero and increase in each iteration. So if we do that, we can actually get all of these one at a time. Let’s save and check to see if it works.

And there we go. Well, that is all for this lesson. As you can see, we’ve created the basic HTML template that we’re gonna be using in our app. And we created a method that receives a question as a parameter. And inside of that method, you can modify the title that you’re gonna show as well as showing each one of the alternatives. For the alternatives, we selected them all using query selector all and then we iterate through each one of them and change their corresponding values. Thank you for watching, I will see you in the next lesson.

Handling User Input

In this lesson, I’m going to start with the code of the previous lesson. We are going to be taking that approach going forward, so that we can build up our app. The way user interaction will work here, is that the user will be able to click on any of the alternatives, and will check whether that’s the correct answer. But to keep things simple, at first, let’s go and try a simple example of using click events.

I’m going to add a new element here in my index.html file. It will be a button. It’s going to have a certain ID. And it will just say Click Me. We want to be able to listen to these clicks and show something in the console. For that, we’re going to start by selecting our button, document.getElementById, and the ID here it needs to be entered, and this will grab our button, and let’s refresh here so that we can see the button.

To listen to click events, type the name of your variable, and then .addEventListener. This is a method that allows us to pass what’s called an event listener. That basically means we are going to specify what event we want to listen for in this case, we want to be listening to a click event. And whenever there is a click event, something needs to happen, and that will be represented as a function here. This function will be executed every time that there is a click on the button. I can go and I can type console.log, and this will say, clicked, save, reload your index.HTML file, and if you click now, you’re going to see that every time you click, you are running these functions. So that’s really how they work.

Next, we want to be listening to events for all of these list items. You could go and give them all a separate ID, and you could select them individually and check that, but since we’re already selecting them all using query selector all, and we are iterating through them, for now, we are going to be adding our event listening here, and check that the answer is correct.

I say for now because there will be some changes made to this architecture later in the course. So for now, we’re going to type in our element, which is this list item. And we’re going to add that same event listener, add event listener. We are listening to click events, and let’s create our function here. In the body of the function, I’m going to access my element again and change the text content, just so that we can be sure that this is working.

If I refresh and I click on this list items, you can see that their content is being changed. And that means that our click listening is working.

And now we can get rid of these, and instead check for the correct answer. Now we need to get the answer that the user entered, which would be the position index. So let’s check the correct answer. And for now we’re going to list inside of here, later on we’re going to move it to a separate place.

How do we know if the answer that was submitted is the correct one? Well, we need to use an if statement to check, first of all, what’s the correct answer? The correct answer would be q.correctAnswer. So q.correctAnswer needs to be equal to whatever the user clicked on. And that would be in our case, the position of the current alternative, starting from zero, so that is index that we have already used to show the text. We’re also going to use that to check for correctness. So if this is equal, then we’re going to show in the console, correct answer.

Let’s go and save and refresh, and let’s check that, see if it’s working. I’m going to click on dog and nothing is happening. If I click in cat, then I see correct answer. If I click on bird and fish, nothing happens. We can add an else statement here to also show when something is not the correct answer, in the console. So let’s go and save, and you can see that’s the wrong answer, that is the correct answer. That’s the wrong answer. And that is the wrong answer.

Great, so we have a basic click functionality. This button that we added, we can definitely get rid off. So I’m going to leave that up to you. I’m going to keep that in this file, but in the next lesson, that is not going to be around. Well, that is all for this lesson. You have learned something really useful which is how to detect for clicks, basics of user interaction. Now your applications on projects can have a whole new layer of interactivity to them. Thank you for watching this lesson. I look forward to seeing you in the next one.

Interested in continuing? Check out the full JavaScript Mini-Projects – Language Learning Game course, which is part of our Full-Stack Web Development Mini-Degree.

For teachers, you can also try Zenva Schools which offers online learning suitable for K12 school environments and offers a wide array of topics including JavaScript, Python, Unity, and more.

]]>
How to Fetch API Data from a URL – JavaScript Tutorial https://gamedevacademy.org/fetch-api-data-tutorial/ Sun, 08 May 2022 01:00:52 +0000 https://html5hive.org/?p=2597 Read more]]>

You can access the full course here: Bite-Sized Modern JavaScript

 

Fetching Data from URL

To fetch data from a URL, we will use the Javascript fetch API. We won’t cover every aspect of the fetch API, just the basic retrieval functionality. To get this functionality, you need to install node-fetch. Set up node in your project if you haven’t already and navigate to the folder in terminal. Once there, run:

npm i node-fetch --save

To install node-fetch and add the line:

const fetch = require(‘node-fetch’);

At the top of your program. Next add the code:

fetch('http://api.steampowered.com/ISteamUserStats/GetGlobalAchievementPercentagesForApp/v0002/?gameid=221380')
    .then(function(response) {
        return response.json();
    })
    .then(function(myJson) {
        console.log(JSON.stringify(myJson));
    });

This will fetch the data, convert it to JSON, and print it to the console. The json response data is stored in the “myJson” variable. This is also taking advantage of Javascript’s new Promise feature along with asynchronous functionality. Let’s take a few minutes to talk about Promises and async functions in Javascript.

 

Transcript

What’s up everyone. Welcome to fetching data from a URL. Here we’re going to write the actual code that will fetch the data we want, and we’re going to use our asynchronous functions that promises to do so. Actually, before we get started we should probably install that fetch API.

So assuming that you are in your project directory, if not then navigate there now. We’re just going to use a simple npm command to install what’s called node fetch. So we’re going to do npm i node-fetch –save like so. Okay, so we’ll not worry about the warning or anything as long as we see added 1 package then we are good to go. If you open up your packages.json – so let’s go back here if we open up packages.json we should see node-fetch there.

So now we’ll need to add the fetch API here. And we’re gonna do so by creating a constant called fetch this is going to be equal to require node-fetch. Okay, so now we have the fetch function and can use this to retrieve the data in our URL. So lets actually go back to chrome. This is the data that we want. This is exactly what the format of the data we want comes back in.

So what we’re going to do for now is gonna copy this URL. We’re gonna create a variable and let’s make this URL equal to this string here, and we’re gonna feed that into a fetch function. So we’ll create an async function and we’re going to call this: fetchData. It’s going to take in a URL as a parameter. Now we want to call upon fetch with that URL. So fetch is the actual JavaScript function built into the node fetch library that will be used to actually retrieve data from a URL.

So we actually want to store the results of this in a variable. We’re going to call this a response. Response equal to fetch(URL). This is where things get interesting, because this is an asynchronous function, we’re going to actually do await fetch(URL). So the fetching of the data is going to take some time. We don’t want this blocking up the main thread while it’s fetching the data. And that’s why we’re doing await fetch, because fetching the URL or fetching dates from this URL may take some time. So we’re basically just going to say response only takes on the value after fetch has retrieved the data.

Okay so from here, we have the response but we want to make sure that it’s JSON data. So this will just come back as an object that needs to be decoded. So what we’re gonna do is we’re gonna create a variable, jsonResponse, and we’re gonna set this equal to again await – because it may take some time – and we’re going to get our response and we’re going to call the JSON function. So this is gonna convert our response to JSON and then let’s say we just want to print out a simple console.log and we’re going to stringify this data.

So we’re gonna call upon a JSON method called stringify and we’re just gonna pass in our jsonResponse. So we’re gonna call upon fetchData and we’re going to pass in that URL. Now this will do the printing. We can actually give this a save and we can run it. This is really promising, you can see that we’re getting back this huge string of data and has essentially exactly the same data as we see here.

Interested in continuing? Check out the full Bite-Sized Modern JavaScript course, which is part of our Bite-Sized Coding Academy.

]]>
Learn Asynchronous Programming – JavaScript Tutorial https://gamedevacademy.org/javascript-asynchronus-programming-tutorial/ Fri, 11 Mar 2022 01:00:07 +0000 https://gamedevacademy.org/?p=15363 Read more]]>

You can access the full course here: Intermediate JavaScript – Build a Dynamic Data Table

Asynchronous Programming with Async Await

In this lesson, we’ll see how to do asynchronous programming with async/await.

An async function is a function declared using the ‘async‘ keyword, with ‘await‘ used within it to make the code stop and wait for the function being called to finish before proceeding to the next line:

async function myAsyncFunction(){
const response = await fetch(‘http://localhost/myfile.json’);
let json = await response.json();
}

Here in this example, we’re loading in a JSON file to our const ‘response‘. Once the fetching is done then we continue by parsing its contents to an object that we store in the ‘json‘ variable.

Note that the await keyword can only be used inside an async function.

Promises vs Async Await

In this lesson, we’ll compare the differences between promises and async/await.

The main differences we can notice between the two approaches are:

  • Async functions do not have states like promises, they simply return a success or failure;
  • Async has cleaner error handling (which we’ll see in the next lesson);
  • You can’t chain async functions as you could with promises;
  • Chaining multiple promises can become complex to deal with.

As such, we’re going to use async functions for the rest of the course.

Error Handling in Async

In this lesson, we’ll learn how to handle errors in JavaScript.

The easiest way to do error handling is by using try catch blocks as they are statements that specify how to handle exceptions when thrown.

Let’s take a look at how they work in practice:

async function myAsyncFunction(){
try {
const response = await fetch(‘http://localhost/myfile.json’);
let json = await response.json();
} catch (err){
console.log(err);
}
}

By wrapping up our code in a try catch block, we’re telling the browser to try to load in the specified JSON file for us, and if it can’t do it then it should simply log the error in the console. Additionally, we could also show a message to the user explaining that an error occurred without displaying the actual whole error stream to them unnecessarily.

Try catch blocks handle pretty much any exception that may occur and thus work pretty well with asynchronous functions as we never know when an error can happen.

Transcript

Asynchronous Programming with Async Await

Hello and welcome back to the next video in this course. And in this video, we’ll be taking a look at asynchronous programming with the async and await keywords.

So what is async and await? An async function is a function declared using the async keyword, and await is used within them. So what that means is that we have to have the two keywords together.

As we can see in this example, before the function key, we use the async keyword, and then somewhere throughout the function, we have to do an await, we have to have the two together.

And what we’re doing in this function is that to our variable response that we’ve made, we are loading in a JSON file, and then what we’re doing is we are adding this, create another variable later on using the let keyword again to load the response, the JSON of our response, into another variable.

Really, you can kinda see, we’re doing the same thing that we did with promises, but this is, in the way I look at it, this is a lot more cleaner.

Now, the next video, we’ll take a look at the differences between promises and async and await, and then we’ll decide which one we’re gonna use for this course. See you then.

Promises vs Async Await

Hello and welcome back. This video, we’re gonna be comparing the two asynchronous options that we’ve looked at so far in JavaScript in the Promises versus Async and Await.

So what is the differences between the two? Technically async and await function is the same thing as a Promise. It’s just done a lot cleaner and you can’t chain them like you can, in the same sense as you do the Promise chaining with next and such.

Async functions do not have states like Promises do either. They either return success or failure. There’s not different states, again, like Promises have.

Async has a much cleaner error handling that we will look at in the next video. And Promises, as you start chaining them, they can really become messy. Again, async and await, is just so much easier to use and easier to maintain.

So because of that, for the rest of the course, when we do asynchronous programming, it will be using the async and the await function. And in the next video, we will take a look at how we can do error handling for async and await.

Error Handling in Async

Hello, and welcome back. And I promise you, this will be our last theory video that we have. The next video, we’ll start getting into, into the code and start writing it. But before we get to that, we have to just look at one more topic.

And that is how we will do our error handling with Async. And the easiest way that we can do error handling is what’s called a try catch block. Try catch blocks are statements that they kind of tell the browser, the JavaScript partial or whatever you want to call it, how to handle exceptions when they occur.

And let’s take a look at what I mean by that. Here this is the rehash of our function that we looked at in the Async and await video. And all I’ve done is I’ve added this try and catch to it.

And what happens is that it will, we’re telling the browser to try to do what we’re doing right here. Try to load in this JSON file for us. However, if you can’t do it, you know, don’t display the massive error to the user.

Let’s put our, put the error into the console. And then what we could do here is we could put a nice little message to the user. Hey, you know, an error has occurred or whatever, instead of just bombarding them with a you know, just massive error stream.

So this try catch block really comes in handy with an asynchronous function. Cause you never know what could happen. You know, the user’s internet could go out.

There could be changes to your server that you’re not aware of, and you can lose a file or, you know, any number of things could happen. And try catch allows us to handle pretty much anything that we can think of gracefully.

So, as I said, this is our last theory video. In the next video, we will begin creating our json file for the project, with all the cards that we’re going to use. And the from here on out, we’ll be writing some code. See ya then.

Interested in continuing?  Check out our all-access plan which includes 250+ courses, guided curriculums, new courses monthly, access to expert course mentors, and more!

]]>
How to Do an HTML Redirect: Beginner’s Web Tutorial https://gamedevacademy.org/html-redirect-tutorial/ Tue, 22 Feb 2022 10:37:03 +0000 https://html5hive.org/?p=2682 Read more]]> The easiest way to have your users automatically redirected from an old URL to a new one is by using an HTML Redirect. Whether you’ve changed your domain name, restructured your website, or simply reorganized some of your web pages, avoiding the dreaded 404 Page-Not-Found error is paramount.

Regardless of your reason for website changes, in this HTML Redirect tutorial, we’ll show you through simple examples how to confidently enhance your website, while protecting your user’s experience and the SEO you have built over time.

Let’s dive in!

About HTML Redirects

HTML redirects are one of three techniques that provide instructions to your visitor’s web browser to automatically take your user from the URL they keyed into their browser to the URL where your content now resides. In this way, you can retire an old HTML page and send users to a brand new HTML page entirely.

How to Code HTML Redirects

Modern websites have a formally structured HTML file, often called index.html, that serves as the main entry point to your site. Your site then has zero to many less formal web pages, HTML fragments, or components that return HTML which varies depending on if you’re using no JavaScript (JS), vanilla JS or one of the many JS libraries or frameworks that are so popular today (React, Angular, and Vue, just to name a few). In its simplest form, the HTML structure consists of three HTML tags: html, head, and body.

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
  </body>
</html>

HTML redirects are coded with a <meta> tag inside the <head> section which contains the metadata written for web browsers rather than the <body> section which contains the HTML elements visible on the displayed webpage.

HTML Redirect Syntax Explained

An HTML redirect,  sometimes referred to as meta redirect or meta refresh, has two attributes containing three pieces of information important to the web browser.

<meta http-equiv="refresh" content="time_delay; url=new_url">

The first property is http-equiv. For HTML redirects, its value is set to “refresh”. Since browsers work within an HTTP Request-Response cycle, this attribute provides information to the browser “equivalent” to what can be found in a similarly-named HTTP header.

The second attribute is content which has two values. Its syntax may seem a little odd so it’s important to note that you have two values inside a single set of double quotes separated by a colon (“time-delay; new_url”).

HTML Redirect Syntax Example

In the code below, the browser redirects to the URL provided (https://example.com) after a delay of 3 seconds.

<meta http-equiv="refresh" content="3; url=https://example.com">

If you changed the first value in content to 0, the page would immediately redirect. If you changed the value to 10, the browser would wait 10 seconds before going to the new URL (in this case the website example.com). Always set this value to zero for accessibility compliance unless you have a strong use-case not to. If you do need to introduce a delay, it is important to keep the user top of mind. Too short a delay may be frustrating while a longer delay should probably be accompanied by a “click here” link that allows the user to manually perform the redirect. This can easily be accomplished in the <body> section using an anchor <a> tag.

<h3>My Important Message...</h3>
<p>You will be automatically redirected in 5 seconds.</p>
<p>Please <a href="https://example.com">click here</a> to be taken immediately.</p>

Essential HTTP Status Codes

What is HTTP?

HTTP is an acronym for Hyper Text Transfer Protocol. In simple terms, web technologies communicate using an HTTP Request/Response cycle.

Why is this Important for Redirects?

When working with web technologies, it’s good to know the meaning of at least a few of the many HTTP Status Codes that are returned when a user enters a URL into the browser or in our case redirects one web page URL to another.

Essential HTTP Status Codes for Redirects

HTTP Status Codes contain three digits with the first number indicating response type (1xx – 5xx). Within this block, there are many codes that you can learn over time. If we ignore for the moment codes that start with 1 (informational) and codes that start with 5 (server-side) there is a small subset of the remaining codes that are essential to redirects:

  • 200 – success
  • 301 – permanent redirect
  • 302 – temporary redirect
  • 404 – page not found

Our goal in redirects is to receive 200 (our web page loaded successfully) and avoid 404 (our web page could not be found). If our content has been permanently moved, we want our redirect strategy to send the browser a 301 status code (known as a permanent redirect). If our content is only temporarily residing at a different location we want our redirect strategy to send the browser a 302 status code (known as a temporary redirect).

HTML Meta Redirect Website Example

An HTML redirect is actually quite simple and best illustrated with an example. In the first code snippet, we add the meta refresh tag redirecting visitors to our new URL after a delay of 3 seconds.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      http-equiv="refresh"
      content="3; url=http://127.0.0.1:5500/new_url"
    />
    <title>Old Website</title>
  </head>
  <body>
    <h1>Old Website URL</h1>
    <h3>http://127.0.0.1:5500/old_url</h3>
  </body>
</html>

Screenshot of a website showing the old website URL

Note the HTTP Status Code of 200 in the browser’s Network tab indicating our old website loaded successfully. After the 3 second delay we coded, the new website is loaded.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>New Website</title>
  </head>
  <body>
    <h1>New Website URL</h1>
    <h3>http://127.0.0.1:5500/new_url</h3>
  </body>
</html>

Screenshot of a website showing the new website URL and Status Codes

Note the two HTTP Status Codes for our new website. The code of 301 indicates a successful redirect while code of 200 indicates our new website was successfully loaded.

Alternative Methods to Perform Redirects

While HTML redirects may be the easiest way to perform redirects, it is not the only way or even the best. As we mentioned in the opening “About HTML Redirects” section, there are two other ways to define redirections. The two other methods are:

  1. HTTP Redirects
  2. JavaScript Redirects

HTTP Redirects

HTTP redirects (also known as 301 redirects, URL forwarding, or URL redirection) are done server-side and are the most powerful and reliable way to ensure that users and search engines are directed to your new content location with no loss of traffic or SEO page ranking.

For Google’s guidance on using 301 redirects where SEO is an important consideration, you can watch this video from Google Search Central YouTube channel.

Important note: In cases where your content is at a new location temporarily it is important to use a 302 (temporary redirect) instead of the 301 (permanent redirect).

While all the concepts we’ve discussed in this article apply, when it comes to HTTP redirects there are so many combinations of technology stacks, hosting services, and domain providers your best approach is to search “301 redirect” followed by “your-technology-stack” followed by “your-service-provider” and follow the guidance of official sources when possible.

JavaScript Redirects

JavaScript redirects provide another simple option to automatically take your user from the URL they keyed into their browser to the URL where your content now resides. At first glance, JavaScript offers a lot of cool benefits for triggering redirections. Let’s explore the JavaScript way by mirroring the results we accomplished above using the HTML redirect technique.

In the code below, the browser redirects to the URL provided (https://example.com) immediately.

window.location = 'https://example.com';

The following are other techniques you may use to achieve the same result.

window.location.href = 'https://example.com';
window.location.assign('https://example.com');

In the code below, the browser redirects to the URL provided (https://example.com) immediately as above. The difference from using the assign() method is that after using replace() the current page is not saved in history which simply means the user cannot navigate back to the original page using the browser’s back button.

window.location.replace('https://example.com');

Another interesting thing with using JavaScript is that you can make the URL dynamic, update the URL in response to events, and basically provide any programming logic to determine which URL to navigate to.

let urlBase = 'https://';
let domainExtention = '.com';
window.location.assign(urlBase+'example'+domainExtention);

In the HTML redirect section above we also showed how you could introduce a delay in redirecting to a new URL. This can be easily accomplished in JavaScript as well by using a setTimeout()  function. In the code below, the browser redirects to the URL provided (https://example.com) after a delay of 3 seconds.

let urlBase = 'https://';
let domainExtention = '.com';

setTimeout(() => {
   window.location.assign(urlBase + 'example' + domainExtention);
}, 3000);

Learning Resources

Learn more about HTML, JavaScript and HTTP Redirect details from the Mozilla Developer Network documentation and from this insightful article from CSS-Tricks.

Continue your HTML learning with this free HTML & CSS 101 – Web Development Fundamentals course or take your skills to the next level in just over an hour with this free COMPLETE COURSE – Learn HTML and CSS in 80 MINUTES. You might also consider trying this HTML Tutorial for Beginners from Programming with Mosh or decide to master the foundations of all web development with this premium Full-Stack Web Development Mini-Degree.

Conclusion

There are many reasons why you might want to provide URL redirection and send people to another page – including seamlessly transitioning to a new domain, restructuring your existing website, directing visitors to a secure version of your site (from http://example.com to https://example.com), allowing people to access your site from multiple domain names (there are now well over 1000 domain extensions and it’s still growing), and many other scenarios.

Regardless of your reason, ensuring that users and search engines are directed to your new content, maintaining other internet sites’ backlinks to your content, user’s bookmarks and of course, no loss of traffic or SEO page ranking make awareness of this topic essential in today’s world. Just think of how many times you’ve been frustrated trying to access an old HTML page that no longer exists.

In this article, we focused on the simplest of three techniques, HTML redirects, and briefly discussed the other two (HTTP and JavaScript). While HTML redirects are a simple solution and JavaScript provides a powerful developer experience, it’s important to keep your end goal in mind when deciding which approach to take. One site’s best way for sending someone to another page may not work for you.

With this foundational knowledge, you can confidently enhance your website by finding and implementing the steps that match your requirements and technology stack ensuring people continue to find you and your valuable content!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
How to Write a JavaScript Comment: Beginners Tutorial https://gamedevacademy.org/javascript-comment-tutorial/ Tue, 01 Jun 2021 05:02:25 +0000 https://gamedevacademy.org/?p=13762 Read more]]> When developing any sort of project, occasionally you want to write code or notes that you don’t want the computer to read. Whether this is to explain something to yourself, helps you test things, or something in-between, these sorts of additions are not only very useful, but quite common in professionally developed programs. If you haven’t guessed it yet, we’re talking about comments. And, in this JavaScript comment tutorial, we’re going to go over just how to use comments in your programs. Whether you’re building a website or HTML5-based games, this tutorial will help you enhance how you work with your code and with JavaScript in general.

About Comments

JavaScript has two simple ways to comment code: single line ( //comment here  ) and multi-line ( /*comment here*/  ). While code is for computers, comments are for people (including your future-self) and are completely ignored by the JavaScript interpreter (i.e. it has no effect on the executing code).

When you’re immersed in a section of code, it’s easy to remember the context. However, when a different developer (or your future-self) returns to existing code, it’s also easy to forget exactly what the code was intended to be doing in the context of the program as a whole. This is where code comments shine.

Single-line Comments

For single-line comments, the JavaScript interpreter ignores everything to the right of the //  until the end of the line. These comments generally describe what the next line of code is doing or when located on the same line as a code statement (known as an inline comment). This provides a succinct annotation.

Syntax for Single-line Comments

As mentioned, single-line comments use two forward slashes ( // ) to tell JavaScript to ignore all text that follows on the same line. The important thing to remember is that “comments are for people; not computers”; so just because you can write a long line of text, doesn’t mean you should. With this in mind let’s consider some Best Practices.

Best Practices for Single-line Comments

Most comments should be placed on the line above the code being documented.

// Prints "Hello World!" to the console
console.log("Hello World!");

Concise comments or annotations, especially referring to the result of a JavaScript statement, can be placed after the code it describes as long as it’s on the same line. This is generally referred to as an inline comment.

console.log("Hello World!"); // Prints "Hello World!" to the console

While technically valid, single-line comments containing a lot of text can be difficult to read and should therefore be avoided.

// I am a single line comment. Everything that follows, on this same line, is ignored by the computer. In this example, I am located above the JavaScript code I'm documenting. The code that follows prints "Hello World" to the console.
console.log("Hello World!");

While technically valid, all “inline comments” comments containing a lot of text will be difficult to read and should therefore be avoided.

console.log("Hello World!"); // I am a single line comment. Everything that follows, on this same line, is ignored by the computer. In this example, I am located on the same line as the JavaScript code I'm documenting. As long as I'm after the JavaScript code; the code will still execute. The code before me prints "Hello World" to the console.

Multi-line Comments

Syntax for Multi-line Comments

To help make comments easier to understand, JavaScript provides a second alternative. The syntax ( /* comments go here */ ) is a much more flexible option that allows you to optionally break your comment into multiple lines. In addition to being able to tell the computer to ignore multiple lines, the other significant difference is that instead of ignoring what follows, this syntax ignores what is in between the opening and closing forward slash-asterisk combination (/ ignored by computer */ ). This type of comment, sometimes called “block comments” can be on the same line, broken over multiple lines, or even placed in the middle of a JavaScript statement (though not a good idea). With this in mind, let’s consider some Best Practices.

Best Practices for Multi-line Comments

All multiline comments should be placed above the code being documented to improve readability.

/* I can exist as a single line */
console.log("Hello World!");

This is especially true for comments that are broken out over multiple lines.

/*
I can span multiple lines
The code that follows me prints "Hello World" to the console.
*/
console.log("Hello World!");

While technically valid using the multiline syntax ( /* */ ), “inline comments” containing a lot of text can be difficult to read (as is the theme here with inline comments) and should therefore be avoided.

console.log("Hello World!"); /* I am a single line comment. Everything that follows, on this same line, is ignored by the computer. In this example, I am located on the same line as the JavaScript code I'm documenting. As long as I'm after the JavaScript code; the code will still execute. The code before me prints "Hello World" to the console.*/

While technically valid using the multiline syntax ( /* */ ), comments should not be placed in the middle of JavaScript statements since they can become very confusing.

console.log("Hello " + /* I can be in the middle of a statement but this makes me hard to read so should be avoided unless you have a very good reason.*/ + "World!");

Development Use: Pseudocode Comments

Comments can be used as a form of pseudocode to outline intention prior to writing actual code. Pseudocode outlines the logical steps your code will take rather than the code itself.

// function to greet user
function sayHello(name) {
  // define salutation
  // define punctuation
  // create string to return
  // return result to calling function
}
/*
1. execute function
2. log result to console
*/

With your plan in place, you can now code the details.

// function to greet user
function sayHello(name) {
  // define salutation
  const returnPrefix = `Hello `;
  // define punctuation
  const returnSuffix = `!`;
  // create string to return
  const returnString = returnPrefix + name + returnSuffix;
  // return result to calling function
  return returnString;
}
/*
1. execute function
2. log result to console
*/
console.log(sayHello("Game Dev"));

Document Use: DocString Comments

DocString comments clarify what the code that follows it does. It generally includes the what, why, and sometimes who – but never the how. They also serve to document inputs, outputs, and even the name of the developer as well as many other optional, but specific, details. DocString Comments are located directly above the code block being documented and follow a format similar to multi-line comments.

Syntax for Documentation Comments

The syntax starts with /** , ends with */ , and each line within the block starts with an asterisk * . Special tags are noted within the block and start with the @ symbol such as parameters ( @param ). DocStrings identify what parameters the function expects and what it returns as well as a long list of optional details such as who wrote or modified the code last, return value and version number to name a few (https://jsdoc.app/ contains a long list of tags as well as examples).

/**
 * function says hello to user
 * @author  Cool Dev
 * @param   {String} name   - Name to greet
 * @returns {String}        - Hello message
 */
function sayHello(name) {
  return `Hello ${name}!`;
}
console.log(sayHello("Game Dev"));

Generate External Documentation

DocStrings also have added benefits including allowing you to document your code alongside the actual code itself as well as the ability to generate external documentation, in the form of an HTML webpage, based on your source code using tools such as JSDoc (https://jsdoc.app/).

Debug Use: Comment-Out

In addition to commenting your code, you can also comment-out-code. This use of the comment syntax allows you to prevent code from running without actually having to delete it. This is valuable for testing and debugging your code help to pinpoint sources of errors and isolate bugs simply by placing // in front of an executable line or surrounding a block of code with /**/ .

For example, when tracking down bugs, comment out lines potentially causing the issue. When code runs without breaking you’ve found the offending line and can investigate what’s happening.

console.log("good code");
// console.log("code with error");

You can prevent execution of a single line of code…

function sayHello(name) {
  // return `Hello ${name}!`;
  const returnPrefix = `Hello `;
  const returnSuffix = `!`;
  const returnString = returnPrefix + name + returnSuffix;
  return returnString;
}
console.log(sayHello("Game Dev"));

… or prevent execution of several lines of code.

function sayHello(name) {
  /* const returnPrefix = `Hello `;
  const returnSuffix = `!`;
  const returnString = returnPrefix + name + returnSuffix;
  return returnString; */
  return `Hello ${name}!`;
}
console.log(sayHello("Game Dev"));

Risks of Using Comments: Out-of-Date Comments

Comments are static! While code is often updated, refactored, or removed. It is very important to keep comments up-to-date with code changes.

Other developers, or your future-self, will naturally assume comments are up-to-date and valid. The consequences of these assumptions proving wrong can cause wasted time, energy, and money – worse they can introduce significant risk! Outdated comments can be worse than no comments at all so remember to maintain and update comments whenever associated code is updated or removed.

JavaScript Commenting Tips

Keyboard Shortcuts

Most code editors have a keyboard shortcut to help you quickly comment out a single line ( Ctrl + / for Windows and Cmd + / for Mac ). You can also highlight a block of code and use the keyboard shortcut to comment out all selected lines.

Best Practices

Comments are not intended to explain cryptic code. Since the code you write is generally abstracted several levels above the machine code it is eventually compiled into, you can safely use variable and function names that allow you to clearly name what you’re doing in a semi-self-documenting way.

For example, this clearly written code and the following cryptic code eventually compile to the same thing as far as the computer is concerned, so write with people and therefore clarity in mind – cleverness is generally not to be admired in code others may have to read or support.

function sayHello(name) {
  return `Hello ${name}!`;
}
console.log(sayHello("Game Dev"));

The code above and below produce the same result including the same after compile size so it’s best to choose clarity over cleverness.

function a(b) {
  return `Hello ${b}!`;
}
console.log(a("Game Dev"));

Indenting

Comments should be indented at the same level as the code immediately below them.

// function to greet user
function sayHello(name) {
  // salutation
  const returnPrefix = `Hello `;
  // end all greetings the same
  const returnSuffix = `!`;
  // create string to return
  const returnString = returnPrefix + name + returnSuffix;
  // return result to calling function
  return returnString;
}
/*
1. execute function
2. log result to console
*/
console.log(sayHello("Game Dev"));

Learning Resources

Continue your JavaScript learning with this free JavaScript 101 course for beginners, take your skills to the next level with this free Learning the JavaScript Language – COMPLETE COURSE or go all-in with this premium HTML5 Game Development Mini-Degree. You might also consider trying JavaScript Tutorial Beginners by Dani Krossing or the JavaScript Tutorial For Beginners by The Net Ninja for even more JavaScript knowledge.

Happy Learning!!!

Conclusion

Through this JavaScript comment tutorial, we’ve learned a lot about how comments can help you develop your program. We first discussed the syntax of single-line ( //  ), multi-line ( /**/ ), and documentation-based comments ( /** */  ). We also explored how to effectively use comments for debugging, as well as the best practices and risks when using comments in general.

All this being said, remember coding comments are a great tool to use – whether it’s with JavaScript or some other programming language. Knowing how to use them properly can vastly enhance and smooth out the kinks in the development process, and just make your life that much easier. Even if it seems tedious to have to update comments, they can be worth it – especially if you can’t finish your programming in one sitting.

Best of luck on your journey to code JavaScript with confidence!!!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
An Introduction to Multidimensional Arrays in JavaScript https://gamedevacademy.org/multidimensional-arrays-javascript-tutorial/ Fri, 19 Feb 2021 01:00:59 +0000 https://coding.degree/?p=810 Read more]]>

You can access the full course here: JavaScript Programming for Beginners

Using Multidimensional Arrays

Multidimensional Arrays are Arrays that contain other Arrays. For example: let mArr = [[1,2,3],[4,5,6,7]]. This allows for an intuitive way to store 2D, 3D, or even higher dimensional values. In the simplest case, for example a 2D Array, you can think of it like a table with rows, columns, and an intersecting cell containing information like in a spreadsheet.

Declaring Multidimensional Arrays

Considering the multidimensional Array shown above we can visualize 4 rows and 4 columns. Let’s start by coding a simple example.

let a = [[1, 2, 3], [4, 5, 6, 7]];
console.log(a);

Browser Developer Console output:

▶︎ (2) [Array(3), Array(4)]

We can see in the console an Array that contains two elements both of which are Arrays; a multidimensional Array. We can also notice that the first Array has three elements and the second has four elements. Let’s open it up further in the console to see inside the multidimensional Array. The first Array is at index zero and the second Array is at index one. Also notice the length property of the main Array.

▼ (2) [Array(3), Array(4)]
  ▶︎ 0: (3) [1, 2, 3]
  ▶︎ 1: (4) [4, 5, 6, 7]
    length: 2

Accessing Array Elements

To help visualize how to access Array elements, you can open up the Arrays inside the main Array to see each index and its value.

▼ (2) [Array(3), Array(4)]
  ▼ 0: Array(3)
        0: 1
        1: 2
        2: 3
        length: 3
      ▶︎ __proto__: Array(0)
  ▼ 1: Array(4)
        0: 4
        1: 5
        2: 6
        3: 7
        length: 4
      ▶︎ __proto__: Array(0)
    length: 2
  ▶︎ __proto__: Array(0)

Let’s write code to log to the console the value of  6 from the second Array. Since Arrays are zero-based, use its index position to return the corresponding value. Access the main Array first by typing a inside the console.log() statement. Next in the first set of square brackets identify which element of the main Array contains the element we are looking for; in this case 1 since it’s the second element. Finally, add a second pair of square brackets and use the index associated with the value we are seeking; in this case it’s the third element (n) which is index 2 (n - 1)

let a = [[1, 2, 3], [4, 5, 6, 7]];

console.log(a[1][2]);  // 6

Browser Developer Console output:

6

Modifying Array Elements

The same Array index technique can be used to change an array element. Change the element we just selected from the value 6 to the value 100 using the Array selection and Assignment Operator (=)

let a = [[1, 2, 3], [4, 5, 6, 7]];

console.log('BEFORE:', a[1][2]);  // 6

a[1][2] = 100;

console.log('AFTER:', a[1][2]);  // 100

Browser Developer Console output:

BEFORE: 6
AFTER: 100

Challenge

In this lesson’s challenge we need to map an area of made up of three types of terrain: desert, grass, and water. Our assignment is to divide the map into rows and columns showing the location of each type of terrain. For this we will use a multi-dimensional array that is essentially a table where each row and column combination creates a cell where the type of terrain in that area can be stored. This would look similar to creating a table in a spreadsheet.

Diagram for multidimensional array JavaScript challenge

Let’s start by declaring a variable named terrains and assign it to an Array that contains four other Arrays, like rows in a table, matching the terrain in the image above.

let terrains = [
  ['desert', 'desert', 'grass', 'grass'],
  ['desert', 'grass', 'water', 'grass'],
  ['grass', 'grass', 'water', 'water'],
  ['grass', 'grass', 'grass', 'grass']
];

console.log(terrains);

Browser Developer Console output:

▼ (4) [Array(4), Array(4), Array(4), Array(4)]
  ▶︎ 0: (4) ["desert", "desert", "grass", "grass"]
  ▶︎ 1: (4) ["desert", "grass", "water", "grass"]
  ▶︎ 2: (4) ["grass", "grass", "water", "water"]
  ▶︎ 3: (4) ["grass", "grass", "grass", "grass"]
    length: 4
  ▶︎ __proto__: Array(0)

Even though this is a larger Array, we can access any Array element just as we did in the section above. Use the following diagrams to help visualize the process of accessing the value desert from the second row (index 1); first column (index 0)

let terrains = [
  ['desert', 'desert', 'grass', 'grass'],
  ['desert', 'grass', 'water', 'grass'],
  ['grass', 'grass', 'water', 'water'],
  ['grass', 'grass', 'grass', 'grass']
];

let el = terrains[1][0];

console.log(el); // desert

Browser Developer Console output:

desert

Multidimensional JavaScript array with Row 1 circled

Multidimensional JavaScript array with Column 0 circled

Multidimensional JavaScript array with the element in Row 1, Colum 0 circled

Transcript

You’ve arrived to a planet that is about to be terraformed. The local authorities tell you that they need to map the terrain before they can begin the works and they need your help with that. One way of mapping the terrain is to divide it in rows and columns so that each cell stores the information of what’s in that part of the terrain, for example, desert or grass or water. All of that can be stored in a data structure like this.

For this, we’re going to be using multidimensional arrays. Which are simply arrays that contain other arrays. And they’re commonly used to represent this sort of two dimensional data. If you think about it, you could have an array where each row represents a whole list of columns. So you could have an array that has four entries and then each one of those entries can be as another array that can have each one of the cells. That is a bit of an overview of what we will be doing.

Let’s head over to our code editor and get started. Let’s begin by looking at a really simple example of an array that contains other arrays. So I’m gonna create an array, let’s call it a, which will have other arrays as entries. So to create another array here simply add another pair of square brackets. So this is another array. And in that other array, we can have let’s say three numbers. Then I can add another entry to my array and this can be another three numbers or maybe four numbers. Like so.

Let’s show this in the console and see what we get. So as you can see, it shows that we have an array and that each element of this array, each entry is on its own an array. So if you expand on that first entry there you can see that it contains entries as well. So it is an array on its own.

To access properties of these arrays, it’s easy to think of it as different levels. So we are on level zero, we have a. Level zero only has two entries. Entry in position zero, and this one that’s in position one.

For example, if I wanna grab this number two, all I have to do is make sure that I grab this array first. And that array is in position zero. Now that I am in this array, I can see that number two is in position zero, one. So what I do here is add another pair of square brackets and just type one. If we show this in the console, you can see that we are grabbing that number two. So that is the approach that you have to take.

First, you forget that these are arrays. You think that this could be, you know this could be a letter. It doesn’t matter. What’s important is the position in which it’s located. Once you’ve grabbed the array, in this case we grabbed that array that’s position zero. We can think of what’s happening inside of that array and grab the corresponding entry. In this case, position one.

Before we move forward, let’s do a small challenge. Showing the console this number six. So try to find it in a similar way to what I did here. If it’s not clear just yet, that’s perfectly fine. I will show you the solution. So pause the video now and come back for the answer.

Great. Well, the way to do that, let’s type console dot log first, type the name of our array, a. First thing is to find the position of the top level. In this case, this is position zero. This is position one. So I’m gonna type square brackets, one. Now that we found the array that we were looking for, we need to find that number six. And that number six is in position zero, one, two. That means another pair of square brackets and position two. And that should give us number six. And you can use this same approach if you wanted to modify that number.

For example, if I wanna change that number to something else, instead of six I want it to be a hundred. You can access it like so. So same as you do with regular arrays. And in fact this is not really different to any regular array. All that you’re doing is just moving one step at a time further down the data structure.

Let’s look at our terrain example. How can we represent this terrain in a multidimensional array? I’m gonna start by creating this variable and it’s going to be called terrains. And it’s going to be an array. And then each item in the array is going to be one of the rows. So the first row here contains desert, desert, grass, grass. So this first row is going to be an array which is going to contain desert, desert, grass, and grass.

And let’s show this in the console. And as you can see we have an array which only has one entry and that entry is on its own, an array. And that array has all of these terrains. We’re going to do another challenge here. I will let you add the rest of the rows into this array. So pause the video, have a go, and then come back for the solution.

Great. Well, the approach here is simply to just add a comma and then add each one of those other rows, and then just add the data for them. I’m not gonna type all the data on the screen. So I’ve already had that and I’m just going to copy and paste it. As you can see it is pretty straightforward in that regard. I’m just going to fix the indentation and there we go.

Well, that is all for this lesson. As you can see, arrays can contain other arrays as entries. And accessing them is quite straightforward. You simply start by finding the position at the top level and then you go down one level at a time. You can also see that multidimensional arrays are a common way to store this sort of to the slash tabular in JavaScript. So this can be quite useful for various purposes when you need to store this type two dimensional or multidimensional data. Thank you for watching. I will see you in the next lesson.

Interested in continuing? Check out the full JavaScript Programming for Beginners course, which is part of our Full-Stack Web Development Mini-Degree.

]]>
Free Course – Learn JavaScript for Web & Games https://gamedevacademy.org/javascript-complete-course/ Wed, 03 Feb 2021 01:00:51 +0000 https://coding.degree/?p=910 Read more]]>

Explore the programming language of JavaScript – a core fundamental for both web development and HTML5 game development. You can also download the project files used for the course below.

Download the project files

About

In this course taught by Pablo Farias Navarro, you’ll learn JavaScript from scratch and explore in-demand skills that will boost any developer’s toolkit. Starting with the fundamentals of coding itself, you’ll discover techniques for storing data with variables, manipulating data with operators, loops, & more, and even creating functions to create the program logic. Additionally, you’ll also learn the basics of using JavaScript to alter webpages in a variety of ways through the DOM API.

Not only will you master one of the most desired skills for all corners of technology development, but also gain the foundations you’ll need to make interactive web projects, build exciting HTML5 games, and work with popular, modern web frameworks.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
A Bite-Sized Guide to JavaScript https://gamedevacademy.org/bite-size-javascript-tutorial/ Fri, 08 Nov 2019 16:00:43 +0000 https://html5hive.org/?p=2165 Read more]]>

You can access the full course here: Bite-Sized JavaScript

Part 1

Learning Goals

  • Including JavaScript code on a HTML document.
  • Loading JavaScript code from external files.

Hello World

In this lesson we will create a Hello World example in JavaScript.

You will learn how to include JavaScript code inside both HTML documents and in external files.

In this course I will be using Sublime Text for my code editor. You can use whatever code editor you like for this course, but Sublime Text does have a free evaluation version and it can be downloaded from: https://www.sublimetext.com/3

The Direct Link to download Sublime Text: Sublime Text Download

Open your code editor and we will create a new document and save the file as “index.html”

Sublime text editor File menu

File Explorer with index.html file being saved

I will be working in different folders for each one of the lessons in the course. Feel free to use the same folder structure, or use one that suits you the best.

Remember you can download all the source code for the course whenever you wish.

Open the index.html file you just saved in your web browser.

Index.html file right clicked to be opened with Chrome

I will be using Chromium which is the open source version of Google Chrome. You can use any web browser that you want in this course as long as it is a current web browser.

Once the file is open we will begin by typing in some basic HTML code. Keep in mind that when you are using Sublime Text you can auto close the HTML tags by pressing alt and the dot character on the keyboard.

See the HTML code below:

<html>
	<head></head>
	<body>
	    hello
	</body>
</html>

Refresh the page and you should see:

Basic HTML file with hello text

If you happened to type JavaScript code into the file where we type the word “hello” it would not work, see the code below to follow along:

<html>
	<head></head>
	<body>
		hello
		alert("Hello World");
	</body>
</html>

This is the code in JavaScript to render a message box that says “Hello World” but if you refresh the page you will see this:

HTML page with alert script in plain text

So its just being showed as text. We don’t want this, what we want is to make the browser execute or run the line of code we just added instead.

What we can do is use the script tag to tell the browser to treat and run the code properly.

See the HTML code below and follow along:

<html>
	<head></head>
	<body>
		hello
		<script>
                alert("Hello World"); 
                </script>
	</body>
</html>

You can use the script tag to enter JavaScript code in your HTML documents. Everything that is written inside the script tag is treated as JavaScript code and as you will see most code editors will highlight the syntax of your JavaScript code.

Refresh the page now and see what happens:

HTML file with JavaScript Hello World alert

Writing code inside a HTML document like we have been doing here is fine, but what if you wanted to include the same JavaScript code in multiple HTML files or simply keep it more organized?

The best way to do that would be to create an external JavaScript file which will have the file extension .js and in that file you put your JavaScript code and then you include that file inside of your HTML documents.

Create a new file and save it as “script.js” 

File explorer with script.js file being created

We are going to cut and paste the JavaScript code inside of the new file and save. You can get rid of the extra code in the HTML file, but keep the script tag. See the image below:

HTML file with hello and script tags

Now what we need to do is add a source to the HTML file, see the HTML code below to follow along:

<html>
	<head></head>
	<body>
		hello
		<script src=script.js"></script>
	</body>
</html>

Refresh the page, and you will see what we have done works the exact same way:

Script tags calling script.js file

We are including the code of the external file into the HTML document.

If you had multiple HTML files and you wanted to include the same file in all of them, you would simply need to copy this and put it in all the files instead of having to copy a thousand lines of code eventually into each of them.

You can see that both files are in the same folder:

Index.html file in file explorer

If we had another folder here called JS and this script file was inside of that folder, how would we include it?

All you have to do to include it is add the path to the location of that file in here, see the code below:

<html>
	<head></head>
	<body>
		hello
		<script src="js/script.js"></script>
	</body>
</html>

Refresh the page, and it will work:

Script tags calling JS file in other folder

Summary

We have introduced the script tag which is used to include JavaScript code both inside of a HTML document and to load it from external files.

You now know how to include JavaScript code from external files.

We have also looked at the case where the two files are not in the same folder, but the script is in a sub folder.

The SCRIPT tag is used to enter JavaScript code. This code can go either on the HTML document or on external files with a js extension.

Part 2

Learning Goals

  • Declare variables
  • Assign values to variables

Variables are used to store and retrieve values from the memory of your computer. In this lesson you will learn how to create variables in JavaScript.

We will show the value of a variable on a message box in our page.

We can start with an empty HMTL document. We will start by declaring a new variable, see the code below to follow along:

<html>
	<head></head>
	<body>
		Variables
		<script>
		var a;
		var b = 10;
		a = 100;
		
		alert(a);
		</script>
	</body>
</html>

Refresh the page and you should see the following:

Index file with variables a and b

You can also enter text in a variable, see the code below and follow along:

<html>
	<head></head>
	<body>
		Variables
		<script>
		var a;
		var b = 10;
		a = 100;
		
		alert(a);
                var text = "Your Name Here";
		alert(text);
		</script>
	</body>
</html>

Refresh the page, and first you will get the value 100 displayed and then you click the OK box and then you will see this:

JavaScript alert displaying text

Variable names are case sensitive, so a variable called “a” is not the same as “A” see the code below and follow along:

<html>
	<head></head>
	<body>
		Variables
		<script>
		var a;
		var A;
		var b = 10;
		a = 100;
		A = 99;

		alert(A);

		var text = "Your Name Here";
		alert(text);
		</script>
	</body>
</html>

Refresh the page and you will see:

Javascript alert showing A variable

You need to be consistent with your variable naming. A common way to name variables is, when you need to name them with more than one word, for example, a persons name, you can use something that is called CamelCase. See the code below and follow along:

<html>
	<head></head>
	<body>
		Variables
		<script>
		var a;
		var A;
		var b = 10;
		a = 100;
		A = 99;

		alert(A);

		var text = "Your Name Here";
		alert(text);

                var personName; 
		</script>
	</body>
</html>

CamelCase starts with a lowercase letter and then an uppercase letter is used for the next part.

Variables can be used for many things. They can be used to perform mathematical calculations, manipulate text, store different types of data, keep track of the main parameters of your website, of your app, and of your game.

JavaScript supports multiple types of variables, not just numbers and text.

Summary

  • Variables are used to store and retrieve values.
  • To declare variables use the var keyword.
  • To assign a value to a variable use the = sign.
  • Variables can store numbers, text, and other types of data.

Part 3

Learning Goals

  • Learn to use basic arithmetic operations.

In this lesson you will learn how to do simple mathematical operations using JavaScript.

We will cover addition, subtraction, multiplication, and division.

Comments

Comments are used to leave messages in your code for other humans, or your future self, to read and understand what the code does after it has been written.

A good practice is to always comment your code that you write and explain what you are doing with comments when you work on any type of project that requires code.

To enter comments in JavaScript you use two forward slashes “//” and then you type what ever you want after the slashes.

Addition

See the code below and follow along:

<html>
	<head></head>
	<body>
		Arithmetic operations
		<script>
		//addition
		var a = 1000;
		var b = a + 200;
		alert(b);

		</script>
	</body>
</html>

And we get the correct result in the alert window:

JavaScript alert performing addition

You then can add some more numbers to the code, and that works fine as well:

<html>
	<head></head>
	<body>
		Arithmetic operations
		<script>
		//addition
		var a = 1000;
		var b = a + 200 + 100;
		//alert(b);
                </script>
	</body>
</html>

The correct result is displayed again in the alert window:

JavaScript alert performing addition for b variable

Comment the alert(b); line out before moving on.

When you hear the phrase “Comment a line out” it means to convert a line of code into a comment. The line of code will still be there for you to see, but when its commented out it will be treated just as text for humans to read, and not the computer.

Subtraction

We will now look at doing subtraction, see the code below and follow along:

<html>
	<head></head>
	<body>
		Arithmetic operations
		<script>
		//addition
		var a = 1000;
		var b = a + 200 + 100;
		//alert(b);

		//subtraction
		var c = 100 - 50;
		alert(c);
		
		</script>
	</body>
</html>

Refresh the page and you will see the correct result for the subtraction:

JavaScript alert performing subtraction

Multiplication

We will now work with multiplication, see the code below and follow along:

<html>
	<head></head>
	<body>
		Arithmetic operations
		<script>
		//addition
		var a = 1000;
		var b = a + 200 + 100;
		//alert(b);

		//subtraction
		var c = 100 - 50;
		//alert(c);

		//multiplication
		var m = c * 10;
		alert(m);
		
		</script>
	</body>
</html>

Refresh the page and we can see the correct result displayed in the alert window:

JavaScript alert performing multiplication

Division

We will now work on division, see the code below and follow along:

<html>
	<head></head>
	<body>
		Arithmetic operations
		<script>
		//addition
		var a = 1000;
		var b = a + 200 + 100;
		//alert(b);

		//subtraction
		var c = 100 - 50;
		//alert(c);

		//multiplication
		var m = c * 10;
		//alert(m);

		//division
		var d = 500 / 2;
		alert(d);
		
		</script>
	</body>
</html>

Refresh the page and we can see the correct result displayed in the alert window:

JavaScript alert performing division

Combining Operations

You also combine all of the operations together, see the code below and follow along:

<html>
	<head></head>
	<body>
		Arithmetic operations
		<script>
		//addition
		var a = 1000;
		var b = a + 200 + 100;
		//alert(b);

		//subtraction
		var c = 100 - 50;
		//alert(c);

		//multiplication
		var m = c * 10;
		//alert(m);

		//division
		var d = 500 / 2;
		//alert(d);

		//mix
		var combo = 100 + 50 / 2 * 10;
		alert(combo);
		
		</script>
	</body>
</html>

Refresh the page and we can see the correct result displayed in the alert window:

JavaScript alert for combo variable

If you wanted to combine operations and have an operation performed first you will have to use brackets.

See the code below and follow along:

<html>
	<head></head>
	<body>
		Arithmetic operations
		<script>
		//addition
		var a = 1000;
		var b = a + 200 + 100;
		//alert(b);

		//subtraction
		var c = 100 - 50;
		//alert(c);

		//multiplication
		var m = c * 10;
		//alert(m);

		//division
		var d = 500 / 2;
		//alert(d);

		//mix
		var combo = (100 + 50) / 2 * 10;
		alert(combo);
		
		</script>
	</body>
</html>

So in this case the 100+50 operation is executed first.

Refresh the page and we can see the correct result displayed in the alert window:

JavaScript alert for combo variable after changes

A Simple Calculator

Now we will work on a simple calculator that will convert from Celsius degrees to Fahrenheit degrees.

See the code below and follow along:

<html>
	<head></head>
	<body>
		Arithmetic operations
		<script>
		//addition
		var a = 1000;
		var b = a + 200 + 100;
		//alert(b);

		//subtraction
		var c = 100 - 50;
		//alert(c);

		//multiplication
		var m = c * 10;
		//alert(m);

		//division
		var d = 500 / 2;
		//alert(d);

		//mix
		var combo = (100 + 50) / 2 * 10;
		//alert(combo);

		//simple calculator
		//from Celsius to F
		// °C  x  9/5 + 32 = °F
		var C = 25;
		var F = C * 9 / 5 + 32;
		</script>
	</body>
</html>

Refresh the page and we can see the correct result displayed in the alert window:

JavaScript alert for temperature conversion calculation

Lesson Summary

  • Addition: var a = b+1;
  • Subtraction: var a = b-1;
  • Multiplication: var a = b*c;
  • Division: var a = b/c;

 

Transcript 1

In this lesson, we’ll create a hello world example in JavaScript. I’ll teach you how to include Javascript code both inside a HTML document and in external files.

We’re going to start by opening up our code editor. Let’s create a new document and save it as index.html. Now, let’s open this index.html file in our web browser. I’ll be using Chromium which is the open source version of Google Chrome. You can use any web browser that you want for this course. As long as it’s a current web browser.

So I’m going to open this up in Chromium. We’re going to type in some basic HTML code. So I’m going to start by typing in HTML tag. So I’m adding in a head and a body. Inside the body, I’m just going to type in hello. And there we go. Now what happens if I just type in Javascript code here? I’m gonna type in alert(“Hello World”), which is the code to render a message box that says hello world. But as you can see, if I refresh this page, this is being shown as text.

Now, how can we make the browser execute, or run, this line of code? What we can do is use the script tag. So by using the script tag, you can enter javascript code in your HTML documents. Everything that I type inside of the script tag, is treated as javascript code. Lets reload the page again and see what happens now. See how now I get the “Hello World” message on my message box, just like we wanted. Writing code inside of a HTML document, like what we’re doing here, is fine. But what if you wanted to include the same javascript code in multiple HTML files?

Well the best way to do that is by creating an external javascript file. So lets create a new file and save it as script.js. We’re going to cut and paste the javascript code inside of this new file, and save. I’ll be adding another, an attribute here called source, src, and then double quotes. And then I can specify the name of that external file. So if I reload the page now, you’ll see that it works in the exact same way. Because we’re basically including the code of this external file into the HTML document.

What happens if a had another folder here, for instance, called js and this script file was inside of that folder? How can we include it in that case? All you have to do is add the path to the location of that file in here. The folder’s called js. So I will type in js and then forward slash, and the name of the file.

Transcript 2

Variables are used to store and retrieve values from the memory of your computer. And in this lesson, you will learn how to create variables in JavaScript.

I’m gonna start by declaring a new variable. To declare a variable in JavaScript, you use the keyword var. And then you need to give your variable a name, that name can be any word or just a single letter, it cannot contain spaces in between. So I’m gonna call a variable a. In JavaScript when you end a statement, you need to enter a semicolon. So what I’ve done here is declare a new variable and call it a. We also need to assign a value to that variable. You can assign a variable, a value to a variable upon declaration.

So I’m gonna create another variable called b and be using an equal sign, you can give it a value, so b will be equal to 10. You can also assign a value to an existing variable, in which case you don’t have to use the var keyword anymore because that’s only for the declaration part. We’ll give this one a value of 100. Let’s show these variables on our web page. So I’m gonna type in alert, which allows me to show a message box and the name of the variable. This case will be a and I’m gonna close this with a semicolon.

When the page loads, it shows the value of 100, which is the value of the variable called a. You can also enter text in a variable. So let’s call this variable, let’s call it text. And I’m gonna enter some text in here. So to enter text you need to use either single or double quotes. And we can show this on a message box using alert.

So let me reload the page. And we’ll see that it first, firstly it shows me 100, and then I click okay, and then it shows me your name here, the value of this one. Variable names are case sensitive, so a variable called lower case a, is not the same as a variable called upper case A. A common way to name variables is when you need to call them with more than one word, for example, person name, is something that’s called camel case. So you type in different words, in this case personName, and the second word starts and the follow up words start with an upper case or with a capital letter. So this is called a camel case notation. It’s just a convention. That’s just how people normally call their variables.

Another thing for you to know is that the name of the variables, it’s only made for us humans to understand. So the computer doesn’t care if you call your variable name, if you call it sky, if you call it letter x, that’s just for humans to have a sense of what’s going on in our code.

Variables can be used for multiple things, they can be used to perform mathematical calculations, to manipulate text, to store different types of data. And JavaScript supports multiple types of variables, not just numbers and text, as we’ll see further in the course.

Transcript 3

In this lesson, I’m gonna show you how to do simple mathematical operations using JavaScript. We’re gonna cover addition, subtraction, multiplication, and division.

Let me begin by adding in some JavaScript code in here. And I’m gonna start by typing in a comment, messages that you leave in your code for other human beings, or your future self, to read and understand what that code does. It is a good practice to always comment your code to write and to explain what you are doing. To enter comments in JavaScript, you type two forward slashes, and then you can type in anything you want. I’m gonna write in addition.

I’m gonna create a variable called a, which will have a value of 1,000. And I want to know the result of the variable a plus 200, and I’m gonna store that in another variable called b. To assign a variable, as we’ve learned, you will use the equals sign. And if we want to do an addition, we will type in a plus the number. That will give us a result which we can easily show on a message box. As you can see, that gives us the correct result. I don’t want to have this shown each time as we move on, so I’m gonna comment this line out.

To comment code out, it means to convert a line of code into a comment so that it stays around but it’s not executed, it’s treated as text. Let’s look now into subtraction. Let’s create a new variable, and this one will have the value of, let’s say, 100 minus 50. And we can easily show that on a message box. Multiplication. Let’s call it m, and let’s say that this will be c times 10. This one here gave us 50 as a result, and 50 times 10 should give us, let’s reload this page, and you can see the 500 in there.

Division works in a similar way. All we need to do is use the forward-slash sign. Let’s divide 500 by two. Let’s comment that one out so we don’t see it each time. 250, half of the value of that number. Call this one combo, and it’ll be, say, 100 plus 50 divided by two times 10. What happens here is that multiplications and divisions executed first, so this part is the first thing that’s gonna be executed, and then the rest will be added.

Whatever you put inside the brackets gets executed first. In this case, this will be executed first. And now to finish this up, I’m gonna implement a simple calculator that will convert from Celsius degrees to Fahrenheit degrees. And let’s end this by showing it on an alert box.

Interested in continuing? Check out the full Bite-Sized JavaScript course, which is part of our Bite-Sized Coding Academy.

]]>
An Overview of JavaScript Versions https://gamedevacademy.org/es6-es9-javascript-tutorial/ Fri, 19 Jul 2019 15:00:38 +0000 https://html5hive.org/?p=2196 Read more]]>

You can access the full course here: Modern JavaScript – From ES6 to ES9

Part 1

What is new in Javascript ES6-9?

  • ES6:
    • Default parameters – add default values for function parameters
    • String interpolation – build variables right into a string
    • Multiline strings – create strings that span multiple lines
    • Let constants – create variables whose value can never change
    • Classes – simulate object oriented behaviour
    • Array functions – extra, highly efficient functionality attached to arrays
    • Arrow functions – create simple functions more easily
    • Destructing – retrieve values based on reverse interpreting
    • Promises – implement try-catch in Javascript
  • ES7:
    • Array.prototype.includes() – check if a function contains an element
    • Exponentiation operator – raise value to the power of another
  • ES8:
    • Async functions – execute functions in parallel
    • Shared memory and atomics – add threading to Javascript
    • Object.values() and .entries() – fetch values from objects
    • String.padEnd() and .padStart() – add padding at the front or back of strings
    • Object.getOwnPropertyDescriptors() – print description of object
    • Trailing commas – does not cast error if extra comma added
  • ES9:
    • RegEx changes – extra support for regular expressions
    • Rest/Spread properties – quickly apply functionality to ranges of values
    • Asynchronous iteration – pair iterators with promises and async function
    • Rest/Spread properties – quickly apply functionality to ranges of values
    • Asynchronous iteration – pair iterators with promises and async function

Part 2

How to Install and Configure Atom

In this course, we will use the Atom IDE. It allows us to write Javascript on an appealing interface and contains packages that allow us to compile and run Javascript programs. If you want to use a different program, feel free to skip this section. If not, download Atom at this page:

Atom website

Run through the installation wizard and start the program. Create a new folder to contain your project files by selecting menu -> file -> Add Project Folder and selecting the new folder you just created. Next, start a new file by right clicking on the folder in the left-hand pane and selecting New File. Name your file <something>.js like so:

Atom project window with new file window

 

Transcript 1

What is up, everyone, and welcome to our course on modern JavaScript. My name is Nimish, and I’ll be guiding you through the next hour to hour and a half , in which we’ll be learning some of the new features available in the JavaScript language and using it to build up a real working app.

So what is this course all about? Well, the general theme is to teach you the fundamentals of the JavaScript language and also to explore some new features available in JavaScript versions ES6 and above. Currently, at the time of me recording this, we are on ES9, but the versions six through nine have really brought some breakthrough features that have made writing code in JavaScript so much more enjoyable.

We’ll also be building an app throughout this course that will help us to retrieve video game stats from the website Steam. No doubt if you’re big into gaming you’ve heard of Steam, and perhaps even used it to buy a game or two. With our new found knowledge of JavaScript, we’ll be able to retrieve statistics from this website by using a Restful API.

So who should be taking this course? Well, we’re assuming that you have little to no previous knowledge of JavaScript; if you have some knowledge already then you may find some of the concepts a little slow. Nevertheless, we are focusing on the new features in the later versions, so you might pick up a thing or two anyway. We’re assuming that you’re keen to learn about new and advanced JavaScript concepts rather. Some of the new concepts introduced in versions ES6 and above cover some fairly advanced topics, so this will be a good way to gain insight into those. We’re assuming that you’re also interested in data fetching software, as the main app that we’ll be building will be tailored towards fetching software data on video games.

So some of the topics that we’re going to be covering are first of all what’s new in JavaScript ES6 and above. This will just be going over a quick list of the features for each of the versions six through nine. We’ll then be talking about how to install and configure Atom. I personally will be using the text editor or ID Atom as well as some plugins to help me run my code. If you don’t want to use that, that’s totally fine if you’re happier with just a text editor and Terminal (I’ll also show you how to use those).

We’ll then be exploring the JavaScript language basics, but we won’t necessarily be doing them one topic at a time. Rather we’ll be building our project and exploring each feature as we need it. We’ll be focusing, first, on fetching online data with JavaScript, so there will be a few tips and tricks to structuring URLs, how to read the data that is incoming, and then actually passing and using this online data with JavaScript. As I said, we’ll be teaching you the language basics and taking advantage of those new features as we go about building our app.

So this has been a quick intro into the course. I hope you guys are really excited about learning this, because I am super excited to teach it to you, and I look forward to your enjoyment and participation throughout this course. So let’s get started with the JavaScript new features.

Transcript 2

What’s up everyone and welcome to our first topic! This is all about new language features in which we’ll explore some of the features that the JavaScript versions ES6 and above have brought to the table. So we’re going to be focusing on just the brand new and most important features that these versions have brought. We’ll bring each one up as kind of a list of the different items that’s brought and explain one by one what each of those items are going to do. Again we’re going to go through each version since ES5. So we’re going to go six, seven, eight, and nine. And then we’ll explore things feature by feature- and of course version by version.

So starting with ES6, this is where a lot of the changes really started to happen. One of the new things is default parameters. This allows us to add default values to our function parameters so that we can avoid passing them in when calling on functions. There’s the idea of string interpolation added as well. This allows us to pass values into strings and convert them in real time, rather than breaking our strings up. As well, multiline strings further prevent us from breaking strings up by allowing us to build strings over multiple lines. There’s the idea of constants which are essentially values or variables that do not change.

And classes is actually a huge one coming to JavaScript, or that has already come, into the JavaScript ecosystem. This allows us to add object-oriented behavior in JavaScript.

Next up we have a whole host of highly efficient and highly functional array functions introduced in this version. We have also arrow functions, which are ways to simplify our function syntax and creates really quick functions that have very fast and quick to implement functionality (it basically makes our process even faster). There’s the idea of deconstructing, which is essentially allowing our compiler to interpret values without us explicitly having to state them, especially when dealing with dictionaries and objects.

There’s also the concept of promises. Now promises is a little bit more complex, so we’ll be exploring promises in much greater detail. Essentially they provide a clean and safe way to guarantee that something will have a value, especially when paired with asynchronous functions.

Now in ES7, we have the array.prototype.includes function, so this is just yet another array function. It’s a way to just determine if an array contains a value. There’s also the exponentiation operator. This is essentially just raising something to the power of something else. For example, we can now do five to the power of two to get 25, rather than just having to multiply things out a bunch of times.

In ES8 we have asynchronous functions. This is, again, a massive new feature. Asynchronous functions are functions that do not work one after the other; that would be synchronous. Instead, they work in parallel and allow us to execute multiple functions all at the same time. There’s also the concept of shared memory and atomics. This is actually a little beyond the scope of this course, so we won’t really be talking too much about that.

There are object.values and object.entries. This is a way to treat our objects kind of like dictionaries, wherein we can get the parameter names and the actual, or rather, the field names and the actual values associated with them by either the values or entries respectively. There’s also the string.padend and padstart functions. This is just a way to add extra characters to the end or to the beginning of a string. Object.getownpropertydescriptors is a way to print out a big string description of an object and all of its entities.

And they’re also trailing commas now this isn’t huge, but it’s nice if in case we forget to close off or rather end a comma if we’re listing a bunch of items. It doesn’t matter if we include that final extra one.

So ES9 is our last one. First up we have RegEx changes, so this is regular expression changes. To be honest, I personally don’t like using regular expressions when possible, and I found I actually don’t have to use them too much, so we won’t really be covering the regular expressions changes so much. Rather if you are super interested, you can definitely check those out. ES9 has added a bunch of support.

There are also Rest and spread properties. These are really cool, as they allow us to essentially build up ranges of values through using three ellipses put together, and this allows a compiler to interpret what values come next in a series of values. After this, we have asynchronous iteration. That’s actually the last big one, and it just lends more powerful support to our asynchronous functionality.

So we’ll explore most of these features but not all of them; some of them are just beyond the scope of this course, because we’re trying to keep things fast and to the point. However, as much as possible, we will incorporate them into our general JavaScript intro concept.

So next up we’ll be actually installing the tools that we’ll need and learning how to set up and run our project, so stay tuned for that. Thanks very much for watching, I will see you guys in the next section.

Transcript 3

What’s up, everyone? Welcome to the second topic in our tutorial series. Here, we’ll be installing Atom, which is a simple IDE that allows us to write and, if we install the right plugins, run JavaScript code. So we’ll start by showing you how to update Atom if you already have it installed, and then we’ll show you how to download and install Atom if you don’t already have it installed on your system.

Now, I should preface this by saying Atom is just one IDE of many out there that will allow you to run and write JavaScript code. If you really don’t want to use an IDE like Atom, that’s fine. You can actually ignore this, and you can just move on to the next section. And that way, you can just kind of run things through Terminal and a simple text editor. We’re gonna have to do some Terminal commands anyways. So if you want to stay clear of Atom, that is totally fine.

But for those of you who are interested, I personally will be using Atom for most of my functionality. So let’s get started. Now, the first thing you might want to do is actually update Atom itself, so this is what it looks like if I have Atom started up with no project going right now. If I want to just update it, I can simply go to Atom, up to check for update, and it actually even tells you the version there. It says no update available. 1.36.0 is the latest version at this time, but depending on when you’re watching it you might have a later version, so just go ahead and update it that way.

If you don’t already have this then you can simply open the browser, go for download Atom, select this first link here, Atom.io. And then go to select your correct platform. For me it auto comes up as MacOS, and I think it should automatically select your system. Then go ahead and click Download, open up the file, and run through the installation with it once you are done.

Now as I said before, you really don’t have to use Atom if you don’t want. I will be using Atom to write most of my codes, so if you do use a different text editor, then things will look a little different. I will show you in a couple of tutorials how to create an NPM project or a node.js project and run through things just using Node.js and the Terminal. That’s going to be an important skill to have, as we’ll need that for some of the packages we’ll install anyway. So like I said if you don’t want to do this, that’s fine you can stick with just Terminal and a basic text editor.

However this next section is going to be configuring Atom, so if you don’t want to use Atom just skip over it and move on to the Node.js part. Okay, so thanks for watching we’ll see you guys in the next one.

Interested in continuing? Check out the full Modern JavaScript – From ES6 to ES9 course, which is part of our Full-Stack Web Development Mini-Degree.

]]>
Full-Stack Web Development Mini-Degree https://gamedevacademy.org/full-stack-web-development-mini-degree/ Sat, 17 Nov 2018 00:30:58 +0000 https://html5hive.org/?p=1961 Read more]]> Go from Zero to Full-Stack Engineer as you build web apps with HTML5, JavaScript, NodeJS, MongoDB, React, GraphQL, Angular, Git, AWS, and Azure. 

This project-oriented curriculum begins by covering the foundations of programming and web development. You’ll learn to create responsive and interactive websites as you get familiar with the basics. We’ll then move on to the server-side and introduce Node.js, Express, Mongo and other frameworks. You’ll be building webapps, REST API’s and scripts.

Following the server-side, we’ll delve further into front-end, this time covering modern frameworks for creating robust applications such as React and Angular. You’ll learn how to integrate these projects with Node.js back-ends and API’s. Finally, you’ll be shown how to use important tools such as Git and Github, and the deployment process to popular platforms such as AWS, Azure and Heroku.

Access this Mini-Degree on Zenva Academy

]]>