Fundamentals: Part 1 (v1)

Let’s dive right in!

Learning Objectives

Look through these now and then use them to test yourself after doing the assignment:

  • How do you declare a variable?
  • What are three different ways to declare a variable?
  • Which one should you use when?
  • What are the rules for naming variables?
  • What are operators, operands, and operations?
  • What is concatenation and what happens when you add numbers and strings together?
  • What are the different types of operators in JavaScript?
  • What is the difference between == and ===?
  • What are operator precedence values?
  • What are the increment/decrement operators?
    • What is the difference between prefixing and post-fixing them?
  • What are assignment operators?
  • What is the "Unary +" Operator?

Live Session

Watch the following 3 parts of the recording of the live session (21/10/2020) that introduces JavaScript:

Total duration: 175 minutes

Part 1/3 – Duration: 68 minutes

Part 2/3 – Duration: 90 minutes

Part 3/3 – Duration: 14 minutes

Numbers

Numbers are the building blocks of programming logic! In fact, it’s hard to think of any useful programming task that doesn’t involve at least a little basic math… so knowing how numbers work is obviously quite important. Luckily, it’s also fairly straightforward.

Study the following material and implement the concepts in your own web page:

  1. JavaScript Numbers @ W3Schools (You must dedicate at least 4 to 6 hours on this material.)
  2. JavaScript Arithmetic @ W3Schools (You must dedicate at least 40 minutes on this material.)
  3. This MDN article covers the same info from a slightly different point of view. There’s much more that you can do with numbers, but this is all you need at the moment. (You must dedicate at least 2 hours on this material.)
  4. Read through (and code along with!) this article about operators in Javascript. Don’t forget to do the "Tasks" at the bottom of the page! It will give you a pretty good idea of what you can accomplish with numbers (among other things!) in JavaScript.

Here is a neat trick to throw away those decimals from a number using the bitwise NOT operator. We suggest you forget the bitwise operators for now, as it is a rather advanced topic. Just keep this code snippet for whenever you want to quickly convert a floating point number to an integer and impress your fellow JS devs!

let float = 3.1415;
let int = ~~3.1415;
console.log( int );
// 3
console.log( ~~1234.5678 );
// 1234

Variables

Variables are pointers to "storage containers" for data in your code. You can think of variables as something close to your contacts in your mobile phone. Each contact list entry contains a name, e.g. Mary. This is your variable name. And each contact list name (variable name) points to a place in the memory of your mobile phone that stores a telephone number or address, e.g. 6985252114.

VARIABLE NAME POINTER TO DATA IN MEMORY
Mary — Points to –> 6985252114
Ahmed — Points to –> 6971234567

In much the same way, variables in programming languages, are names that point to some memory location in which some kind of data is stored:

var someVariableName = "Just some text.";
// The someVariableName, now points to a place in memory
// where the "Just some text." data is stored and can be retrieved.

Until recently there was only one way to create a variable in JavaScript — the var statement. But in the newest JavaScript versions we have two more ways — let and const.

  1. This variable tutorial will explain you everything you need to know! Be sure to do the Tasks at the end. Information won’t stick without practice! (Estimated reading and practice time for this material: approx. 2 hours). Here is a list of the concepts you’ll be introduced to through this post:
  • What is a variable?
  • Constants
  • Variable naming and naming things right
  • Case sensitivity and reserved names

The above tutorial mentioned this, but it’s important enough to note again: let and const are both relatively new ways to declare variables in JavaScript. In many tutorials (and code) across the internet you’re likely to encounter var statements. Don’t let it bother you! There’s nothing inherently wrong with var, and in most cases var and let behave the same way. But sometimes the behavior of var is not what you would expect. Just stick to let (and const) for now. The precise differences between var and let will be explained later.

Practice!

You can easily run your own JavaScript code from files you create on your computer. The simplest way to get started is to simply create an HTML file with the JavaScript code inside of it. Type the basic HTML skeleton into a file on your computer somewhere:

<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>
  <meta charset="UTF-8"/>
</head>
<body>
  <script>
    // Your JavaScript goes here!
    console.log("Hello, World!")
  </script>
</body>
</html>

Save and open this file up in a web browser and then open up the browser’s console by right-clicking on the blank webpage and selecting "Inspect" or "Inspect Element". In the ‘Developer Tools’ pane find and select the ‘Console’ tab, where you should see the output of our console.log statement.

console.log() is the command to print something to the developer console in your browser. Use it for all of the following exercises.

Try the following exercises:

  1. Add 2 numbers together! (just type console.log(23 + 97) into your html file)
  2. Add a sequence of 6 different numbers together.
  3. Print the solution to the following equation: (4 + 6 + 9) / 77
    1. answer should be approximately 0.24675
  4. Let’s use variables!
    1. Type the following at the top of the script tag: let a = 10
    2. console.log(a) should print 10
    3. Try the following: 9 * a
    4. and this: let b = 7 * a (returns undefined) and then console.log(b)
  5. You should be getting the hang of this by now… try this sequence:
    1. Declare a constant variable max with the value 57
    2. Set another variable actual to max - 13
    3. Set another variable percentage to actual / max
    4. If you type percentage in the console and press enter you should see a value like 0.7719
  6. Can you think of any real-life scenarios where Numbers and the arithmetic operators of JavaScript can be of use? Take the time to implement these scenarios in your code and add them to the web page. Here’s an example to get you started:

How about using JavaScript to calculate the VAT (or some other kind of tax) for a product?

