test

All complex concepts, like programming, are generally many simpler concepts put together. This post is going to look at the basic building blocks of programming using Javascript.


Starting out

When you are first starting out programming, you generally want to try and print something to the screen. This is a very basic input/output concept, connecting what you input, potentially changing it or using it in some way, then having the software give an output.

echo to console image

This is an example in the console of the Command Prompt application. hi was entered into the window, but the computer does not know what to do with that. In Windows operating system’s, you have an application called Command Prompt. Whenever you open that, it has a set of commands it can run. Here you can see of an example of Command Prompt using a command called echo that will print back whatever is provided after it.

Side note: you can generally type help when you open tools like Command Prompt to get more information on what you can do.

We’re going to focus on the output of printing something to the screen, but there are other types of ‘outputs’, like taking the input and writing the output into a file for example.


Let’s do something we can all play around on

Because every major operating system includes a web browser, the following is going to show the basics in Javascript. This will allow people reading this on Linux, Mac and Windows all to do the same thing.

Web browsers need to implement the programming language specifications of Javascript, so we can all run each other’s code and expect the same results.

A website does not require Javascript to run, however. It is merely a programming language we can use when we’re creating websites.

Side note: 80px.com does not require javascript to run! Try disabling javascript and see which of your favorite sites still work as you expect.

Let’s get a basic development environment working, and it may become a little clearer.

First create a folder in a place you will remember to hold all of our files. This is necessary so we can have a way to absolutely reference all the other files.

jsplayground/

Now let’s make a file in the jsplayground/ folder and call it index.html

We’re going to use this index.html file to run our javascript programming examples.

Side note: HTML files are generally what you are going to see visually on a web page, like images, text, buttons, links, etc. You can also include non-visual scripts that can modify this visual content in some way.

We’re going to make index.html a blank webpage that includes a script, and an empty visual item (coderesults) to put content into.

HTML stands for Hypertext Markup Language. HTML is what you use to draw elements to the screen using tags. Some tags are for organization purpose, some are for visual items. Here is a minimal html file with all the tags the browser needs to know how to interpret it.


index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>jsplayground</title>
  </head>
  <body>
    <div id="coderesults"></div>
    <script src="script.js"></script>
  </body>
</html>

Taking some time to parse something new can be benefitial in the long run. Here are a some notes about this simple html file:

  • The beginning of the file specifies that we’re using an HTML type of document

    • This helps the browser know what to do
  • We can see the <html> and </html> tags wrap everything after the DOCTYPE

    • We have a hierarchical data structure with multiple tags allowed at one level
  • There are two subsections head and body
  • The title tag in the head will show up in the top of the browser window
  • There is a script tag is looking for a source file called script.js
  • Inside the body, we have a div tag with an id property and it’s value is coderesults

    • There is no content within the div tag, just an open tag and a close tag

Side note: Script tags can be placed in the head or body tag. Because we want to have the div tag available to the script, we place it at the end of the body.

Save the HTML index file, and lets make the script file that the html file is looking for.


script.js

document.getElementById('coderesults').innerHTML = 'writing to the screen in javascript!'

There are a lot of assumptions that happen when you program. It is very much like learning a new language. You are going to have to move on from things you don’t know at first, do research, and increase your understanding over time. You cannot be expected to know what document is in the definitive programming sense, but we can gather some other context clues to narrow down what’s happening in our program.

Let’s assume the document part of this is talking about our index.html document.

Just from the names in this bit of javascript code we can see that:

  • We’re getting an element by an ID

    • coderesults matches our div tag id property
  • The = sign must be saying set something equal to something else

    • We’re setting the inner html of the div tag equal to writing to the screen in javascript!

When we open the index.html file in a browser, we can see that we’re greeted with the text from our javascript file.

javascript code on html page image


Now let’s do some programming basics

We’ve got our javascript code writing to the website and that’s awesome!

Now let’s go over some of the things that basic programming concepts, that javascript has implemented, will allow you to do. The goal is to show you them in order that you may use them.

Concepts

  • Variables

    • Data types
  • Comparison operators
  • Functions
  • Control structures

Variables

Variables are a way to store data inside of your code. This can be something you specify manually, or you can change the variable while the code is running to make it more dynamic.

Let’s specify a variable called firstname and assign it a value of Mark. Let’s write that to the browser coderesult div tag html with an updated script.


script.js

let firstname = 'Mark'

document.getElementById('coderesults').innerHTML = firstname

This is a good simple example of how we’re storing information in a variable, then using that variable in a later piece of code. In this case, updating the div element html.

Notes:

  • We can see that there is a keyword let which is saying the following text is going to be a variable
  • We made the variable name firstname and set the value to Mark
  • The raw value of Mark is wrapped with quotation ' markers

    • This is so the code can determine if it is reading code, or a value that is a string of text
  • There are many types of data you can use for variables

    • In javascript, we don’t have to say this is a string, because it is an inferred language. That means it figures out what type your variable is
    • If we set let age = 2 javascript will now know it is a number and not a string

Basic javascript data types and examples

Data type Example
String 'Hello world'
Number 2
Boolean true
Array ["Circle", "Square", "Line"]
Object { firstInitial: 'T', lastInitial 'S'}

Side note: Javascript started very simply, and is continuously evolving. The above datatypes are the commonly referred to names. When you see something with [] brackets, you can typically call it an Array. Same with {} and Objects. Besides string, number, and boolean, all other data types are complex, and considered to be of type object officially in javascript. That includes Arrays, Objects, and Functions.

