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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.