const VAT = 24;    // VAT Tax is set to 24%
const phone = 300; // Net price
const total = phone + ( phone * ( VAT / 100 ) ); // Total === net price + VAT

How about using JavaScript to calculate the number of calories burned while walking or any other activity?

How about calculating a woman’s fertile window?

Blood alcohol content anyone?

There is no shortage of (really useful) ideas to implement in JavaScript using Numbers and the arithmetic operators, so let’s get to work!


Take a few minutes to keep playing around with various things in your script tag. Eventually, we will learn how to actually make those numbers and things show up on the webpage, but all of this logic will remain the same, so make sure you’re comfortable with it before moving on.

Additional Resources

This section contains helpful links to other content.

Assignment

Click this link and follow the instructions on how to complete and submit this assignment.


Material based on Erik Trautman | The Odin Project
LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack

UPDATED: 02.02.2021

  • [16.11.2020] Added article for variable shadowing
  • [27.11.2020] Added the bitwise operator rounding trick

CONTRIBUTORS:

Events

Introduction to Events

In the previous topic we learned how we can manipulate the DOM. So in this topic we will learn how we can make that happen dynamically. The way we do it is using events. Events are actions that occur on our web page. For example a mouse-click or a keypress are events and we can use JavaScript to make our web page to listen and react to those events.

There are three primary ways to handle the events:

  1. Attach functions attributes directly on the HTML elements
  2. Set the on_event_ property on the DOM object in our JavaScript
  3. Attach event listeners to the nodes in our JavaScript

The third way with the event listeners is definitely the preferred method. However we will regularly see the others in use, so we’re going to cover all three.

Learning Objectives

  • How "events" and "listeners" work.
  • The three ways to use events in our code
  • How "bubbling" works.

Basic Example

Now we are going to see a basic example using all three methods. So we are going to create 3 buttons that all alert "BUTTON" when clicked.

You can try them all out using your own HTML file, or using something like CodePen.

Method 1 (Not recommended)

<button onclick="alert('BUTTON')">Click Me</button>

This way is less than ideal because we are cluttering our HTML with JavaScript. In addition, we can only have 1 "onclick" event per element.

Method 2 (Not recommended)

<!-- HTML FILE -->
<button id="btn">Click Me</button>
// JAVASCRIPT FILE
const btn = document.querySelector('#btn');
btn.onclick = () => alert("BUTTON");

*If you need further assistance with the arrow functions check this link: Arrow Functions Basics.

This way is a little better since we have moved the JS out of the HTML and into a JS file. However we still have the problem that a DOM element can only have 1 "onclick" property.

Method 3 (Recommended)

<!-- HTML FILE -->
<button id="btn">Click Me Too</button>
// JAVASCRIPT FILE
const btn = document.querySelector('#btn');
btn.addEventListener('click', () => {
  alert("BUTTON");
});

This way is much better since we have our HTML and JavaScript separated and we also allow multiple event listeners if the need arises. Although it is a bit more complex to set up, it is more flexible.

We can also use these methods with named functions if we want to.

<!-- HTML FILE -->
<!-- METHOD 1 -->
<button id="btn" onclick="alertFunction()">CLICK ME AGAIN</button>
// JAVASCRIPT FILE
const btn = document.querySelector('#btn');
function alertFunction() {
  alert("BUTTON");
}

// METHOD 2
btn.onclick = alertFunction;

// METHOD 3
btn.addEventListener('click', alertFunction);

It is a really good idea to name the functions. The code is cleaner and it is really handy if you are going to use it in multiple places.

If we want we can access more information about the events. We can do that by passing a parameter to the function we are calling. Let’s see how we can do it.

// JAVASCRIPT FILE
btn.addEventListener('click', function (e) {
  console.log(e);
});

*Note that function (e) is a callback from addEventListener. If you need further assistance with callbacks you can check this link Callbacks.

The e in that function is an object that references the event itself. Within that object you have access to many useful properties and functions such as which mouse button or key was pressed, or information about the event’s target. The target refers to the DOM node that was clicked.

So we can access the button by accessing the target property as:

// JAVASCRIPT FILE
btn.addEventListener('click', function (e) {
  console.log(e.target);
});

and then we can change the background color of the button as:

// JAVASCRIPT FILE
btn.addEventListener('click', function (e) {
  e.target.style.background = 'purple';
});

Attaching listeners to groups of nodes

In case we want to attach similar event listeners to many elements there is a way to make our code more efficient rather than writing the same code over and over again.

In previous topics we learned that we can get a nodelist of all the items matching a specific selector. We can do that with the querySelectorAll('selector'). So in order to add a listener to all of them all we have to do is to iterate through the entire list.

<!-- HTML FILE -->
<div id="wrapper">
    <button id="1">Click Me</button>
    <button id="2">Click Me</button>
    <button id="3">Click Me</button>
</div>
// JAVASCRIPT FILE

// buttons is a node list. It looks and acts much like an array.
const btns = document.querySelectorAll('button');

// we use the .forEach method to iterate through each button
btns.forEach((btn) => {

  // and for each one we add a 'click' listener
  btn.addEventListener('click', () => {
    alert(btn.id);
  });
});

What we have learned so far in regards to DOM manipulation and event handling is just the tip of the iceberg. However you have learned enough so as to complete some exercises.

In our previous examples we have used the click event but there are a lot more available to you!

Below is a list of some useful events:

  • click
  • dblclick
  • keypress
  • keydown
  • keyup

