Introduction to variables, arrays, JavaScript Object Notation.

Tue, Sep 17, 2019

Introduction

JavaScript is a coding language used in webpages. It enables you to do things like add interactivity to a website, build applications, and retrieve data from other sites.

This tutorial is used as a reference guide to a class taught at the UC Berkeley Graduate School of Journalism on coding for journalists. It is recommended that this tutorial be used as a complement to a course on JavaScript and/or coding fundamentals. Parts of a webpage:

Webpages are made up of three elements:

  1. HTML — The structure and content of the webpage.
  2. CSS — The style and design of the webpage.
  3. JavaScript — Code that enables things like interactivity or manipulation of elements on a webpage.

All three parts of a webpage are written in a unique syntax, and are considered different languages.

Where does JavaScript reside?

JavaScript is stored right inside the HTML of a webpage. The code itself is put in one of two places:

Linking to a JavaScript file

JavaScript can be stored in a separate text file that is referenced in your HTML. Generally, this separate text document has the file extension .js

JavaScript is included on a webpage using the <script> tag. To link to a javascript file, use the following syntax:

<script type="text/javascript" src="path_to_file/filename.js"></script>

It is important to note that when linking to JavaScript files, you need both an opening and closing <script> tag.

Inline JavaScript

JavaScript can also be written directly within the HTML of a webpage, also using the <script> tag. Put your code between the opening and closing script tags.

<script type="text/javascript">
    //JavaScript code here
</script>

The attribute type="text/javascript" is not required, but some believe it is good practice to use it. A plain <script> tag will also work, as all modern browsers automatically default to JavaScript language when the see a <script> tag with no attribute.

Variables

JavaScript is a lot like math in the sense that we store data in variables. Here is some info about variables, and how they work in JavaScript.

Variables in JavaScript must follow a certain set of naming rules.

  • Variables should start with a letter (underscore or dollar symbol are also acceptable, but typically reserved for certain situations)
  • Variables can only contain letters, numbers, an underscore, dollar symbol, or Unicode characters
  • Variables cannot have spaces
  • Variables in JavaScript are case sensitive, which means the variable mytotal is a different variable than myTotal.

Variable names can be a single letter, such as i, j or k. But it is better better to use more descriptive names such as total, sum or totalscore. You will come up with your own names for variables in your program which pertain to your own application.

Semicolon (;)

A semicolon terminates a line of code. Think of it similar to a period at the end of a sentence. Technically, semicolons are optional in JavaScript, but considered good practice.

The VAR keyword

When using variables in JavaScript, you should declare them using the VAR keyword. This establishes the word you picked to be used as a variable under a certain “scope,” or place. (more on what this means in the section on functions.)

var i;
var total;
var numberofphotos;

Only use the var keyword the first time you mention a variable in any scope (space).

The LET keyword

In addition to var, JavaScript also has a “let” keyword that does the same thing for our purposes. In more advanced uses, which we will cover later, the difference is that the var keyword will make this variable available “everywhere.” This means that once we declare it, we can find this variable works inside things called functions, which we’ll learn about later.

However, the let keyword is more limited, and less stingy. When declaring a variable with let, it’s only available in the scope where we decared it. If you try to access the variable in a function, it won’t find it.

For our purposes at this point, they operate the same way.

let i;
let total;

Assignment Operator

The expression:

var x = 7;

means that we are storing the value 7 inside the variable x. It does not establish equivalency — saying x is the same as 7 — rather, the equals sign is performing a task of storing the value on the right inside the variable on the left.

Assignment process in JavaScript

It is also possible to replace the value of variable with something else. Thus the expression:

var x = 7;
x = 8;
x = 9;

means that x will be 9 — the final value. Each time we assign a new value, it replaces the old value.

Assignting a Variable to Another Variable

When a variable is assigned to another variable, it receives its value, as in this example:

var x = 8;
var y = x;

The value of y is 8. Because in the first line, we assigned 8 to the x variable. Then in the second line, we assigned the value of x, to y.

Basic Math Operations

In JavaScript, you can perform some basic arithmetic operations.

var x = 5 + 7;

The value of x will be 12. Likewise, you can use other variables for a part of these math operations.

