Chapter 3 - Functions, Methods and Objects Flashcards

1
Q

What is the difference between a function and a method?|

A

A function is a series of statements that have been grouped together because they perform a specific task.

A method is the same as a function, except that it is created inside, and is part of, an object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is an object?

A

A model of the world using data. Objects are made up of properties and methods. A browser comes with a set of built-in objects that act like a toolkit for creating interactive web pages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Why are functions useful?

A

They group together statements that perform a task, helping to organise code.
They are a way to store the steps that accomplish the task. This is useful if e.g. you only want the code to run when a user clicks on a page element.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you get a function to perform its task?

A

You should give a function that you intend to use later a name. The name should describe what it does. When you ask the function to perform its task, it is referred to as calling the function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are some other notable characteristics of functions?

A

Functions may package their code in a code block. Code blocks are one or more statements package in curly braces. There is no semi-colon after the end of the curly braces, as there would be in a statement.
Some functions need to be given information in order to achieve their goal. These pieces of information passed to the function are called parameters.
Functions that you expect to give an answer give back a return value.
Anonymous functions do not have a name, and are called when the interpreter comes across them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Give and example of a basic JavaScript Function

A
// Create a variable called msg to hold a new message
var msg = 'Sign up to receive our newsletter for 10% off!';
// Create a function to update the content of the element whose id attribute has a value of message
function updateMessage() {
  var el = document.getElementById('message');
  el.textContent = msg;
}
// Call the function
updateMessage();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How would you declare a function?

A

You give it a name and write statements needed to achieve its tasks inside curly braces.

You declare a function using the function keyword.
You give the function a name (or identifier) followed by parentheses.
The statements that perform the task sit in a code block, inside curly braces

function sayhello() {
	document.write(‘hello!’;)
}

How do you call a function

You can execute all the statements within the curly braces with just one line of code.
You call the function like so:

sayhello();

When a function is called, all the statements within its block are executed. The code then continues to run from the point where it was initially called.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Can you call a function before it has been declared?

A

Yes, because the interpreter runs through the entire script before executing each statement.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you declare a function that needs information?

A

When you declare the function, you give it parameters. Inside the function, these parameters act like variables.
You need to indicate what a function needs to know in parentheses after the function name. The items that appear in these parentheses are known as parameters of the function.

function getArea(width, height) {
	return width * height
}

This shows how code does not need to know exact details in advance, as long as it has rules to follow.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you call functions that need information?

A

You specify the values it should use in the parentheses that follow its name.
These values are called arguments, and can be provided as either values or variables.

Arguments as values:
getArea(3, 5);

Arguments as variables:
wallWidth = 3;
wallHeight = 5;
getArea(wallWidth,wallHeight);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the difference between a parameter and an argument?

A