Comparison operators

When we’re coding, the language must provide us some tools that we can use on our variables. For example, if we want a program that does different behavior for people aged 65 and older, we need a way to check that the number we have is under or over 65.

These are called comparison operators.

Numbers

  • 1 < 2 for getting a boolean back specifying is 1 less than 2?

    • The response would be true
  • 1 > 2 for getting a boolean back specifying is 1 greater than 2?

    • The response would be false
  • 1 == 2 for getting a boolean back specifying is 1 equal to 2?

    • The response would be false
  • You can also mix and match the greater, and less than signs with equal signs.

    • These are refered to as greater than or equal and less than or equal
    • The result is true if either of the conditions is true.
    • 2 >= 2 would result in true, just as 2 <= 2 would result in true

Strings

  • 'test' == 'test' would return true
  • 'test' == 'test2' would return false
  • 'test' != 'test' would return false

    • Here we are saying does 'test' not equal 'test'?
  • 'test' != 'test2' would return true

    • Here we are saying does 'test' not equal 'test2'?

Functions

Sometimes we want to do a batch of instructions all at once. It makes it easy if we can separate this logic and refer to it later. This is where functions, or methods, come in.

Here is an example function.

function printname(){
  let name = 'Mark'
  return name
}

Notes:

  • Our functions name is printname
  • We specify it is a function with the function keyword
  • Our function has a list of parameters (), in this case we have none
  • The body of the function after the parameters starts with { and ends with }
  • The function does 2 things:

    • Create a variable named name and set the value to the string 'Mark'
    • Return the name variable

Side note: Functions do not have to return variables, but this one does.

Let’s use this in our html script as an example.


script.js

function printname(){
  let name = 'mark'
  return name
}

document.getElementById('coderesults').innerHTML = printname()

Now we are setting the html of the div with coderesults id via the printname() function.

Another important node about functions is that they can be specified to accept input, or parameters.

Let’s modify the script’s printname() function to take in a first name, and a last name, then combine them and add a space in between them.


script.js

function printname(firstname, lastname){
  let fullname = firstname + ' ' + lastname
  return fullname
}

document.getElementById('coderesults').innerHTML = printname('Mark', 'Malone')

Couple things to note here.

  • When we define our function, we’re saying there are 2 parameter. All parameters are separated by commas, in our case firstname and lastname

    • function printname(firstname, lastname)
  • When we call our function, we’re giving it the two parameters to use in the function, in this case 'Mark' and 'Malone' separated with a ,

    • printname('Mark', 'Malone')

Now when we visit our webpage, we can see our html getting updated from a function that we call with a couple parameters.

javascript code on html page image from function code

Control structures

There are a few ways we can control the data that we have. One way is to create a range of numbers, and perform an action for every step in that range. Another might be comparing some data and performing an operation in one case, or performing a different option in another case.

If statements

Let’s start with the simple if, else if and else control statements.

function iftester(stringinput){
  if(stringinput == 'test') {
    return true
  }
  else if(stringinput == 'test2'){
    return false
  }
  else {
    return false
  }
}

Can you see, starting from the top, how the if statement controls what is going to be returned? We are using our comparison operators from before to go within the if statements if the comparison is true.

  • If we called this function with iftester('test'), what would be the result?

    • true
  • iftester('test2')?

    • false
  • iftester('test3')?

    • false

For loops

We can give the script a range of steps to perform operations on. This is a very powerful tool. Let’s use for loops to write the numbers 1 through 10 on our index.html page.


script.js

function printnumbers(){

  // newhtml is an empty string
  let newhtml = ''

  /*
    This is our for loop
  */
  for(let iterator = 1; iterator <= 10; iterator++) {
    newhtml += iterator
  }
  
  return newhtml
}

document.getElementById('coderesults').innerHTML = printnumbers()

We’ve introduced a few new concepts with this, let’s review:

  • You can write comments to help you remember what something is doing in code.

    • In javascript you can do this with // on single line comments
    • Or, wrap your comment with /* and */ to have a comment over multiple lines
  • For loop syntax usually follows this structure:

    • Create a new temporary variable starting at the value you want (let iterator = 1;)
    • Specify the condition in which you are allowed to continue the control (iterator <= 10;)
    • Perform an operation before the next stage in the for loop (iterator++)
    • The ; separates these stages in the for loop.
    • Your range temporary value iterator must be a number
  • When you have variable++ you are saying add 1 to that existing iterator. 1 becomes 2
  • We created a new variable named newhtml and set it to the empty string ''

    • In our for loop, we’re using the += operator which adds the new value on the right of the operator to the existing value on the left of the operator.
    • In this case, we’re adding a number like 1 to an empty string variable ''.
    • Javascript will infer the number as a string. When you add two strings together you concatenate them. Just like our previous example: 'Mark' + ' ' + 'Malone' = 'Mark Malone'
    • A slice of our for loop looks like this: '123' + '4' = '1234'

Now when we browse our website, we can see the for loop made a string consisting of 12345678910 and put it in our HTML.

javascript code on html page image from function for loop


The concepts we just went over exist in many different languages out there. Each programming language has it’s quirks, but most of the time the differences are really just syntact in nature.

We’re starting to get some pretty strong tools to help us learn more.