Data and Functions

Data types and functions are essentials of programing. Functions allow us to separate out our logic and code to make our life simpler, that way we can narrow our focus and solve hard problems in baby steps. Data to the computer is simply a bunch of 0's and 1's, but we can use it to represent things such as: Numbers ,Text, Lists, etc. In this section we will take a look at Functions, Data Types, and Variables.


Data Types are simply different ways we represent our Data. While there are a lot of different data types, we will just talk about the basics. In JavaScript data types are dynamic. Which means that the same variable can be used as a different type. Here are some examples:

  • Numbers - ( Integers [5] and decimals [1.205] )
  • Strings - ( Text ["Hello World"] )
  • Arrays - ( A list of items [1,2,3,4,5] )
  • Booleans - ( True or False statements )
  • Objects - ( Something that has properties[adjectives] and methods[actions] )
  • null, NaN - (Something undefined, something that is not a number)

Variables are simply a way to store our data. In JavaScript they are represented by the keyword "var". Here is the syntax:

 var myVariable = Value; 

Here are some examples of variables being declared.

<script>  
   var x = 5; // x is a Number
   var y = "Hello World"; // y is a String
   var z = true; // z is a Boolean
   var i = [1,2,3,4,5]; // i is a Array of Numbers
   var j = ["Spencer","Calvin","Alex","Max","Jason"]; // j is a Array of Strings
   x = "Im a String" // x is now a String
</script>
We will take more about objects in the future on a sections all about objects.

Numbers along with Booleans are simple data types. Numbers can be either whole numbers(Integers) or real numbers(Doubles in JS). We perform Arithmetic operations on numbers with add( + ), subtract( - ), multiplication( * ), and division( / ):

var x = 10; // x is 10

Basic Arithmetic:

var x = 10/2; // => 5
x = x * 3; // x = x*3 => 15
x++; // This means x = x + 1, so => 16
x+=4; // This means x = x + 4 => 20, the same thing goes with x-=n -> x = x - n.

Numbers also have methods(actions):

  • number.toString() - Returns the number as a string.
  • number.valueOf() - Returns the primitive number of the variable.

You can also define all basic data-types as Objects, the format for creating an object is:

var obj = new Object(...);

For creating numbers as objects we do:

var num = new Number(10); // num is 10

Creating a variable as an object is not the same as creating a variable as a primitive number. JavaScript will temporarily change variables that are primitive into objects with you call a method with them. Because of this I recommend simply making variables as primitive numbers like: var x = 3; This way we avoid problems with strict equality(===) and Case/Switch statements, both of which we will discuss later.

Out of all the data types we talked about Arrays are definitely the most complex. An array is a list of items. In all programing languages an array's particular elements can be accessed by their index( Where the item is in the array ). The index starts at 0, and a item in an array can be access by the notation: Array[index]. For example.

//              0       1        2       3
var array = ["Apple","Banana","Peach","Orange"]
  • array[0] = "Apple"
  • array[1] = "Banana"
  • array[2] = "Peach"
  • array[3] = "Orange"

You can also alert an array and JavaScript will give you a nice representation of the array:
alert(array) --> "Apple,Banana,Peach,Orange"

You can find the number of elements in an array by saying: array.length, in our example the array with elements ["Apple","Banana","Peach","Orange"] has a length of 4. There are plenty of methods you can use with an array, which can always be looked up online, so you don't have to memorize these:

  • array.indexOf(element) - Returns the index of some element in an array.
  • array.slice([start_index], [end_index]-1) - Returns a sub-array (shallow copy) from an array.
  • array.pop() - Removes an element from the end of an array
  • array.push(element) - Adds an element to the end of an array
  • array.sort() - Sorts an array in ascending, alphabetical, or numerical order depending on the elements in the array.

Challenge:

What will be alerted?

var array = ["Apple","Banana","Peach","Orange","Cherry"];
array.sort();
array.pop();
array.push("Lemon");
var newArray = array.slice(1,5); 
alert(newArray);

You can place any datatype into an array, even another array. Known as a multi-dimensional arrays, for example an array within an array is a 2D array. Which can be treated like a table, grid, or matrix. For example:

var Array2D = [
      [1,2,3],
      [4,5,6],
      [7,8,9]
];

Since there is an array inside the array we need two brackets, one two go into the outer array then the next to go into each inner array, or it maybe easier to see it as a table with rows and columns.

  • Array within Array :2dArray[outerArray_index][innerArray_index]
  • A Table :2dArray[row][col]

Here is some examples of getting elements:

Array2D[1]    => [4,5,6]
Array2D[1][0] => 4
Array2D[1][1] => 5
Array2D[0][2] => 3

Strings in there basic form are actually an array of characters, although they are a bit more than advanced than that in high level languages (like JavaScript). So for example we could look at ['H','e','l','l','o'] being similar to "Hello". So it is no surprise that strings have many methods that arrays have:

  • var str = "Hello" --> str[0] is 'H' , str[1] is 'e' , ...
  • string.indexOf(element) - Returns the character at the index.
  • string.length --> "Hello".length is 5.
  • string.slice([start_index], [end_index]-1) - Returns a sub-array of strings (shallow copy) from a base string.

Strings also have a property known as concatenation, which means we merging two strings together. This is used by the + symbol:

var hello = "HELLO";
var world = " WORLD"; //notice the space.
var statement = hello+world; // statement is "HELLO WORLD"

Some other things that strings can do:

  • string.toLowerCase() - Returns a string that has all the characters in the given string to be lower-case.
  • string.toUpperCase() - Returns a string that has all the characters in the given string to be upper-case.
  • string.split(para) - Returns an array sub-strings being separated by the parameter.
  • string.replace(original, replacement) - Returns a string that Finds and replaces something in the original string.
  • string.match(str) - If it finds the item in the parameter it returns it, otherwise return null.
var myStr = "Hello World";
myStr = myStr.toLowerCase(); // => "hello world"
myStr = myStr.toUpperCase(); // => "HELLO WORLD"
myStr = myStr.replace("WORLD","INTERNET"); // => "HELLO INTERNET"
var anotherStr = myStr.split("E") // anotherStr => ["H","LLO INT","RN","T"]

Functions are blocks of code that can accept values (known as arguments or parameters). We can use functions to separate out our program and focus on one part at a time, in a much more organized fashion. In JavaScript the syntax of functions is:

function nameOfFunction(arg1*,arg2*,...){ /* JavaScript Code */ }

The brackets { and } are known as branches, which in this case means they are a separate piece of code away from our main code. We will talk alot more about branching (along with a better definition) in the next section. Just know that those squiggly brackets are where we put our code for a function.

Note that when we make a function it does not do anything until we use it, known as calling a function. Here is an example:

function sayHello(){
   alert("Hello World");
}
sayHello(); // <-- This calls the function

All variables that are made inside a function are gone once we leave that function. This is known as local variables (Which are variables stored in the Stack - You don't need to know what that means).So for example this code will not work:

function sayBye(){
   var imGone = "Bye!";
   alert(imGone); // <-- This is fine
}
sayBye();
alert(imGone); <-- We arn't in the function, we don't know what imGone is.

This will output alert("Bye!"), but then you will get an error message like: imGone is not defined.

Global variables are variables we define outside of functions, we can use these values outside and inside functions fine:

var imGone = "Bye!";
function sayBye(){
   alert(imGone); // This works!
}
sayBye();
alert(imGone); //<-- This works too!


The locality of variables and where they are defined is called the scope. For global variables the scope is the entire program, globals are defined everywhere. Although for local variables they are only defined within their scope or where they were made between the brackets { ...variable... } .

Parameters:

We can also can give variables for our functions to work with (known as passing a value to a function). The values are known as arguments or parameters, and they are separated by commas:

function addStuff(x,y){
   var sum = x + y;
   alert(sum); 
}
addStuff(5,10) // 5+10 = 15


Returning Values:

We can also give out values with our functions, by saying return item. If we look back we can see many functions we used above does this ( toString() , valueOf(), slice() ). For example:

function giveStuff(x,y){
   var sum = x + y;
   return sum; 
}
var theSum = giveStuff(5,10) ;
/* giveStuff(...) gives a value, 15 in thie case, it's like: var theSum = 15; */
alert(theSum);

We know that we can produce output with the alert(string) function. We can also get input from the user with the prompt(str_message, ~str_text). ~ means optional. The Prompt function returns the string you gave it.

var name = prompt("What is your name?","Enter name here");
alert("Hello "+name);

Since datatypes are dynamic in JavaScript and can change easily, it's hard to be sure which datatype some variable is. This is mostly always between Strings and Numbers. We will want to convert to either: [Number to String] or [String to Number]. And we have functions for that:

  • parseInt(string) - Converts in a whole number
  •   parseFloat(string) - Converts to a decimal number
  • datatype.toString() - Converts a datatype into a String

Here is an example of a problem that can happen, lets say we ask for a number for input and we add to it:

var num = prompt("Enter a number");
var sum = num + 12;
alert(num+" + 12 = "+sum);


At first glance this look like it would run fine, but when we test it something is wrong. If I say 4, it tells me that " 4 + 12 = 412 ". Remember that prompt returns a string, so it did a string concatenation: "4" + 12 = "412". In JavaScript: [Number + String = String] and the Number is treated as a string. If we cast (change datatype) the input into a Number we will get the right result:

var num = prompt("Enter a number");
num = parseInt(num);
var sum = num + 12;
alert(num+" + 12 = "+sum);

Lets skim over the important points in this section.

Data Types are ways we represent our data:

  • Numbers - ( Integers [5] and decimals [1.205] )
  • Strings - ( Text ["Hello World"] )
  • Arrays - ( A list of items [1,2,3,4,5] )
  • Booleans - ( True or False statements )
  • Objects - ( Something that has properties[adjectives] and methods[actions] )
  • null, NaN - (Something undefined, something that is not a number)

Functions are blocks of code that can accept values:

  • function myFunction(arg1*,arg2*,...){ ... }
  • We can make functions return values with return value;
  • Local Variables: Variables only defined in functions, and are gone when the function ends.
  • Global Variables: Variables defined for the entire program, we can use them in functions and outside functions.

Datatypes in JavaScript are dynamic and can change easily to convert to a data type we use:

  • parseInt(string) - Converts in a whole number
  •  parseFloat(string) - Converts to a decimal number
  • datatype.toString() - Converts a datatype into a String

To get user input we use: prompt(str_message, ~str_text), ~ means optional.

Spencer Wieczorek