Learn Programming / JavaScript Basics

The “script” tag

JavaScript programs can be inserted into any part of an HTML document with the help of the <script> tag.

For instance:

<!DOCTYPE HTML>
<html>

<body>

  <p>Before the script...</p>

  <script>
    alert( 'Hello, world!' );
  </script>

  <p>...After the script.</p>

</body>

</html>
alert("Thanks for your input!");

Let’s say my name is Mark, and I want to store this information in the browser.

A variable is created when you write var (for variable) followed by the name that you choose to give it. It takes on a particular value when you assign the value to it. This is a JavaScript statement that creates the variable name and assigns the value “Mark” to it

var name = "Mark";

Now the variable name refers to the text string “Mark”. Note that it was my choice to call it name. I could have called it myName, xyz, lol, or something else. It’s up to me how to name my variables, within limits.

name refers to “Mark”. Then I come along and code the line…

name = "Ace";

Before I coded the new line, if I asked JavaScript to print name, it printed… Mark But that was then. Now if I ask JavaScript to print name, it prints… Ace

Alerting the name variable!

alert(name);

What do the quotes mean, and what happens if I omit the quotes? The syntactic difference between variables and text strings is that variables are never enclosed in quotes, and text strings are always enclosed in quotes.

A string isn’t the only thing you can assign to a variable. You can also assign a number.

var weight = 150;

Having coded the statement above, whenever you write weight in your code, JavaScript knows you mean 150. You can use this variable in math calculations. If you ask JavaScript to add 25 to weight…

var newWeight = weight + 25;
alert(newWeight); // will say 175

JavaScript can also handle an expression made up of nothing but variables. For example

var originalNum = 23;
var numToBeAdded = 7; 
var newNum = originalNum + numToBeAdded; // newNum equals 30

Working with strings

suppose you wanted to personalize a message. In another part of your code you’ve asked the user for her name and assigned the name that she entered to a variable, userName. (You don’t know how to do this yet. You’ll learn how in a subsequent chapter.) Now, you want to combine her name with a standard “Thanks” to produce an alert that says, for example, “Thanks, Susan!” When the user-provided her name, we assigned it to the variable userName. This is the code.

alert("Thanks, " + userName + "!");

Using the plus operator, the code combines—concatenates—three elements into the message: the string “Thanks, ” plus the string represented by the variable userName plus the string “!” Note that the first string includes a space. Without it, the alert would read, “Thanks,Susan!”. You can concatenate any combination of strings and variables, or all strings or all variables. For example, I can rewrite the last example this way

var message = "Thanks, ";
var banger = "!";
alert(message + userName + banger);

Trick question:

What will be alerted here

alert("2"+"2");

Now you try it:

TIP: Use this link http://x.co/jslinks to automatically open all the following items in new tabs

Prompts

var spec = prompt("Ask some question?", "default value?");

Prompt code is like alert code, with two differences.

  • In a prompt, you need a way to capture the user’s response. That means you need to start
    by declaring a variable, followed by an equal sign.
  • In a prompt, you can specify a second string. This is the default response that appears in
    the field when the prompt displays. If the user leaves the default response as-is and just
    clicks OK, the default response is assigned to the variable. It’s up to you whether you
    include a default response.

As you might expect, you can assign the strings to variables, then specify the variables
instead of strings inside the parentheses.

var question = "Your species?";
var defaultAnswer = "human";
var spec = prompt(question, defaultAnswer);

The user’s response is a text string. Even if the response is a number, it comes back as a
string. For example, consider this code.

var numberOfCats = prompt("How many cats?"); //enter 5
var tooManyCats = numberOfCats + 1; // will get 51

To fix this problem we can use a JS helper function called parseInt, which takes a string and tries to figure out what the number would be inside the string

var numberOfCats = prompt("How many cats?"); //enter 5
var tooManyCats = parseInt(numberOfCats) + 1; // will get 6

If Statements

Suppose you code a prompt that asks, “Where does the Pope live?” If the user answers correctly, you display an alert congratulating him. This is the code.

