Objects, Functions and Conditionals
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.
Functions
A function is another data type, just like numbers, strings, booleans, arrays and objects. You can assign functions to variables, just like the other data types.
//example of an empty function assigned to a variable. This does nothing,
//it's just an example.
var someVariable = function(){ };
But what exactly is a function? It’s a block of code that is stored into memory to await execution at a time when the function is run. When we place code in a function, it is read by the program, but the code is not executed immediately. Rather, it waits until we tell it to.
//A function that when called, will return a string with "Hello there"
var sayGreeting = function(){ return "Hello there"; }
This might seem confusing at first, especially when compared to other static data types like strings. It’s important to note that when we assign a function to a variable, we basically just make a special variable that has the ability to call the code in the curly braces. You call the function by using the parentheses characters.
var sayGreeting = function(){ return "Hello there"; }
//now run the function. This will output the string.
console.log(sayGreeting());
When the function is run, it returns some information — typically as a different data type. (This is the part that can be confusing). But this only happens when the function is run. For example:
var sayGreeting = function(){ return "Hello there"; }
var anotherVariable = sayGreeting();
//value of anotherVariable is the string "Hello there",
//because that is what was returned.
Arguments
The parentheses have a special purpose, which is to include a variable called an argument. function(argument)
. This argument is passed into the function, and can be used as part of the return. Let’ take the following example:
var calculateTip = function(bill){ return bill * 0.20; }
calculateTip(10); //this will return 10 * 20%, or 2 dollars
We can see we have the argument bill
which we can use in the function. This argument acts like a temporary variable whose value is determined when the function is run. This allows us to reuse the function numerous times to make multiple calculations.
var calculateTip = function(bill){
return bill * 0.20;
}
calculateTip(10); //this will return 10 * 20%, or 2 dollars
calculateTip(100); //this will return 20
calculateTip(1000); //this will return 200
Multiple Arguments
You can also specify multiple arguments, which can be passed into the function. We do this by separating them with commas.
var calculateTip = function(bill, tip){
return bill * tip;
}
calculateTip(10, 0.15); //calculate a $10 bill with 15% tip
calculateTip(100, 0.10); //calculate a $100 bill with 10% tip
calculateTip(1000, 0); //calculate a $1000 bill with 0% tip
It’s important to note that in the example above, the calculateTip()
isn’t displaying the output anywhere. Normally we would do something with the returned result, like assign it to another variable, or output it onto the page.
Here is an example of writing a greeting onto the page:
var greeting = function(name, location){
return "Hello " + name + " from " + location;
}
document.write( greeting("Jeremy", "Berkeley") );
//output to the page:
//Hello Jeremy from Berkeley
Above we’re using document.write()
, which is a built-in function in the browser that allows us to output some text to the page. (Note: this is an archaic method of writing text to the page, typically we would use a JS library like jQuery or d3).
var makeBold = function(str){
return "<strong>" + str + "</strong>";
}
document.write("Some " + makeBold("text") + " where parts are " + makeBold("bold"));
//output:
//Some text where parts are bold
In the above example, we’ve designed a function that takes a string, and adds some <strong>
tags around them, then returns the new text. We can reuse the function over and over by sending new data, each time it would convert it to bold.
Another way to write functions
On a rare occasion, you might see functions written in a different way where they are not assigned to a variable. These are called function declarations. They differ slightly in a fairly technical way. When a function is declared (not assigned to a variable) then it is read into memory before all other code. This means you can technically call a function before you even declare it! This isn’t possible with variables, where everything needs to be in order.
var functionOne = function() {
// Some code
};
function functionTwo() {
// Some code
}
//they both do the same thing
functionOne();
functionTwo();
In the above example, both methods are identical. We can specify function someName()
to declare it, or we can assign an anonymous function to a variable var someVar = function()
.
Here is where they differ:
functionOne(); //gives an error, because it doesn't exist yet!
functionTwo(); //This is fine, because declared functions are read first
var functionOne = function() {
// Some code
};
function functionTwo() {
// Some code
}
If you’re curious about more ways to write functions, check out this StackOverflow article or this comprehensive article about named functions.
Variable Scope
There is another unique quality of functions, and that is an issue called variable scope. This is where variables you declare (create with var) within a function, only exist within that function.
var myCoolFunction = function(){
var data = [1, 2, 3, 4]; //created an array variable
}
console.log(data); //ERROR! data variable doesn't exist outside the function!
Also, any argument variables only exist within that function.
var calculateTip = function(bill){
return bill * .20;
}
console.log(bill); //ERROR! bill doesn't exist outside the function
Variable scope will become important later.
Functions as values inside objects
Remember that an object literal can store any data type. This includes functions.
var person = {
name : "Joe",
age : 25,
greeting : function(){ return "Hello!"; }
}
person.name //value is Joe as a string
person.age //value is Joe as a number
person.greeting() //this runs the function, and returns the string "Hello!"
“this” keyword
One of the most confusing aspects of JavaScript function is the use of this
keyword. Basically, there is a special variable called “this” which automatically exists inside every function. So, what is it’s value? The value of this
is the object that called the function.
This makes the most sense when the function is a value of an object, like in the earlier example.
var person = {
name : "Joe",
age : 25,
greeting : function(){
console.log(this.name);
//this will output "Joe", because this refers to the parent object
}
}
Conditionals
One of the hallmarks of programming is the conditional operator. It gives the programs the ability to logically assess a variable, and decide a course of action depending on the result.
We use these operators to find out if a particular condition is true, and to pick a course of action depending on the result.
Conditional operators use the keyword if to find out if a certain condition—which is surrounded in parenthesis—is true or false. If the condition is true, then code that is surrounded by curly brackets is executed. Here is an example:
var score = 5;
if(score == 10){
document.write("Congratulations! you won");
}
In the above example, we are assessing the condition x == 10 to see if this is true. The double-equals symbols is the equivalency operator, and checks to see if both sides of the equation are equal. This is different than the single-equals symbol, which is the assignment operator, and performs a different action of assigning a value to a variable.
In the above example, the code within the curly brackets would not execute, because the value score is not 10, and the condition was not true. So, our program would skip over the code in the curly brackets.
Here are some possible operators that can be used to establish conditions:
Operator | Description |
---|---|
== |
Equivalency Operator. Checks whether both sides are equal. |
!= |
Bang Operator. Checks whether both sides are not equal. |
> |
Greater than. Checks whether the left side is larger, but not equal to, the right side. |
< |
Less than. Checks whether the left side is smaller, but not equal to, the right side. |
>= |
Greater than or equal to. Checks whether the left side is greater or equal to right side. |
<= |
Less than or equal to. Checks whether the left side is less than or equal to the right side. |
Checking if value is more than or less than
In these examples, we check to see if the value is more than or less than another value. It’s important to note that all of these conditions will have either true or false result. If the condition is true, the code within the curly braces will be executed.
var x = 7;
var y = 10;
if(x > y){
document.write("You win!");
}
In the above example, the value of x is not more than y, therefore, the code in the curly braces will not execute.
var age = 12;
var requirement = 12;
if(age >= requirement){
document.write("You can ride the ferris wheel!");
}
In the above example, the code would be executed because the condition is true, age is more than or equal to the requirement variable. Else Statement
Sometimes you want some code to execute on when a condition is not met. We can optionally provide an alternative action using the else keyword, and a second set of curly brackets. Observe the following example:
var age = 20;
if(age >= 21){
document.write("Have a beer!");
} else {
document.write("Sorry, have a juice box instead.");
}
In the example above, the age variable is 20, which does not meet the condition of being more than or equal to 21. So the code inside the first set of curly brackets will not execute. The else statment provides an alterative when the condition fails, or is false. Negated Conditions
It’s important to remember that the program assesses the expression inside the parenthesis, to determine if it’s a true or false statement. This can be tricky at times, especially when using negated conditions. There is an operator called the not operator (also called a bang) that means “not equal to.” This is sometimes useful when you want to ensure the value can be anything but an equavalency. Observe the example below:
var answer = 3;
if(answer != 3.14){
document.write("This is not pi");
}
In the above example, the expression evaluates to a true statement, answer is not equal 3.14, so the program will execute the code between the curly brackets. Evaluating multiple conditions
There are times when you want to check if multiple conditions exist. JavaScript, and many other programming languages, offer two operators for determining if multiple conditions exist, the AND operator, and the OR operator. The AND operator is signified by two ampersands, like so &&. The OR operator is sigified by two bar or pipe keys, like so ||. Symbol Description
Symbol | Description |
---|---|
&& |
AND operator. Checks if all conditions are true. |
|| |
OR operator. Checks if either condition is true. |
In the example below, we use the AND operator to check if two conditions are true.
var minimumHeight = 48;
var maximumHeight = 78;
var rider = 40;
if(rider > minimumHeight && rider < maximumHeight){
document.write("you're tall enough to ride the ferris wheel");
}
In the example above, the code between the curly brackets will only execute if—and only if—both conditions are true. If one of them is false, the entire statement evaluates to false. The above example would not run, since the rider variable is not more than the minimumHeight, even through it is less than the maximumHeight.
The figure below shows and example using the OR operator:
var userResponse = "Maybe";
if(userReponse == "yes" || userResponse == "no"){
document.write("Thanks for answering the question");
} else {
document.write("Only yes or no responses are accepted");
}
In the example above, either condition can be true for the whole statement to be true. In situations where both conditions are true, the entire statement evaluates to true.
Below are some additional examples using the OR and AND operators:
if(x == 1 && y == 2 && z == 3){
document.write("All three conditions must be true to see this text.");
}
if(x == 1 || y == 2 || z == 3){
document.write("Any of the conditions can be true to see this text.");
}
Using Additional Parenthesis To Combine AND and OR operators
In situations where you want to use both AND and OR operators, you will need to specify the order of operations with additional parenthesis, like so:
if((x == 1 || x == 10) && (y == 1 || y == 6)){
document.write("For this to be seen, x needs to be 1 or 10 and y needs to be 1 or 6.");
}
Empty Strings and Zero-value Numbers
There are a couple of idiosyncrasies to JavaScript and the way it assesses certain variables. If a string is empty, the variable it is assigned to will assess as false. Also, any number that has a zero value, will also result in a false condition when assessed. Consider the following example:
var emptyString = "";
if(emptyString == true){
document.write("This text would only appear if the string had content.");
} else {
document.write("Empty strings are false.");
}
The same is true of zero-value numbers, which will result as a false statement. It should also be noted that it is possible to assess a variable without using the equivalency operator. Putting a variable in the parenthesis will assess whether the variable is true or false. This is also a great method to check if a variable has a value.
var num = 10;
num = num - 10; //num is now zero
if(num){
document.write("This text won't display since
num is zero, and false");
} else {
document.write("This text will display, since
num is zero, and thus false.");
}