Javascript Basics

Introduction

The goal in this short intro is to get you coding. Over the course of the next few months you will learn more.

Variables

Let's start with the most basic of basics. Variables are used to store values. In Javascript variables can be of multiple types. There are 8 basic primative types.

In javascript you declare a varaible with let or const. Let is how you declare a variable that you plan to change. Const is how you declare a constant variable that does not change. You should default to const until you have to use let.


    let result = 0; // This is a comment because it starts with "//". Result will change, so it is a `let`
    const firstNumber = 5;
    const secondNumber = 10;
    result = firstNumber + secondNumber;
    console.log(result); // Output: 15 to the console in your web inspector in the browser.
        

Equality and Assignments

You will often test for equality in javascript or assign values to variables. The = operator is an assignment operator. It means take the value on the right side and put it into the variable on the left. It does not test equality, it assigns!

== is a test for equality, but it provides unexpected results. It will do type conversions then compare for equality. For example if you compare the string "0" to the number 0, it will return true. If you compare the string "0" to the boolean false, it will return true! There are many edge cases and you should not use this.

=== is a test for equality. It will not do type conversions. It will compare the value and the type. If the types are different, it will return false. You can also do > or < as you would expect.


    "0" = 0 // Error, you can't assign a value to "0".
    "0" == 0 // returns True
    "0" == false // returns True
    "0" == true // returns False
    "0" === 0 // returns False!

    const age = 25;
    age === 21 // False
    age >= 21 // True
                
            

Control Structures

There are other control structures we will learn about in person. I will just give a few examples below. Here is the structure of an if statement. You don't have to include the else or else if. Here is some reading on control structures.


    const age = 25;
    if (age >= 21) then {       // First case
        console.log("They can drink.")
    } else if (age <= 12) {     // You can add another condition if the first one is false
        console.log("They can have orange juice.")
    } else {                    // Covers all other cases
        console.log("Watch out for them in this age group")
    }
            

Here is a for loop and additional reading on loops.


    let age = 20;
    for (let i = 0; i < 10; i++) { // Start at 0, go to 9 incrementing by 1.
        age = age + 1
        console.log('They are ' + age + ' years old');
    }
            

The above code will print "They are 10 years old" "They are 11 years old" ... "They are 19 years old".

Functions

Sometimes you want to write code that doesn't execute right away. Or maybe you want to write a block of code you can run multiple times. This is what functions are for. Let's create a function that adds two numbers together.


      function add(a, b) {
        return a + b;
      }

      const numberResult = add(5, 2); // Returns 7
      const stringResult = add("cat", "dog"); // Returns "catdog"
      

In the above code there are two "arguments" to the function `a` and `b`. Are those numbers? Strings? Objects? No idea! Javascript doesn't specify types. You just have to know or test for all types in your code. This is one reason we will go to typescript later. In this case, it can be anything. We can use this function wherever we want. We can even pass it to a button. Read the functions link above to see all the ways functions can be used and specified. Pay special attention to Arrow Functions.

Connecting Javascript to your HTML

You should have Visual Studio Code setup now. Use VSCode to write this javascript. Create javascript-basics.js and put it in the same folder as your .html and .css files. Your .js should be empty now. You will also get practice with the web inspector as we do this. Let's get values from the user. For this we will use an input.

+ = 0

To see how this works, open up the web inspector and look at javascript-basics.js and the HTML. It uses the element IDs to get the values, then puts the result into the right output. When you read in the value from HTML it is always text or a "string" type. In the HTML we said type="number", but all that does is tell the browser not to let the user type non-numbers. We must convert the string to a number type. That is what parseint does. See if you can get it to work on your website.

To link the javascript to the HTML you need a script tag that looks like

<script src="./javascript-basics.js"></script>

The javascript references specific elements - the two `input` elements - to get their values. Then it references the add button and the output. If you put this script tag BEFORE your elements that the javascript references, it will error. This is because the HTML for the button or the inputs hasn't loaded yet. In javascript you say "get me the value of the input" and it responds "what input? It hasn't been made yet." This is why the script is at the end of the website. There are other ways round this, for later.

In the javascript code on this website, there are two ways to calculate the result implemented. One way is just to change the first value. The second way is to press the add button. Of course this makes no sense, you would normally just either make it when either value changes or use the add button. It's written this way to demonstrate different ways to interact with elements.

I know this is a lot. It's time to start your own project. We will need to sit down, set up your environment, then get you started.

Congrats! You have made a website that uses HTML, CSS, and Javascript from scratch. Most new developers skip this step and miss out on the foundational knowledge of how it works. Now we will make it easier and use a framework. This get element by ID stuff is annoying. We won't be doing that anymore...more to follow.

It's time to sit down, answer questions, and set-up your computer. The goal of this learning group is not to learn from a website. There are much better ones out there. The goal is to learn in person (or via text). Let me know when you are ready!