var x = prompt("Where does the Pope live?");
if (x === "Vatican") {
  alert("Correct!");
}

If the user enters “Vatican” in the prompt field, the congratulations alert displays. If he enters something else, nothing happens. (This simplified code doesn’t allow for other correct answers, like “The Vatican.” I don’t want to get into that now.)

So let’s make a trivia game!

var score = 0;

var x = prompt("Where does the Pope live?");
if (x === "Vatican") {
    alert("Correct!");
    score = score + 1;
} 

var z = prompt("Where does Angel live?");
if (z === "Santa Barbara") {
    alert("Correct!");
    score = score + 1;
}

alert("You got a score of: " + score + " out of 2");

What if we want something that DOES NOT equal the other value?

var x = prompt("Where does the Pope live?");

if (x === "Vatican") {
    alert("Correct!");
    score = score + 1;
} 
if (x !== "Vatican") { 
    alert("Sorry incorrect!"); 
} 

So if it !== doesn’t equal we do something else. But typically it’s easier to say “IF this then do that ELSE do the other thing” which looks like this

var x = prompt("Where does the Pope live?");

if (x === "Vatican") {
    alert("Correct!");
    score = score + 1;
} else {
    alert("Sorry incorrect!"); 
} 

That’s much better.

Functions

Sometimes we want to be able to run the same code one or many times, to do this we can store a set of code inside a function and call it at a later time. This also keeps our code organized!

// Create a function
function nameMe() {
    alert("My Name is Angel");
}

// Call the function to run the code inside it
nameMe();

Functions become really useful when you also pass data inside of them with a parameter like so:

// Create a function
function nameMe(name) {
    alert("My Name is " + name);
}

// Call the function to run the code inside it
nameMe("Angel");

You can even pass the value we got from a prompt!

// Create a function
function nameMe(name) {
    alert("My Name is " + name);
}

var setMyName = prompt("What is your name?");
nameMe(setMyName);

Handling a click

The easiest way to handle a click is the use an html attribute called onclick

See the Pen bzGOXa by Angel Grablev (@agrublev) on CodePen.32466

So we create a div, then simply add the onclick attribute with a value that will call our function when clicked like this:

<div onclick="quiz()">CLICK</div>

<script>
function quiz() {
    var score = 0;

    var x = prompt("Where does the Pope live?");
    if (x === "Vatican") {
        alert("Correct!");
        score = score + 1;
    }

    var z = prompt("Where does Angel live?");
    if (z === "Santa Barbara") {
        alert("Correct!");
        score = score + 1;
    }

    alert("You got a score of: " + score + " out of 2");
}
</script>

And if you have time for fun do this tutorial:

https://www.codeavengers.com/web-development/100#1.1

It provides video guides AND a solution button up to the top right!

Additional exercises/Reading materials

Once you feel comfortable with all that give this article a look:

And watch this video:

TO BE ADDED LATER (IGNORE):

https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics

The Ultimate JavaScript Introduction

Variables

Variables are containers that you can store values in. You start by declaring a variable with the var keyword, followed by any name you want to call it:

var myVariable;

A semicolon at the end of a line indicates where a statement ends;

String

We indicate a string by surrounding the string value with quotes, like this:

var variableName = "string content in here";

Now you try it!