var x = 5;
var y = 2;
var j = x + y;

In this case the value of j will be 7. You can also perform multiplcation and division, and even use parethesis much the same way you do with algebraic expressions. Multiplication is done with an asterisk (*), and division with a forward slash (/).

var x = 9;
var y = (x / 4) * (x + 3);

The value of y is 27, or 9 divided by 4, multiplied by the sum of 9 and 3.

String Data Type

Variables can store more than numbers. They can also store words, phrases and several other types of abstract data. If you want to store a word or a phrase, you need to surround it by quotes. (both single or double quotes work.)

var myname = "Jeremy";
var website = "Knight Digital Media Center";

If you don’t use quotes, the browser will think you are trying assign values to another variable.

Concatenation

What happens with you try add two string variables? In JavaScript, it simply connects the two together in a process called concatenation.

firstname = "Jeremy";
lastname = "Rue";
fullname = firstname + lastname;

In the above example the value of fullname is JeremyRue. Notice there is no space. That is becauase JavaScript will concatenate variable exactly without the addition of spaces. Notice the following example:

sentence = "This tutorial is written by";
firstname = "Jeremy";
lastname = "Rue";
fullsentence = sentence + " " + firstname + " " + lastname;

In this example, the fullsentence variable will contain the string This tutorial is writtten by Jeremy Rue, with spaces between all words.

Concatenating strings with numbers

It is also possible to concatenate strings and number. The result will always be a string.

firstnumber = "4";
secondnumber = 5;
fullnumber = firstnumber + secondnumber;

In this example, the value of fullnumber would be the string “45.” It’s important to understand when variables are numbers, and when they are strings of text that simply contain numbers. Taking the example above, if we didn’t have quotes around the 4, it would not concatenate the two values, but rather combine them.

firstnumber = 4;
secondnumber = 5;
fullnumber = firstnumber + secondnumber;

In this example, the value of fullnumber is 9. Because the type of data in both of these variables are numbers, they are not concatenated, but rather combined as numbers.

Boolean Data Type

Variables in JavaScript can store much more than numbers and text strings. They can also store a wide array of abstract data types. One of these is the Boolean data type, which only has two values: true and false. Why we would want to store a true or false value in a variable doesn’t make a lot of sense right now. But later, in the section on conditionals, it becomes a vital tool.

var showtooltip = false;

Assigning a Variable to Itself

Sometimes you want to change the value of a variable, based on its current value. This often done by assigning a variable to itself, and applying the changes.

var x = 27;
x = x + 3;

In the above example, the value of x is now 30. When you assign a variable to itself, the value doesn’t change until the operation is complete. It is also possible to do this with strings, which concatenates the variable:

var fullname = "Jeremy";
fullname = fullname + " " + "Rue";

In the above example, the value of full name is Jeremy Rue. We first assign it the value Jeremy, then we assign the original value with the last name concatenated.

Arrays

An array is a method of storing multiple values in a single variable.

var myarray = ["bob", "john", "peter", "sandy"];

Each value in an array is separated by a comma. The values can also have a unique data types. For example, some values can be numbers, while other values can be strings or booleans.

var myarray = ["joe", 47, false, true];

In order to retrieve any element in the array, we use something called the index number. It is important to note that the index of every array starts on zero.

var myarray = ["bob", "john", "peter", "sandy"];
console.log( myarray[2] );

In the above example, myarray[2] would retrieve the value “peter” because it is the third element in the array. (remember, we start on zero.) We can also cite the index in a number of ways. What are the values of the following variables?

var myarray = [
    "bob", 
    "john", 
    "peter", 
    "sandy"
];
var x = 1;

myarray[1 + 2]
myarray[x]

In the first example, myarray[1+2] would retrieve the “sandy” value, because it is the fourth element. In the second example, the myarray[x] would retrieve the “john” value, because it is the second element. This idea of being able to bring up a value becomes very useful later, especially when working with large datasets.

It’s also important to note how the array was typed out on multiple lines. JavaScript doesn’t care how the information is presented, as long as the opening and closing brackets match up correctly. Changing Values Within an Array