In this page HTML DOM Events you will find a more complete list of events as well as an explanation of each one.

Avoiding Confusion

As you’ve seen, you can define an event handler in 3 different ways.

  1. Using the addEventListener method (Recommended)
document.querySelector(".box").addEventListener( "click", function( event ){ ... });
document.querySelector("form").addEventListener( "submit", function( event ){ ... });
document.body.addEventListener( "keyup", function( event ){ ... });
  1. Using the on<EVENTNAME> property syntax (Not recommended)
document.querySelector(".box").onclick = function( event ){ ... };
document.querySelector("form").onsubmit = function( event ){ ... };
document.body.addEventListener.onkeyup = function( event ){ ... };
  1. Using an attribute with the on<EVENTNAME> directly in an HTML element (Not recommended):
<div class="box" onclick="clickHandler()">Click me</div>
<form onsubmit="submit()">
    <!-- CONTENT -->
</form>
<body onkeyup="handleKey()">

Events in the first syntax are used like this (nouns): ‘click’, ‘submit’, ‘change’, ‘scroll’, etc.

While using the 2nd syntax, are prefixed with the ‘on’ keyword: ‘onclick’, ‘onsubmit’, ‘onchange’, ‘onscroll’, etc.

The second syntax corresponds to element properties and should not be confused with the event names used in the first case.

Additional Resources

In this section you can find a lot of helpful links to other content. This is a supplemental material for you if you want to dive deeper into some concepts.


The archived old version of this post can be found here

UPDATED: 03.06.2021

LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack

Feedback

  • Is there anything we can help with up to this point? Do you have something to suggest about this chapter? Let us know in the comments below.

Project: Calculator

Introduction

Up until now you should have a really firm grasp on the fundamentals of JavaScript and you should be able to create quite a bit.

Therefore for the final project you are going to create an on-screen calculator. In this project you will combine what you have learned so far in HTML, CSS and JavaScript.

Keep in mind that there are elements in this project that isn’t going to be easy for you. However we have covered all the knowledge needed it to complete it. As usual we are going to walk you through the various steps you can take but once again the implementation is up to you.

Important Note: Before you get started with this calculator project, we need to cover a word of warning. As you look into how to evaluate complex mathematical statements in JavaScript, you will likely come across the tantalizing eval() function. However, this function can be very dangerous and should not ever be used! You’ll need to build your own functions to evaluate expressions as part of this calculator project.

Assignment

Let’s see some use cases (abilities your project needs to have):

  1. Your calculator is going to contain functions for all of the basic math operators you typically find on simple calculators, so start by creating functions for the following items and testing them in your browser’s console.

    1. add
    2. subtract
    3. multiply
    4. divide
  2. Create a new function operate that takes an operator and 2 numbers and then calls one of the above functions on the numbers.

  3. Create a basic HTML calculator with buttons for each digit, each of the above functions and an "Equals" key.

    1. Do not worry about wiring up the JS just yet.
    2. There should also be a display for the calculator, go ahead and fill it with some dummy numbers so you can get it looking right.
    3. Add a "clear" button.
  4. Create the functions that populate the display when you click the number buttons… you should be storing the ‘display value’ in a variable somewhere for use in the next step.

  5. Make the calculator work! You’ll need to store the first number that is input into the calculator when a user presses an operator, and also save which operation has been chosen and then operate() on them when the user presses the "=" key.

    1. You should already have the code that can populate the display, so once operate() has been called, update the display with the ‘solution’ to the operation.
    2. This is the hardest part of the project. You need to figure out how to store all the values and call the operate function with them. Don’t feel bad if it takes you a while to figure out the logic.
  6. Gotchas: watch out for and fix these bugs if they show up in your code:

    1. Users should be able to string together several operations and get the right answer, with each pair of numbers being evaluated at a time. For example, 12 + 7 - 5 * 3 = should yield 42. An example of the behavior we’re looking for would be this online calculator: https://www.theonlinecalculator.com/. Note that this behavior means your calculator is not required to follow order of operations, aka PEMDAS (though there’s nothing stopping you from implementing PEMDAS if you feel like it!).
    2. You should round answers with long decimals so that they don’t overflow the screen.
    3. Pressing = before entering all of the numbers or an operator could cause problems!
    4. Pressing "clear" should wipe out any existing data.. make sure the user is really starting fresh after pressing "clear"
    5. Display a snarky error message if the user tries to divide by 0… don’t let it crash your calculator!

EXTRAS

  1. EXTRA CREDIT: Users can get floating point numbers if they do the math required to get one, but they can’t type them in yet. Add a . button and let users input decimals! Make sure you don’t let them type more than one though: 12.3.56.5. It is hard to do math on these numbers. (disable the decimal button if there’s already one in the display)

  2. EXTRA CREDIT: Make it look nice! This can be a good portfolio project… but not if it’s UGLY. At least make the operations a different color from the keypad buttons.

  3. EXTRA CREDIT: Add a "backspace" button, so the user can undo if they click the wrong number.

  4. EXTRA CREDIT: Add keyboard support!

Submission

Create a private GitHub repository, add your solution code along with your instructor(s) as collaborator(s) and submit the URL in the quiz below.

Additional Resources

How To Make Calculator using HTML CSS & JavaScript


The archived old version of this post can be found here

UPDATED: 03.06.2021

CONTRIBUTORS

LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack

Fundamentals: Part 5

Introduction to Objects