See the Pen JS-Intro by Angel Grablev (@agrublev) on CodePen.0

  • Number – 1, 5200, 95.34
  • Boolean – true/false
  • Array – store a list
    • var myArray = [1,2,3,4,5];
    • Accessing a list
    • var myArr = [1,2,3,4];
      myArr[0]; // returns 1 because arrays start from 0
    • Looping lists
    • var myArr = [1,2,3,4];
      // Using jQuery! As it's much simpler/prettier
      $.each(myArr, function( index, value ) {
        console.log( index + ": " + value );
      });
      // will return
      // 0: 1
      // 1: 2
      // 2: 3
      // 3: 4
    • Push unshift splice
    • var myVar = [1,2,3,4];
      // add to end of array
      myVar.push(5);
      console.log(myVar);
      // [1,2,3,4,5]
      
      // add to beginning of array
      myVar.unshift(0);
      console.log(myVar);
      // [0,1,2,3,4,5]
      
      // remove 1 item at index 0
      myVar.splice(0,1);
      console.log(myVar);
      // [1,2,3,4,5]
  • Object – store name: value properties
    • Accessing objects [] vs .
    • Looping object (no order!!)
    • Adding/removing properties
    • // empty object
      var myVar = {};
      console.log(myVar);
      // {}
      
      // predefined object
      var myVar2 = {
          // property
          "name":"value"
      }
      console.log(myVar2);
      // {"name":"value"}
      
      // predefined object
      var myVar3 = {
          "firstName":"Angel"
      }
      // safer way to get the value of a property
      console.log(myVar3["firstName"]); // Angel
      console.log(myVar3.firstName); // Angel
      // adding a new property to an existing object
      myVar3.lastName = "Grablev";
      console.log(myVar3.lastName); // Grablev
      
      console.log(myVar3); // {"firstName":"Angel","lastName":"Grablev"}
      // removing a property
      delete myVar3.lastName;
      console.log(myVar3); // {"firstName":"Angel"}
      
      
      // looping is similar to array, but instead of the index we get the name
      // this loops follows NO ORDER!
      $.each(myVar3, function( propertyName, propertyValue ) {
        console.log( propertyName + ": " + propertyValue );
      });
      // firstName: Angel
      // lastName: Grablev

Functions

Are a way to set blocks of executable code that can be called later as many times as needed. You can set a name for the function and set parameters to be passed into it.

function add(x, y) {
  // can return a value, but it's not required
  return x + y;
}
console.log(add(1,1)); // 2

var aNumber = 0;
function addToNumber(x) {
  aNumber = aNumber + x;
}
addToNumber(5);
console.log(aNumber); // 5
addToNumber(5);
console.log(aNumber); // 10

See the Pen JS-Intro by Angel Grablev (@agrublev) on CodePen.0

To execute a function we simply use its name and pass any needed parameters inside the parenthesis. If no parameters then simply adding parenthesis executes the function.

function loveIt() {
    console.log("Love it");
}

loveIt(); // Love it

Anonymous functions

An anonymous function has no name and is always executed right away. Most commonly we pass an anonymous function to libraries like jQuery so it knows what code to execute for us.

// Passing anonymous function to jQuery to do something
// on click
$("#click").on("click",function(){
    $("#click").addClass("clicked");
});

// Can be done just as easily with a named function like this
function whenClicked() {
    $("#click2").addClass("clicked");
}
// jQuery will simply execute the function
$("#click2").on("click",whenClicked);

Storing function in a variable

We can store a function in a variable, which does almost the same thing as a normal function declaration.

function add(x,y) {
    return x+y;
}
// is identical to
var add = function(x,y) {
    return x+y;
}
// we're simply storing an anonymous function
// inside our add variable

Comparisons and if statements

// 3 = signs means absolute comparison
console.log("1" === 1); // false - string is not number

// 2 = signs means relative comparison
console.log("1" == 1); // true - they are relatively the same

// < less than | <= less than or equal to | > and >= same but opposite
console.log(0 < 1); // true
console.log(1 <= 1); // true

// && says "and" meaning both must be true 
// || says "or" means either must be true
console.log(0 < 1 && 1 < 1); // false
console.log(0 < 1 || 1 < 1); // true

If statements

var name = "angel";
if ( name === "angel" ) {
    // yep
} else {
    // nope
}

Variable scopes!

Every variable we define exists in a scope. We can only call variables from parent scopes.

// window scope - think of it as browser wide
var parent = "Im at top";

function child() {
    var child1 = "I'm inside child!";
    console.log(parent); // Im at top
}
console.log(child1); // undefined - IT DOES NOT exist in this scope

// Also you can't use variable/function before it's defined
test(); // error
function test() {
    console.log("Will NOT be executed!");
};

Brain teasers

var a = 1;
var b = 2;

(function() {
  var b = 3;
  a += b;
})();