You can change individual values within an array by referencing them by their index number. Consider the following:

var myarray = [
    "bob",
    "john",
    "peter",
    "sandy"
];

myarray[1] = "mary";

The john value no longer exists in myarray, because we’ve replaced it with mary. Remember, john was located at index 1, which is the second value because indices start on zero.

Multidimensional Arrays

A multidimensional array sounds more complicated than it is. The idea is simple: An array within an array. Sometimes the key to grasping a multidimensional array lies in how it’s typed out.

var my2Darray = [
    ["bob", "alex", "joe", "wendy"],
    ["teresa", "jodi", "sara", "peter"],
    ["jack", 44, 90],
    [true, false]
];

The above array has four elements, each one is also an array. So how do we reference each item? We use indexes for both the main array, and each child array nested. For the above array:

my2Darray[0][1] //This would return "alex"
my2Darray[2][2] //This would return 90
my2Darray[3][0] //This would return true
my2Darray[2][3] //This is undefined, since there is no fourth element

We used the name 2D array because this is a two-dimensional array. It is possible to further have more arrays nested within these arrays, and so on. It begins to get very complex however. Generally, most arrays don’t go too far beyond three dimensions. More ways to write arrays

Arrays can be typed and declared in a number of ways. If you want to declare a variable as an array without assigning any values to it, you have to use a special statement called a constructor. Here are two ways to do this:

var myarray = new Array();
var myarray = [];

These are both functionally the same thing. Once you’ve declared your array, it is possible to change out or assign specific values at various indices.

var myarray = [];
myarray[3] = "john";
myarray[2] = 56;
myarray[102] = "Peter";

If there was already a value in those spots, it would be replaced.

When you reference an array item, it works just like any other variable. You can concatenate them, or use them in arithmetic functions, like so:

var myarray = [1, 2, 3, 4, 5, 6, 7];
var sum = myarray[2] + myarray[4];

The value of sum would be 8, since we are adding the values 3 and 5. Remember, indices start on zero.

Test yourself:

var myarray = ["Java", "learned", "I", "today", "Script"];
var indices = [3, 2, 1, 0, 4];

//What is the value of the variable message?

var message = myarray[indices[0]] + " " + 
     myarray[indices[1]] + " " + 
     myarray[indices[2]] + " " + 
     myarray[indices[3]] + myarray[indices[4]];

In the above example, we actually use an array to represent the index value of each array.

Objects

Objects are variables that can store associative data and functions. Objects have a much larger role in JavaScript than just storing data, as we’ll find out later. But at this point in the tutorial we’ll learn about how to create a basic generic object— in our case mostly used for storing associative data.

There are three basic formats for writing objects:

  • Object literal
  • Dot notation
  • Square bracket notation

Object Literals

An object literal is a method of writing an object. You cannot recall values from an object using a literal, only assign values.

An object literal is written with curly braces. Each item in the object contains an keyword called a property and it is separated by a colon with the value of that property.

var person = {name: "Jim", age: 47, location: "Berkeley"};

In the above example, we’ve created a variable called person, and we’ve associated three properties with this person; a name, age and location. Each property is assigned a value, with an according datatype.

Using Dot Notation To Create Objects

It is possible to create a generic object without assigning it a value. This is called instantiating, a process that will become more important later when we cover classes.

var dog = new Object();

Once we’ve instantiated an object, we can assign properties to it.

dog.name = "Rex";
dog.type = "hound";
dog.age = 3;
dog.hasFleas = false;

It is important to note that this is another way of creating and assigning values to an object. We could achieve the same exact result with an object literal like so:

var dog = {name: "Rex", type: "hound", age: 3, hasFleas:false };

Using Square Bracket Notation to Create Objects

Square bracket notation is very similar to dot notation, and it offers a few advantages. The primary advantage is that property names can have spaces, since they are strings. This also allows us to calculate property names dynamically.

Like dot notation, we must first instantiate an object:

var cat = new Object();

Next, we assign properties to it.

cat["name"] = "Penny";
cat["type"] = "Tabby";
cat["age"] = 3;
cat["likes to sleep"] = true;