Objects are a very important part of the JavaScript language. Although simple and even intermediate tasks can be accomplished without them, any real project that you are going to attempt is going to feature Objects.

In this topic we are going to cover the basics and later on we will dive deeper.

Let’s get started!

  1. This JavaScript.info article is the best place to get started with Objects.

  2. The MDN tutorial isn’t bad either, so check it out if you need another take on the subject.

Intermediate/Advanced Array Magic

Arrays are not only a handy way to store data but also have a set of functions for manipulating that data. These functions are very important and once you start using them you will see that the possibilities of what you can do with them are near endless.

Objectives of these section:

  • Learn about the forEach Array method

  • Learn about the filter Array method

  • Learn about the map Array method

  • Learn about the sort Array method

  • Learn about the reduce Array method

  1. Start out by watching the video JavaScript Array Cardio Practice – Day 1 from Wes Bos.

Duration: 24 minutes

To follow along clone the JavaScript30 repository.

  1. Watch and code with Part 2 of Wes Bos’s array series.

Duration: 8 minutes

Practice

Up until now you have been through a ton of content, and it would not be surprising if you were feeling rather overwhelmed at this point. Thus we will practice some of this stuff with coding exercises.

Be aware that those exercises get pretty difficult. However we have covered everything you need to know to solve them. Don’t forget to go back and review if you find that you can’t remember something. In addition if you get stuck reach out for help in the usual channels.

Exercise

Go to the Exercises Repository and follow the instructions on how to complete and submit the exercise.

Want MORE practice?

You really can’t spend too much time reviewing and practicing the fundamentals that we’ve covered here and luckily for you there are several websites that offer just this type of thing. Seriously, the better you grasp and the more fluently you can use the fundamental building blocks of JavaScript, the easier the hard stuff is going to come to you when we get to it. Take a minute to check out the following links.

  • Exercism – Uses a neat command-line interface to download and submit exercises and allows you to give and get feedback on your solutions.

  • CodeWars – A neat gamified system with leveled exercises. As you complete more exercises you level up and access more difficult ones.

  • HackerRank – Similar in setup to CodeWars, but this site is more focused on interview question type tasks. Some companies even use this site to interview candidates.


The archived old version of this post can be found here

UPDATED: 12.11.2020

LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack

Project: Etch-a-Sketch

Introduction

In this project you will create a browser version of something between a sketchpad and an Etch-A-Sketch. This application is a good practice to flex your DOM manipulation skills.

Keep in mind that this project should not be easy for you. You will have to google a lot to get the right JavaScript methods and the CSS rules that you should use.

You can build this app using the tools that you have already learned. However if you decide you need more stuff to build it, then feel free to check out the plenty of resources that the net provides.

We will walk you through the basic steps, however it will be up to you to actually implement them.

Instructions

Follow the instructions here in order to complete and submit the exercise.


The archived old version of this post can be found here

UPDATED: 03.06.2020

LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack

DOM Manipulation

Introduction to DOM

One of the most unique and useful abilities of JavaScript is its ability to manipulate the web pages. It can manipulate both the HTML and CSS of any web page through the DOM. But what is the DOM, and how do we go about changing it? Let’s jump right in…

Learning Objectives

  • DOM in relation to a web page
  • The difference between a "node" and an "element"
  • How to target nodes with "selectors"
  • The basic methods for finding/adding/removing and altering DOM nodes
  • The difference between a "nodelist" and an "array of nodes"

Study

Watch An Introduction to Browser Rendering.

Duration: 8 minutes

Read: What, exactly, is the DOM?

DOM – Document Object Model

The DOM (or Document Object Model) is a tree-like representation of the contents of a webpage – a tree of "nodes" with different relationships depending on how they’re arranged in the HTML document.

<div id="wrapper">
  <div class="main"></div>
  <div class="secondary"></div>
</div>

In the above example, the <div class="main"></div> is a "child" of <div id="wrapper"></div> and a sibling to <div class="secondary"></div>. Think of it like a family tree. <div id="wrapper"></div> is a parent, with its children on the next level, each on their own "branch".

How to Target Nodes with Selectors

If we want to target a specific node that we want to work with then we use the selectors. These selectors can be a combination of CSS-style selectors and relationship properties.

We will start with the CSS-style selectors. If we want to target the <div class="main"></div> node then we could use the following selectors:

  • div.main
  • .main
  • #wrapper > .main
  • div#wrapper > div.main

In addition we can use relational selectors (i.e. firstElementChild or lastElementChild etc.) with special properties owned by the nodes.

const wrapper = document.querySelector('#wrapper');
// select the #wrapper div (don't worry about the syntax, we'll get there)

console.dir(wrapper.firstElementChild);                      
// select the first child of #wrapper => .main

const secondary = document.querySelector('.secondary');   
// select the .secondary div

console.dir(secondary.previousElementSibling);                  
// selects the prior sibling => .main

Basically in the examples above we identifying a certain node based on its relationship to the other nodes around it.

Introduction to DOM Methods

As stated before when the HTML code is parsed by a web browser it is converted to the DOM. Those nodes are objects that have many methods and properties attached to them. Therefore we use those methods and properties to manipulate our web page with JavaScript.

We will start with the query selectors and those selectors help us to target nodes.

Target an Element with Query Selectors

  • element.querySelector(selector) returns reference to the first match of selector
  • element.querySelectorAll(selectors) returns a "nodelist" containing references to all of the matches of the selectors