a; // What's a?
b; // What's b?
function parentFunc() {
    var a = 1;
    function nestedFunc() {
        var b = 4; // parentFunc can't use this

        return a + b;
    }
    return nestedFunc(); // what's returned?
}
function createAdder(x){
    return function(b) {
        return x+b;
    }
}
var adder1 = createAdder(5);
console.log(adder1(1)); // what's the result?

 

Useful snippets

Adding jQuery to your website

  <!-- add jquery right before the ending body tag -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <!-- make sure to add your JS after jQuery otherwise you can't use it -->
  <script src="js/main.js"></script>
</body>

Using jQuery

// This is jQueries way of waiting for page to load
// we simply pass an anonymous function to the jQuery function
$(function(){
    
});

// Basically equiavelnt of this
var $ = function(runThisCodeWhenPageLoaded) {
    // some magic happens and then it calls your annonymous function
    runThisCodeWhenPageLoaded();
};
// Then you'd call it as usual
$(function(){
    console.log("TEST!"); // TEST!
});

Common jQuery usecases

// Handle a click on element with class .some-element
$(".some-element").on("click",function(){
    // do something
});

// Handle a click on an anchor with href="#"
// without moving to top of page
$(".button a").on("click",function(browserEvent){
    // take the browser event and prevent the default reaction
    browserEvent.preventDefault();
    // do something
});

// Handle a click on element with class .some-element
// and since you can have 100 elements with that class
// we can reference the exact one we clicked with $(this)
$(".some-element").on("click",function(){
    $(this).hide(); // will ONLY hide the clicked element
});

// Common interactions with elements

// <div class="some-element"
// becomes <div class="some-element test"
$(".some-element").addClass("test");

// hide/show the element
$(".some-element").hide();
$(".some-element").show();
// if an element has display:none; css applied
// or it was hidden with jQuery you can show it
$(".some-element").fadeIn(3000); // fades it in in 3seconds
$(".some-element").fadeOut(5000); // fades it out in 5seconds

// find a child
$(".some-element").find(".test"); // finds a child of .some-element with class .test
$(".some-element").find(".test").hide(); // hides the child .test

// find a parent of the element
// <div class="test">
//		<div class="doesnmatter">
//			<a href="#" class=".some-element">ME!</a>
$(".some-element").parents(".test"); // finds the first parent of .some-element with class .test
$(".some-element").parents(".test").hide(); // hides the child .test

// Adds an element inside and at the end of the chosen element
$(".inside-me").append("<div class='test'>Awesome</div>");
/*
<div class="inside-me">
    <div class="random">
        Random element
    </div>
    <!-- WE ADD THE DIV CLASS TEST HERE -->
</div>
*/

// Adds an element after the chosen element
$(".inside-me").after("<div class='test'>Awesome</div>");
/*
<div class="inside-me">
    <div class="random">
        Random element
    </div>
</div>
<!-- WE ADD THE DIV CLASS TEST HERE -->
*/

 

Setting up Firebase

Go to https://firebase.google.com/ and click SIGN IN

Then go to https://console.firebase.google.com/u/0/ and click Add Project

Enter a name and Create Project

Navigate to DEVELOP -> Authentication then click Set Up Sign In Method

Enable the ones you want to use

Remember that later you will need to add the domain of your website so it works!

Now select DEVELOP->Database

Then Firestore Get Started

Set it in Test Mode and Enable

Finally, let’s enable storage

Now go to rules tab

Change to

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write
    }
  }
}

Then publish.

 

Get authnetication information

Click the COG on top right and select project settings

Now select

This will give you the code you need to add inside your project!

 

Download the example zip and then follow these steps:

  1. Extract zip
  2. Open the file js/initializeFirebase.js
  3. Replace its contents with the settings from above
  4. Open terminal and type “npm install”
  5. Every time you want to run the system type “gulp”
  6. Here are the links you can go to for the different examples
    1. will have a full login/signup and list items example
    2. /items.html will have a full example for working with items (add/edit/delete)
    3. /upload.html has an example of uploading files
    4. /auth.html has an example for sign up and login

https://angelprivate.s3.amazonaws.com/teaching/additionalFun.zip