Parameters are used when declaring a function. These words act like variables.
Arguments are used when calling a function. They are the real numbers used to perform the calculation (or variables that hold real numbers.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you get a single value from a function?

A

You declare a variable that holds the result of a calculation using arguments. You then use the return keyword.
e.g.

function calculateArea(width, height) {
	var area = width * height;
return area;
}
var wallOne = calculateArea(3, 5);
var wallTwo = calculateArea(8, 5);

The interpreter leaves the function when return is used.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do I get multiple values from a function?

A

create a function called getSize()
The area of a box is calculated and stored in a variable called area.
The volume is calculated and stored in a variable called volume.
Both are placed into an array called sizes.
The array is returned to the code that called the getSize function, allowing the values to be used.

function getSize(width, height, depth) {
	var area = width * height;
	var volume = width * height * depth;
var sizes = [area, voume];
	return sizes;
}
var areaOne = getSize(3, 2, 3) [0];
var volume = getSize(3, 2, 3) [1];
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Can you use a function where a value is expected?

A

Yes: Expressions produce a value. If a function is used where a value or expression are expected, it is treated as an expression. This is called a function expression.

Names are usually omitted in this case, meaning the functions involved are anonymous functions.

This means you can effectively store a function in a variable, like so:

var area = function(width, height) {
	return width * height;
};

var size = area(3, 4);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Why do you have to be careful when using function expressions?

A

With a function expression, the function is not processed until the interpreter gets to that statement.
This means you cannot call this function until the interpreter has discovered it.
It also means any preceding code may could potentially alter what goes on inside this function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is an immediately invoked function expression (IIFE)?

A

Pronounced ‘iffy’, these function expressions are invoked as soon as the interpreter comes across them.
Below, the variable area will hold the value returned by the function

var area = (function() {
	var width = 3;
	var height = 2;
}());

The final parentheses after the curly brace tell the interpreter to call the function immediately.
The grouping parentheses (after = and after the final parentheses ensure the interpreter treats these as an expression.
It is considered best practice to place the final parentheses before the closing group operator.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

When should you use anonymous functions and IFFEs?

A

For code that only needs to run once, rather than being repeatedly called from other parts of the script.

As an argument when a function is called (to calculate the value for that function).
To assign the value of a property to an object.
In event handlers and listeners to perform a task when an event occurs.
To prevent conflict between two scripts that might use the same variable names.

IFFEs are commonly used as a wrapper around a set of code.
Any variables declared within that code are effectively protected from variables in other scripts that might have the same name.
This is due to a concept called scope.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is scope?

A

This is how the location of a variable affects where it can be used within your code.
e.g. If a variable is declared within a function, it can only be used within that function.

19
Q

What is a local variable?

A

When a variable is created within a function using the var keyword, it can only be used within that function because it is a local or function-level variable.
It is said to have local scope or function level scope.
The interpreter creates local variables when a function is run, and removes them when that function has finished its task.
This means:
If a function runs twice, the variable can have different values each time.
Two different functions can use the same variable names without conflict.

20
Q

What is a global variable?

A

If you create a variable outside a function, it can be used anywhere in a script.
It is a global variable and has global scope.
Global variables stay in memory for as long as the web browser is loaded into the web browser.
This means:
They take up more memory than local variables.
They increase the risk of naming conflicts.
This means you should use local variables whenever possible.

21
Q

How are variables stored in memory?

A

Variables reference a value that is stored in memory.
This means that the same value can be used with more than one variable.
e.g.
var isWall = true;
var canPaint = true;

These both point to the same true value in memory.

22
Q

Why do you need to be vigilant in order to avoid naming conflicts?

A

Even though you can control the names YOU give to variables, many scripts are written by more than one person.
Also, if an HTML page uses two JS files, and both have global variables of the same name, it can cause errors.

e.g. Scripts one and two both have a global variable - var = msg.

23
Q

What is an Object?

A

Objects group together a set of variables and functions to create a model of something you would recognise from the real world.

24
Q

How do variables and functions change when they are part of an object?

A

Variables become Properties - e.g. the number of rooms in a hotel
Functions become Methods - representing tasks associated with the object - checkAvailability()

25
Q

What is a key?

A

Like variables and functions, properties and methods have a name and a value.
In an Object, that name is called a key.
An object cannot have two keys with the same name, as keys are used to access their corresponding values.
The value of a property can be a string, number, Boolean, array or even another object.
The value of a method is always a function.

26
Q

Give an example of an Object

A
var hotel = {
	name: ‘Quay’,
	rooms: 40,
	booked: 25,
	gym: true,
	roomTypes:[‘twin’, ‘double’, ‘suite’],
checkAvailability: function() {
	return this .rooms - this.booked; } };
27
Q

Key value pairs are used when defining properties and methods in an Object. Give some other examples of where they might be used in programming.

A

HTML - Attribute names and values
CSS - Property names and values

Javascript

Variables - names and values (string, number or Boolean)
Arrays - name and group of values (each item in an array is a name/value pair as it has an index number and a value.)
Named functions have a name and a value that is a set of to run if the function is called.
Objects consist of a set of name/value pairs - The names are referred to as keys.

28
Q

How would you create an Object using Literal Notation?

A

Literal notation is the easiest and most popular way to create objects.
An object is the curly braces and their contents.
The object is stored in a variable called hotel.
You would refer to this as the hotel object.
Separate each key from its value using a colon.
Separate each property and method with a comma, but not after the last value.

var hotel - {

name: ‘Quay’,
rooms: 40, booked: 25,

checkAvailability: function() {
return this.rooms - this.booked;
}
};

In this example, the this keyword is used to indicate that it is using the rooms and booked properties of this object.

When setting properties,, treat the values like you would do for variables.
Strings live in quotes and arrays live in square brackets.

29
Q

How would you access the methods or properties of an object?

A

Using dot notation.
You use the name of the object, followed by a period, then the name of the property or method you want to access.
This is known as dot notation.
The period is known as the member operator

30
Q

Give an example of accessing the methods and properties of an object.

A
var hotelName = hotel.name;
var roomsFree = hotel.checkAvailability();
31
Q

How else can you access the properties of an object?

A

Using square bracket syntax.
The object name is followed by a square bracket and the property name is inside them.
var hotelName = hotel[‘name’];

32
Q

When would you use square bracket syntax?

A

When the name of the property is a number - This is allowed, but should be avoided.
A variable is being used in place of a property name.

33
Q

Give some examples of creating objects using Literal Notation

A
// Set up the object
var hotel = {
  name : 'Quay',
  rooms : 40,
  booked : 25,
  checkAvailability : function() {
    return this.rooms - this.booked; // Need "this" because inside function
  }
};
// Update the HTML
var elName = document.getElementById('hotelName'); // Get element
elName.textContent = hotel.name;                   // Update HTML with property of the object
var elRooms = document.getElementById('rooms');    // Get element
elRooms.textContent = hotel.checkAvailability();   // Update HTML with property of the object
/* 
NOTE: textContent does not work in IE8 or earlier
You can use innerHTML on lines 13 and 16, but note the security issues on p228-231
*/

The object is called hotel which represents the Quay hotel with 45 rooms, of which 25 have been booked.
Next, the content of the page is updated with data from this particular object.
You can supply methods with parameters via parenthese, just as you would pass arguments to a function.

// Set up the object
var hotel = {
  name : 'Park',
  rooms : 120,
  booked : 77,
  checkAvailability : function() {
    return this.rooms - this.booked; // Need "this" because inside function
  }
};
// Update the HTML
var elName = document.getElementById('hotelName'); // Get element
elName.textContent = hotel.name;                   // Update HTML with property of the object
var elRooms = document.getElementById('rooms');    // Get element
elRooms.textContent = hotel.checkAvailability();   // Update HTML with property of the object
/* 
NOTE: textContent does not work in IE8 or earlier
You can use innerHTML on lines 13 and 16, but note the security issues on p228-231
*/

This second example only changes as far as the values of the hotel object’s properties.
The rest of the page works exactly the same way.
If you had two objects on the same page, you would create each one using the same notation, but store them in variables with different names.

34
Q

How would you create an object using constructor notation?

A

The new keyword and the object constructor create a blank object.
First you create a new object using
the new keyword
the Object() constructor function, which is part of JS and used to create objects.
Next, you add properties and methods to it using dot notation
Each statement that adds a property or method should end with a semicolon.

35
Q

Give an example of creating an object using constructor notation…

A

var hotel = new Object();

hotel.name = ‘Quay’;
hotel.rooms = 40;
hotel.booked = 25;
hotel.checkAvailability = function() {
return this.rooms - this.booked;
};

You can use this syntax to add properties and methods to any object you have created

36
Q

How would you create an empty object using object literal notation?

A

var hotel = {}

37
Q

How would you update an object?

A

To update values of an object, use dot notation or square brackets.
This works on all objects, whether created with literal or constructor notation.

38
Q

Give and example of updating an object.

A
hotel.name = ‘Park’;
hotel[‘name’] = ‘Park’;

If the property you are trying to update does not exist, it will be added to the object.

39
Q

How would you delete a property from an object?

A

Use the delete keyword

delete hotel.name

To clear the value of a property, you can set it to a blank string.

hotel.name = ‘’;

40
Q

How would you create many objects at once using constructor notation? Give an example.

A

Object constructors can use a function as a template for creating objects.
First, create a template with the object’s properties and methods.

Create a function called hotel.
Like all functions, it contains statements, in this case, ones that add properties and methods to an object.
The function has three parameters - each one sets the value of a property in an object.
The method will be the same for each object created using this object.

function Hotel (name, rooms, booked) {
	this.name = name;
	this.rooms = rooms;
	this.booked = booked;
	this.checkAvailability = function() {
	return this.rooms - this.booked;
};
}

The ‘this’ value is used instead of the object name to indicate that the property or method belongs to the object that this function creates.
Each statement that creates a new property or method for this statement for this object ends with a semicolon, not a comma as used in literal syntax.
The name of a constructor function usually begins with a capital letter.
The uppercase letter is supposed to help remind developers to use the new keyword when they create an object using that function.

41
Q

How do you create instances of an object using a constructor function?

A

The new keyword, followed by a call to the function creates a new object.
The properties of each object are given as arguments to the function

e.g.

var quayHotel = new Hotel(‘Quay’, 40, 25);
var quayHotel = new Hotel(‘Park’, 120, 77);

Methods stay the same for each object because they access, update, or perform a calculation based on the data stored in the properties.

42
Q

When would it be appropriate to use a constructor function?

A

If your script contains a very complex object that needs to be available, but might not be used..
The object is defined in the function, but only created if it is needed.

43
Q

Give an example of creating objects using constructor syntax.

A
// Set up the object
var hotel = new Object();

hotel.name = ‘Park’;
hotel.rooms = 120;
hotel.booked = 77;
hotel.checkAvailability = function() {
return this.rooms - this.booked;
};

var elName = document.getElementById('hotelName'); // Get element
elName.textContent = hotel.name;                   // Update HTML with property of the object
var elRooms = document.getElementById('rooms');    // Get element
elRooms.textContent = hotel.checkAvailability();   // Update HTML with result of method
/* 
NOTE: textContent does not work in IE8 or earlier
You can use innerHTML on lines 12 and 15, but note the security issues on p228-231
*/
44
Q

Give an example of creating and accessing objects using constructor notation.

A
// Create the template for objects that are hotels
function Hotel(name, rooms, booked) {
  this.name = name;
  this.rooms = rooms;
  this.booked = booked;
  this.checkAvailability = function() {
    return this.rooms - this.booked;
  };
}
// Create two hotel objects
var quayHotel = new Hotel('Quay', 40, 25);
var parkHotel = new Hotel('Park', 120, 77);
// Update the HTML for the page
var details1 = quayHotel.name + ' rooms: ';
    details1 += quayHotel.checkAvailability();
var elHotel1 = document.getElementById('hotel1');
elHotel1.textContent = details1;
var details2 = parkHotel.name + ' rooms: ';
    details2 += parkHotel.checkAvailability();
var elHotel2 = document.getElementById('hotel2');
elHotel2.textContent = details2;
/* 
NOTE: textContent does not work in IE8 or earlier
You can use innerHTML on lines 21 and 26, but note the security issues on p228-231
*/