*There are several other, more specific queries, that offer potential (marginal) performance benefits, but we won’t be going over them now.

Important note: When using querySelectorAll, the return value is not an array. Although it might look an array it somewhat acts like an array, but it’s really a "nodelist". The big difference is that several array methods are missing from nodelists. One solution is to convert the nodelist into an array. You can do this with Array.from() or the spread operator.

Create Elements

  • document.createElement(tagName[, options]) creates a new element of tag type tagName. [options] in this case means you can add some optional parameters to the function.
const div = document.createElement('div');

Keep in mind that this function does NOT put your new element into the DOM – it simply creates it in memory. Thus before you place the element to the DOM you can add styles, classes, ids, text etc.

Then you can add that element to the DOM with the following methods.

Append Elements

  • parentNode.appendChild(childNode) appends childNode as the last child of parentNode
  • parentNode.insertBefore(newNode, referenceNode) inserts newNode into parentNode before referenceNode

Remove Elements

  • parentNode.removeChild(child) removes child from parentNode on the DOM and returns reference to child

Altering Elements

We can also alter the element’s own properties. In other words when we have a reference to an element we can use that reference and do many alterations to the element itself, such as add or remove an attribute, change classes, adding styles and much more.

Let’s see an example. First we will create a div element.

const div = document.createElement('div');                     
// create a new div referenced in the variable 'div'

In the following sections we will use that div to do several alterations to it.

Inline style

Now we will add the color purple and the background color gray in to our previously created div.

div.style.color = 'purple';                                      
// adds the indicated style rule

div.style.cssText = 'color: purple; background: gray';          
// adds several style rules

div.setAttribute('style', 'color: purple; background: gray');    
// adds several style rules

For further information on inline styles see the DOM Enlightenment’s section on CSS Style rules.

Please be aware that if you’re accessing a kebab-cased css rule from JS, you’ll either need to use camelcase or you’ll need to use bracket notation instead of dot notation.

For example:

div.style.background-color // doesn't work - attempts to subtract color from div.style.background
div.style.backgroundColor // accesses the divs background-color style
div.style['background-color'] // also works
div.style.cssText = "background-color: white" // ok in a string

Attributes

Now let’s see how we can edit an attribute of an element.

div.setAttribute('id', 'myDiv');                              
// if id exists update it to 'myDiv' else create an id
// with value "myDiv"

div.getAttribute('id');                                        
// returns value of specified attribute, in this case
// "myDiv"

div.removeAttribute('id');                                     
// removes specified attribute

For further information on available attributes see MDNs section on HTML Attributes.

Classes

Now we will see some examples of methods we use with the class that our element might has.

div.classList.add('content');                                      
// adds class "content" to our new div

div.classList.remove('content');                                   
// remove "content" class from div

div.classList.toggle('active');                                
// if div doesn't have class "active" then add it, or if
// it does, then remove it

It is often standard (and more clean) to toggle a CSS style rather than adding and removing inline CSS.

Text content

Now we will see how we add text content to our element.

div.textContent = 'My first content!'                               
// creates a text node containing "Hello World!" and
// inserts it in div

HTML content

Now we will see how we add HTML content to our element.

div.innerHTML = '<span>My first content!</span>';                   
// renders the html inside div

*Note that textContent is preferable for adding text, and innerHTML should be used sparingly as it can create security risks if misused. For further information about this topic you can check this article.

Now let’s see an example as a review of what we have covered so far. So in the example we will create a DOM element and we will append it to a webpage.

<!-- HTML FILE -->
<body>
  <h1>
    HERE IS THE TITLE OF YOUR WEBPAGE
  </h1>
  <div id="wrapper"></div>
</body>
// JAVASCRIPT FILE
const wrapper = document.querySelector('#wrapper');

const container = document.createElement('div');
container.classList.add('content');
container.textContent = 'This is our text-content!';

wrapper.appendChild(container);

First we get a reference to the wrapper div that already exists in our HTML. Then we create a new div and store it in the variable container. We add a class and some text to the container div and finally append that div to wrapper.

So, after the JavaScript code is run, our DOM tree will look like this:

<!-- DOM -->
<body>
  <h1>
    HERE IS THE TITLE OF YOUR WEBPAGE
  </h1>
  <div id="wrapper">
  	<div class="content">
      This is our text-content!
    </div>
  </div>
</body>

Something to keep in mind is that the Javascript doesn’t alter our HTML. The HTML file will look the same but the JavaScript changes what the browser renders.

Important note: JavaScript, for the most part, is run whenever the JS file is run, or when the script tag is encountered in the HTML. Therefore, If you include your JavaScript at the top of your file, many of these DOM manipulation methods will not work. This is due to the fact that the JS code is being run before the nodes are created in the DOM. So, the simplest way to fix this is to include your JavaScript at the bottom of your HTML file. In that way the Javascript runs after the DOM nodes are parsed and created.

Additional Resources

In this section you can find a lot of helpful links to other content. This is a supplemental material for you if you want to dive deeper into some concepts.


The archived old version of this post can be found here

UPDATED: 03.06.2021

CONTRIBUTORS:

LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack

Fundamentals: Part 4

Introduction to Arrays

As the scripts get more complex we are going to need a way to deal with large quantities of data. Fortunately JavaScript, apart from numbers and strings, has a couple of data types that are used for just that. An Array is simply an ordered collection of values (Strings, Numbers, other Arrays, etc.).

Watch this short introductory video on Arrays by Code.org:

Duration: 4 minutes