Take note of the last line of the above code. The property “likes to sleep” has spaces, so typing this as dot notation would not be possible.

Just as with dot notation, we can create this object using object literals. Below is the identical method of creating the cat variable using object literals:

var cat = {name : "Penny", type : "Tabby", age : 3, "likes to sleep": true };

Surrounding property names in quotes is usually optional in object literals, but it is required when property names have spaces.

Arrays and Objects

Arrays and objects work well together. They are very similar, but have some important differences. Objects use properties to identify values, while Arrays use an index number, to store multiple values.

In this following example, we have an array of office workers. Each item in the array is a different object that we can reference.

var officeWorkers = [ 
    {name: "Suzy",   position: "secretary", "years of employment": 5},
    {name: "Jim",    position: "manager",   "years of employment": 2},
    {name: "Robert", position: "janitor",   "years of employment": 10},
    {name: "Mary",   position: "CEO",       "years of employment": 1}
];

In the above array, if we wanted to reference any of the objects, we would first use the index of that object, then use the respective property name. For example, if we wanted to get Mary’s position we would reference that by one of two ways:

officeWorkers[3].position;
officeWorkers[3]["position"];

Either dot notation or square bracket notation can be used to recall information. Remember, object literals are only for assigning data, so we cannot use them to retrieve values from an object. Advantages of using square bracket notation

Square bracket notation has benefits because we can dynamically create the property name. There are situations where we may wish to reference a property of an object in response to a particular action by the user, or for retrieving data from a very large dataset. Consider the following example:

var photos = {
    photo1: "fish.jpg",
    photo2: "cat.jpg",
    photo3: "dog.jpg",
    photo4: "horse.jpg",
    photo5: "turtle.jpg",
};

While we can retrieve any of these items using the properties (photo1, photo2, photo3, etc.) sometimes we may need to specify the property name based on another value.

var currentPhoto = 1;
photos["photo" + currentPhoto];

In the above situation, the information in the square bracket will resolve to photo1, and thus retrieving the information for “cat.jpg” in the photos variable. The reason this happens, is because we’ve concatenated the string “photo” with the value 1 in the variable currentPhoto, which was set earlier. Objects inside of objects

Objects can be nested inside of other objects, and this is quite common practice. However, making the code legible is crucial to understanding the structure of the object. We generally use a mix of indentation and carriage returns (new lines) to make the code human-readable.

var blogData = {
    title : "Headline for my blog post",
    author : "Jeremy Rue",
    meta : {
        date : "Jan 1, 2012",
        time : "12:00am",
        keywords : "blog post berkeley"
    },
};

In this above example, you can see that the value of the meta property is another object. Using both dot notation or square bracket notation, we could recall these values—such as the keywords property—like so:

blogData.meta.keywords; 
blogData["meta"]["keywords"];

JavaScript Object Notation, or JSON

There is a standard on the web for transferring information between websites called JavaScript Object Notation, or JSON (pronounced “jase-on.”) JSON is simply a combination of JavaScript object notation and arrays. JSON is used by many other programming languages than JavaScript, and has cemented itself as a standard format for data. This is why understanding objects, arrays and datatypes is so crucial for understanding how JavaScript works.

Here is an example of some JSON formatted data:

{
    "firstName": "Ross",
    "lastName": "Marshall",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021"
    },
    "phoneNumber": [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567"
        }
    ]
}

It’s important to know that JSON is just referring to the data part. When you have a .json file, it shouldn’t be assigned to a variable.

JSONP

Sometimes JSON will be transferred in a way where it’s automatically encased in a function call, known as JSONP. This is often done to get around browser security limitations called CORS (Cross-Origin Requests).

Such an scenario might look like this:

callback({
    "firstName": "Ross",
    "lastName": "Marshall",
    "age": 25
})

In the case above, this file isn’t actually JSON. It’s a JavaScript that is wrapping the JSON code in something called a function that we will learn about in the next lesson. In order to receive or transfer the above code from a website with a different domain, we would need to also create the function to receive that JSON.

var myJSON;

function callback(data){
    myJSON = data;
}

This is a bit advanced and won’t make a lot of sense until we cover functions in the next class. It’s important to introduce the topic, however.