Watch this recorded Live Session (04/11/2020) about String and Array Methods

Part 1/3 | Duration: 1 hour

Part 2/3 | Duration: 2 hours

Part 3/3 | Duration: 1 hour

The code and exercises for this live session can be found here: JavaScript: Array and String Methods.

Do you have any questions regarding the concepts and code presented in the videos? Leave your questions and comments on the comments section at the bottom of the page.

  1. Carefully go through the JavaScript Arrays tutorial at W3Schools and make sure to practice the concepts on your own coding environment. Try as many examples as possible for every concept mentioned in the tutorial and don’t forget to complete the quizzes at the end fo the page. (Estimated reading and practicing time: 8~10h)

Some things to be aware of while going through the tutorial:

Avoid using var to declare variables in JavaScript. Prefer the modern and safer let keyword. You will learn more about the distinction at later chapters and live sessions.

Avoid using vague and meaningless variable names such as x or y as mentioned in the tutorial. Always prefer meaningful and descriptive names. See examples below:

BAD

var x = cars.length;   
var y = cars.sort();   

MUCH BETTER

let carsLength = cars.length;   
let sortedCars = cars.sort();   
  1. Read the JavaScript Array Methods post at W3Schools which covers some of the most useful built-in array methods. These fundamentals are something you’ll use every day, so don’t rush too much and miss out! Practice as much as you can on each concept, create your own examples, try to think of real-life applications for each method and don’t forget to complete the quiz at the end of the page.

The same best practices mentioned above (avoid var, use meaningful variable names) apply to this tutorial also.

You can play around with this codepen we created to get a better understanding of how the Array splice method works.

NOTES: If you are unaware of the following command mentioned in this tutorial, here’s a short explanation of what it does:

document.getElementById("demo").innerHTML = fruits;

This command searches through the document (our HTML page), for an element with id demo and replaces its HTML content with the contents of the fruits variable.

For example, let’s say we have the following HTML content in our document:

<div id="target">Some content here</div>

The following code will replace the current HTML content of this div (Some content here) with <strong>JS rocks!</strong>:

let content = "<strong>JS rocks!</strong>";
document.getElementById("target").innerHTML = content;

The getElementById command is part of the so-called DOM Manipulation API, a fancy word for the set of JavaScript commands available to us for manipulating our page’s HTML and CSS (adding elements, removing elements, creating elements, updating the elements’ content, and much much more). This is the true power of JS.

Introduction to Loops

Programming languages are very useful for completing repetitive tasks. Fortunately computers are able to solve problems that involve lot of calculations multiple times. Something that will take a human hours to complete, computers can do that in a few seconds. As expected the speed depends on the complexity of the calculation as well as the computer itself. A way to make a computer to do a repetitive task is using a loop.

  1. Read this MDN article: Looping Code. This article is a long one, but make sure you tackle the ‘Active Learning’ sections at the bottom of the page.

  2. This article has the same info as the previous one but in slightly different context JavaScript.info (Don’t forget the tasks at the end of the page. You learn best by doing)

Introduction to Test Driven Development

Test Driven Development (TDD) refers to the practice of writing automated tests before completing the entire code. In other words, you write some code and then you test it before you write more code.

For example let’s say you want to write a function that multiplies two numbers and returns their product. With the TDD approach you should first write a test that uses that function and gives the expected output. As expected the test will fail before you write the code and when the tests pass then you know that your code works correctly.

In the example above if we had a simple function such as multiply(2, 2) it wouldn’t be a big deal to check the function ourselves. We would have to run the code over and over again plugging in different numbers until we were sure that it was working. However what would have happened if we had a much more complicated function, for example a function that checks whether or not someone has won a game of tic tac toe gameWin(["o", null,"x",null,"x",null,"x", "o", "o"])? We would have to play multiple games against ourselves to check that the function is working correctly!

For this reason TDD is a much more productive than writing code without tests. Later in this course we will teach you how to write these tests.

In the exercises below we have the tests already written out for you. All you have to do is read the specs and write the code that makes them pass! The very first exercise (01-helloWorld) is intentionally very simple and walks you through the process of running the tests and making them pass.

Exercises

Complete the following exercises found in the repository here and submit the Quiz.


The archived old version of this post can be found here

UPDATED: 27.11.2020

  • [27.11.2020] Added codepen to better understand Array.prototype.splice
LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack

Clean Code

Writing Clean Code

Developers spend SO MUCH more time reading code than writing it. This is true even with your own code. As a favor to yourself and whoever will need to use, maintain, or further develop your code, please learn to write readable code.

Consider the following 2 snippets of JavaScript:
ugly, hard to read code:

const x =
function(z) {
let w = 0;z.forEach(
function(q){
     w += q;
});return w;
};

x([2, 2, 2]);

clean and easy to read code:

const sumArray = function(array) {
  let sum = 0;
  array.forEach(function(number) {
    sum += number;
  });
  return sum;
};

sumArray([2, 2, 2]);

Believe it or not, both of those functions do the exact same thing (in the exact same way!), and both of them are perfectly valid code, but obviously the second one is much easier to follow. Imagine you’re working on a project with someone else and they’ve written the first function… how long is it going to take you to figure out what’s going on there so you can do your work? Imagine you’re working on a project all by yourself and YOU wrote the first function a week or two ago… chances are good that you aren’t going to remember exactly what you were up to there and it’s still going to take you a good while to figure it all out again.

The second one, however, is much easier to follow. Even if you don’t know exactly what everything in the code is doing, things are named clearly enough that you could guess, and the indentation is consistent enough that it’s easy to parse the different parts of the function.

There are many different opinions on what constitutes great JavaScript code. The most important thing is just that you’re consistent. The war between coders that use tabs and coders that use spaces to indent their code is so engrained that it’s essentially a joke by now, but it doesn’t really matter as long as you’re consistent.

Rules of Thumb

  1. Indentation: It doesn’t really matter what style of indentation you use. Various JS style-guides recommend different options, and one is not really superior to the other. What is important, however, is consistency. In our examples we will use 2 spaces for indentation.

  2. Semicolons: Semicolons are mostly optional in JavaScript because the JS compiler will automatically insert them if they are omitted. This functionality CAN break in certain situations leading to bugs in your code so…

It is better to get used to adding semi-colons;

  1. Line length: Again, different style guides will recommend different options for this one, but just about ALL of them suggest limiting the length of each line of code. This rule is not quite as strict as some of the others, but as a general rule, your code will be easier to read if you manually break lines that are longer than about 80 characters. Many code editors have a line in the display to show when you have crossed this threshold. When manually breaking lines, you should indent the second line 2 levels, and should try to break immediately after an operator or comma:
   let reallyReallyLongLine = something + somethingElse + anotherThing +
   		howManyTacos + oneMoreReallyLongThing;
  1. Naming Things: Names for functions and variables should be descriptive. Always use camelCase. To keep things consistent and easy to read, variables should always begin with a noun and functions with a verb. It is ok to use single characters as variable names in the context of a loop or a callback function, but not elsewhere.
   // Good
   const numberOfThings = 10
   const myName = "Thor"
   const selected = true

   // Bad (these start with verbs, could be confused for functions)
   const getCount = 10
   const isSelected = true

   // Good
   function getCount() {
     return numberOfThings
   }

   // Bad (it's a noun)
   function myName() {
     return "Thor"
   }

Study

Read through these articles that discuss a few elements of writing good clean code.

  1. This list of clean-code tips.

  2. This article, and this one too about the role of comments in your code.

  3. Study the following examples (all of them are real examples from student code) and make use to keep these rules in mind when naming variables yourselves:

Proper Naming for Functions and Variables

  • Name your variables and functions according to what they do.
  • Use verbs for functions and nouns for variables
  • Try to use descriptive names.
Example 1

BAD

myFunction(){ ... }
myFunction2(){ ... }

BETTER

function openMenu(){ ... }
function closeWindow(){ ... }
Example 2

BAD

This next function displays a range input field.

function rangeOutput(){ ... }

BETTER

It should probably be named using a verb that describes what it does.

function outputRange(){ ... }
Example 3

BAD

Can you guess what does the next function do? The name is too vague and ambiguous.

propTypeFunction();
Example 4

BAD

let sortArray = [ 1, 3, 2 ];
sortArray.sort();

BETTER

Prefer nouns when naming variables.

let sortedArray = [ 1, 3, 2 ];
sortedArray.sort();
Example 5

BAD

What does the tempArray hold? Try to be more descriptive.

let tempArray = entries.filter( getOdd );

BETTER

let oddEntriesArray = entries.filter( getOdd );
Example 6

BAD

What kind of object does the variable hold?

let object = new Category( categoryId, $categoryName );
// OR:
let object = new Article( articleId,  text);

BETTER

let category = new Category( categoryId, categoryName );
let article = new Article( articleId, text );

Additional Resources

LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack

Project: Rock Paper Scissors

Introduction

In this lesson we are going to make an implementation of the well known game "rock paper scissors". In case you don’t know it you can check the wikipedia article. If you need further assistance then read this article that provides a step-by-step guidance.

For now we are going to play the game from the browser console. However we will revisit it and add a front end later so don’t forget to keep the code on GitHub!

Problem Solving

Before starting your first JavaScript Project, let’s talk about the most important skill for a developer: problem solving. Your primary goal as a developer is to use whatever programming language you know to solve problems.

For most beginners (in programming), problem solving can be a challenging skill regardless of the programming concepts or commands you know. Staring at a blank screen and not knowing where to start is a pretty common situation for beginner programmers. In order to overcome this blocking situations, here are some helpful techniques:

  • Make sure you understand exactly the problem you are trying to solve. Explaining the problem to someone or even yourself can greatly improve your understanding. Drawing diagrams or writing the problem on paper also helps a lot.

  • Come up with a Plan before starting to code. What are the steps that you need to follow and implement? In what order? What technologies, algorithms or commands must you use for each step? How can one step affect subsequent steps?

  • Write the solution in Pseudo Code. You don’t need to start writing JavaScript right ahead. Writing the solution in an easy to read and understand pseudo code helps you understand how each piece of the program fits in the big picture and also what’s the main responsibility of each code section. An example of a user input might be something like the following:

  1. Get input from the user in form of two numbers
  2. Multiply the two numbers and store them in a variable
  3. Display the variable that contains the result in a modal box
  • Divide and Conquer: split your problem into smaller, easier to solve problems. If you feel stuck, you can start from the easiest problem at hand. Avoid trying to solve the problem all at once. It’s always a good approach to break your problem down into smaller ones and reduce complexity.

References:

Assignment

Check the instructions here.

Once you’ve completed and tested your code submit the GitHub URL to the form below.


The archived old version of this post can be found here

UPDATED: 04.05.2021

  • [Added Problem Solving section]
LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack

Fundamentals: Part 3

Introduction to Functions

Up until now you have being writing code to solve various problems. However the code you were writing wasn’t useful. In other words you couldn’t take it and use it over and over again without having to rewrite it. So what would be nice is to write a block of code and use it wherever we want! Here is where the functions come handy. Functions are a very important concept and they are used in many programming languages.

Study

We’ll begin by this short introduction to JavaScript function by Mosh Hamedani and then move on to the reading material that goes in-depth. Try to pause the video, and code along with Mosh, as he describes these basic function concepts.

Watch this recording of our live session with Paulin de Naupois which introduces JavaScript functions.

Duration: 100 minutes

Do you have any questions regarding the concepts and code presented in the videos? Leave your questions and comments on the comments section at the bottom of the page.


Now, we’ll get more serious with a couple of intensive articles.

  1. Start by reading this article Function Basics from Javascript.info. Keep in mind that JavaScript has changed a bit over the years and thus functions have recently received some innovation. This article covers one of the more useful new abilities: ‘default parameters’. (NOTE: The last "task" at the end of this lesson uses loops. Don’t worry about it since you will learn about it in the next lesson. )

  2. Finally, read about Function Expressions in JavaScript to give you a little more context. In addition read this article about Arrow Functions to get an idea about a relatively new feature in modern JavaScript called the arrow function.

Arrow functions are useful but not crucial. So don’t worry if you don’t understand them. However you are going to encounter them as you move forward and thus it’s better that you have at least some idea of what you’re looking at.

  1. Read this article about return values.

  2. Now we will see what parameters and arguments are in the context of the following example function:

function favoriteColor(color)) {
   console.log(color + " is my favorite color!")
}

favoriteColor('Purple')

In JavaScript, parameters are the items listed between the parentheses in the function declaration. Function arguments are the actual values we decide to pass to the function.

In the example above, the function definition is written on the first line: function favoriteColor(color). The parameter, color, is found inside the parentheses. We could just as easily replace color with animal, car, or blah.

By putting color inside the parentheses of the favoriteColor() function, we are telling JavaScript that we will send some value to our favoriteColor function. This means that color is just a placeholder for some future value. But what value are we sending?

The last line, favoriteColor('Purple'), is where we are calling our favoriteColor function and passing the value Purple inside that function. Here, Purple is our argument. We are telling the favoriteColor function, "Please send ‘Purple’ to the favoriteColor function and use ‘Purple’ wherever the ‘color’ placeholder is." As you can see the use of a parameter provide us with the flexibility to declare any color to be our favorite.

Feel free to experiment with the code on your own and replace Purple with your favorite color. Furthermore you can change the argument color in the function declaration and in the function body and see what happens.

  1. Take this interactive tutorial and learn more about the difference between declaring variables with the var keyword and using the let keyword (Preferred way). For now, you can omit the last section (Declaring with const) as it describes concepts that you are not yet familiar with. If you feel adventurous, you try it!

Function vs Block Scopes

Don’t forget to practice before leaving this interactive tutorial.

  1. Finally, take a look at this lengthy MDN article. Pay special attention to the sections on ‘Function Scope’. Scope is a topic that is tricky to both beginner and intermediate coders. For this reason it is a good idea to spend some time with it up front. See if there are sections in the article that supplement the previous resources.

You can open this Codepen demo and hover over the functions and variables in the code to see them colored depending on the scope they belong to.

Code Smell (Alert)

The wikipedia article on Code Smells, describes them as follows: In computer programming, a code smell is any characteristic in the source code of a program that possibly indicates a deeper problem.

At this point, and since we are introduced to functions, you need to watch the following video and keep the suggestions and rules mentioned in it in your course notebook (try using pen and paper on some of the notes. They will greatly improve your learning efficiency. Keeping a digital version of the notes, also comes in handy.). From now on, and whenever you are creating functions, keep these best practices in mind and try to avoid code smells.

Smelly code and long functions Duration: 3 minutes

After watching the video, continue by reading the following article by Martin Fowler*

*You definitely want to bookmark Martin Fowler’s site and follow him online.

The arguments object

Watch this video from an SHA Live Session (25.11.2020) which explains the arguments object which is accessible inside functions declared with the function keyword.

What you’ll learn:

  • What is the arguments object?
  • What is its type?
  • Can it be used as an argument?
  • What are its use cases?
  • Is it helpful if it is converted into an Array?
  • What type of data types does the arguments object accept? (In short: any value)

Duration: 25 minutes

How do you convert the arguments object into an Array?

function a(){

	const arrArg = Array.from(arguments);
	console.log( arrArg.reverse() );

}

a(1,2,3);

References:

Assignment

Follow the instructions found in the Exercises Repository and submit your assignment.


The archived old version of this post can be found here

UPDATED: 03.06.2021

  • [13.03.2021] Added Colored Scope Codepen demo
  • Adding video about the arguments object
LOOKING FOR HELP?

When looking for help, try doing so in the following order:

  • Did you try everything you could?
  • Did you read the documentation?
  • Did you Google for it?
  • Did you post your question on Slack/Forum?
  • Did you ask your fellow students for help?
  • Did you ask your Mentors for help?
  • Did you leave a comment on the comments section of this page?
  • Did you ask your Instructor for help?
    • Did you arrange and appointment with your instructor using Calendly? Visit this URL and set up an appointment: https://calendly.com/kostasx
    • Is it urgent? Did you try reaching him on Slack