JavaScript
Sixth Edition
Chapter 2
Working with Functions, Data Types, and
Operators
2
Objectives
When you complete this chapter, you will be able to:
Use functions to organize your JavaScript code
Use expressions and operators
Identify the order of operator precedence in an expression
JavaScript, Sixth Edition
3
Working with Functions
Methods
Procedures associated with an object
Functions
Related group of JavaScript statements
Executed as a single unit
Virtually identical to methods
Not associated with an object
Must be contained within a script element
JavaScript, Sixth Edition
4
Defining Functions
Named function
Related statements assigned a name
Call, or reference, named function to execute it
Anonymous function
Related statements with no name assigned
Work only where they are located in code
Use named function when you want to reuse code
Use anonymous function for code that runs only once
JavaScript, Sixth Edition
5
Defining Functions (cont'd.)
Function definition
Lines making up a function
Named function syntax
function name_of_function(parameters) {
statements;
}
Anonymous function syntax
function (parameters) {
statements;
}
JavaScript, Sixth Edition
6
Defining Functions (cont'd.)
Parameter
Variable used within a function
Placed within parentheses following a function name
Multiple parameters allowed
calculateVolume(length, width, height)
JavaScript, Sixth Edition
7
Defining Functions (cont'd.)
Function statements
Do the actual work
Contained within function braces
Put functions in an external .js file
Reference at bottom of body section
function calculateVolume(length, width, height) {
var volume = length * width * height;
document.write(volume);
}
JavaScript, Sixth Edition
8
Calling Functions
To execute a named function:
Must invoke, or call, it
Function call
Code calling a function
Consists of function name followed by parentheses
Contains any variables or values assigned to the function parameters
Arguments (actual parameters)
Variables (values) placed in the function call statement parentheses
JavaScript, Sixth Edition
9
Calling Functions (cont'd.)
Passing arguments
Sending arguments to parameters of a called function
Argument value assigned to the corresponding parameter value in the
function definition
JavaScript, Sixth Edition
10
Calling Functions (cont'd.)
Handling events
Three options
Specify function as value for HTML attribute
<input type="submit" onclick="showMessage()" />
Specify function as property value for object
document.getElementById("submitButton").onclick =↵ showMessage;
Use addEventListener() method
var submit = document.getElementById("submitButton");
submit.addEventListener("click", showMessage, false);
JavaScript, Sixth Edition
11
Calling Functions (cont'd.)
Adding an event listener is most flexible
Separates HTML and JavaScript code
Can specify several event handlers for a single event
IE8 requires use of the attachEvent() method instead of
addEventListener() (see Chapter 3)
JavaScript, Sixth Edition
12
Locating Errors with the Browser
Console
Unintentional coding mistakes keep code from working
Browsers generate error messages in response
Messages displayed in browser console pane
Hidden by default to avoid alarming users
Developers display browser console to see errors
JavaScript, Sixth Edition
13
Locating Errors with the Browser
Console (cont'd.)
Consoles specify a line number with each error
Figure 2-3: Internet Explorer browser console
Figure 2-4: Chrome browser console
JavaScript, Sixth Edition
14
Using Return Statements
Can return function value to a calling statement
Return statement
Returns a value to the statement calling the function
Use the return keyword with the variable or value to send to the calling statement
Example:
function averageNumbers(a, b, c) {
var sum_of_numbers = a + b + c;
var result = sum_of_numbers / 3;
return result;
}
JavaScript, Sixth Edition
15
Understanding Variable Scope
Variable scope
Where in code a declared variable can be used
Global variable
Declared outside a function
Available to all parts of code
Local variable
Declared inside a function
Only available within the function in which it is declared
Cease to exist when the function ends
Keyword var required
JavaScript, Sixth Edition
16
Understanding Variable Scope
(cont’d.)
Good programming technique
Always use the var keyword when declaring variables
Clarifies where and when variable used
Poor programming technique
Declaring a global variable inside of a function by not using the
var keyword
Harder to identify global variables in your scripts
JavaScript, Sixth Edition
17
Understanding Variable Scope
(cont’d.)
If variable declared within a function and does not include the
var keyword
Variable automatically becomes a global variable
Program may contain global and local variables with the same
name
Local variable takes precedence
Value assigned to local variable of the same name
Not assigned to global variable of the same name
JavaScript, Sixth Edition
18
Understanding Variable Scope (cont’d.)
var color = "green";
function duplicateVariableNames() {
var color = "purple";
document.write(color);
// value printed is purple
duplicateVariableNames();
document.write(color);
JavaScript, Sixth Edition
// value printed is green
19
Using Built-in JavaScript Functions
Called the same way a custom function is called
JavaScript, Sixth Edition Table 2-2 Built-in JavaScript functions
20
Working with Data Types
Data type
Specific information category a variable contains
Primitive types
Data types assigned a single value
Table 2-3 Primitive JavaScript data types
JavaScript, Sixth Edition
21
Working with Data Types (cont’d.)
The null value: data type and a value
Can be assigned to a variable
Indicates no usable value
Use: ensure a variable does not contain any data
Undefined variable
Never had a value assigned to it, has not been declared, or does not
exist
Indicates variable never assigned a value: not even null
Use: determine if a value being used by another part of a script
JavaScript, Sixth Edition
22
Working with Data Types (cont’d.)
var stateTax;
document.write(stateTax);
stateTax = 40;
document.write(stateTax);
stateTax = null;
document.write(stateTax);
Figure 2-7 Variable assigned values of undefined and null
JavaScript, Sixth Edition
23
Working with Data Types (cont’d.)
Strongly typed programming languages
Require declaration of the data types of variables
Strong typing also known as static typing
Data types do not change after declared
Loosely typed programming languages
Do not require declaration of the data types of variables
Loose typing also known as dynamic typing
Data types can change after declared
JavaScript, Sixth Edition
24
Working with Data Types (cont’d.)
JavaScript interpreter automatically determines data type stored in a variable
Examples:
diffTypes = "Hello World"; // String
diffTypes = 8; // Integer number
diffTypes = 5.367; // Floating-point number
diffTypes = true; // Boolean
diffTypes = null;
JavaScript, Sixth Edition
// Null
25
Understanding Numeric Data Types
JavaScript supports two numeric data types
Integers and floating-point numbers
Integer
Positive or negative number with no decimal places
Floating-point number
Number containing decimal places or written in exponential
notation
Exponential notation (scientific notation)
Shortened format for writing very large numbers or numbers with many
decimal places
JavaScript, Sixth Edition
26
Using Boolean Values
Logical value of true or false
Used for decision making
Which parts of a program should execute
Used for comparing data
JavaScript programming Boolean values
The words true and false
JavaScript converts true and false values to the integers 1 and 0
when necessary
JavaScript, Sixth Edition
27
Using Boolean Values (cont’d.)
1 var newCustomer = true;
2 var contractorRates = false;
3 document.write("<p>New customer: " + newCustomer + "</p>");
4 document.write("<p>Contractor rates: " + contractorRates +↵
5 "</p>");
Figure 2-9 Boolean values
JavaScript, Sixth Edition
28
Working with Strings
Text string
Contains zero or more characters
Surrounded by double or single quotation marks
Can be used as literal values or assigned to a variable
Empty string
Zero-length string value
Valid for literal strings
Not considered to be null or undefined
JavaScript, Sixth Edition
29
Working with Strings (cont’d.)
To include a quoted string within a literal string surrounded by
double quotation marks
Surround the quoted string with single quotation marks
To include a quoted string within a literal string surrounded by
single quotation marks
Surround the quoted string with double quotation marks
String must begin and end with the same type of quotation
marks
JavaScript, Sixth Edition
30
Working with Strings (cont’d.)
document.write("<h1>Speech at the Berlin Wall↵
(excerpt)</h1>");
document.write("<p>Two thousand years ago, the proudest boast ↵
was 'civis Romanus sum.'<br />");
document.write('Today, in the world of freedom, the proudest↵
boast is "Ich bin ein Berliner."</p>');
var speaker = "<p>John F. Kennedy</br>";
var date = 'June 26, 1963</p>';
document.write(speaker);
document.write(date);
JavaScript, Sixth Edition
Figure 2-10 String examples in a browser
31
Working with Strings (cont’d.)
String operators
Concatenation operator (+): combines two strings
var destination = "Honolulu";
var location = "Hawaii";
destination = destination + " is in " + location;
Compound assignment operator (+=): combines two strings
var destination = "Honolulu";
destination += " is in Hawaii";
Plus sign
Concatenation operator and addition operator
JavaScript, Sixth Edition
32
Working with Strings (cont’d.)
Escape characters and sequences
Escape character
Tells the compiler or interpreter that the character that follows has a
special purpose
In JavaScript, escape character is backslash (\)
Escape sequence
Escape character combined with other characters
Most escape sequences carry out special functions
JavaScript, Sixth Edition
33
Working with Strings (cont’d.)
JavaScript, Sixth Edition Table 2-4 JavaScript escape sequences
34
Using Operators to Build
Expressions
JavaScript, Sixth Edition
Table 2-5 JavaScript operator types (continues)
Using Operators to Build Expressions 35
(cont’d.)
Table 2-5 JavaScript operator types (cont'd.)
36
Using Operators to Build
Expressions (cont’d.)
Binary operator
Requires an operand before and after the operator
Unary operator
Requires a single operand either before or after the operator
JavaScript, Sixth Edition
37
Arithmetic Operators
Perform mathematical calculations
Addition, subtraction, multiplication, division
Returns the modulus of a calculation
Arithmetic binary operators
JavaScript, Sixth Edition Table 2-6 Arithmetic binary operators
38
Arithmetic Operators (cont’d.)
Arithmetic binary operators (cont’d.)
Value of operation on right side of the assignment operator
assigned to variable on the left side
Example: arithmeticValue = x + y;
Result assigned to the arithmeticValue variable
Division operator (/)
Standard mathematical division operation
Modulus operator (%)
Returns the remainder resulting from the division of two integers
JavaScript, Sixth Edition
Arithmetic Operators (cont’d.) 39
var divisionResult = 15 / 6;
var modulusResult = 15 % 6;
document.write("<p>15 divided by 6 is "↵
+ divisionResult + ".</p>"); // prints '2.5'
document.write("<p>The whole number 6 goes into 15 twice,↵
with a remainder of "+ modulusResult + ".</p>");↵ // prints '3'
JavaScript, Sixth Edition Figure 2-13 Division and modulus expressions
40
Arithmetic Operators (cont’d.)
Arithmetic binary operators (cont’d.)
Assignment statement
Can include combination of variables and literal values on the right side
Cannot include a literal value as the left operand
JavaScript interpreter
Attempts to convert the string values to numbers
Does not convert strings to numbers when using the addition operator
JavaScript, Sixth Edition
41
Arithmetic Operators (cont’d.)
Prefix operator
Placed before a variable
Postfix operator
Placed after a variable
Table 2-7 Arithmetic unary operators
JavaScript, Sixth Edition
42
Arithmetic Operators (cont’d.)
Arithmetic unary operators
Performed on a single variable using unary operators
Increment (++) unary operator: used as prefix operators
Prefix operator placed before a variable
Decrement (--) unary operator: used as postfix operator
Postfix operator placed after a variable
Example: ++count; and count++;
Both increase the count variable by one, but return different values
JavaScript, Sixth Edition
43
Arithmetic Operators (cont’d.)
Figure 2-14 Output of the prefix version of the student ID script
44
Arithmetic Operators (cont’d.)
Figure 2-15 Output of the postfix version of the student ID script
45
Assignment Operators
Used for assigning a value to a variable
Equal sign (=)
Assigns initial value to a new variable
Assigns new value to an existing variable
Compound assignment operators
Perform mathematical calculations on variables and literal values
in an expression
Then assign a new value to the left operand
JavaScript, Sixth Edition
46
Assignment Operators (cont’d.)
JavaScript, Sixth Edition Table 2-8 Assignment operators
47
Assignment Operators (cont’d.)
+= compound addition
assignment operator
Used to combine two strings and
to add numbers
Examples:
JavaScript, Sixth Edition
48
Assignment Operators (cont’d.)
Examples: (cont’d.)
JavaScript, Sixth Edition
49
Comparison and Conditional
Operators
Comparison operators
Compare two operands
Determine if one numeric value is greater than another
Boolean value of true or false returned after compare
Operands of comparison operators
Two numeric values: compared numerically
Two nonnumeric values: compared in alphabetical order
Number and a string: convert string value to a number
If conversion fails: value of false returned
JavaScript, Sixth Edition
50
Comparison and Conditional Operators (cont’d.)
JavaScript, Sixth Edition Table 2-9 Comparison operators
51
Comparison and Conditional
Operators (cont’d.)
Conditional operator
Executes one of two expressions based on conditional expression
results
Syntax
conditional expression ? expression1 : expression2;
If conditional expression evaluates to true:
Then expression1 executes
If the conditional expression evaluates to false:
Then expression2 executes
JavaScript, Sixth Edition
52
Comparison and Conditional
Operators (cont’d.)
Example of conditional operator:
var intVariable = 150;
var result;
intVariable > 100 ?↵
result = "intVariable is greater than 100" :↵
result = "intVariable is less than or equal to 100";
document.write(result);
JavaScript, Sixth Edition
53
Falsy and Truthy Values
Six falsy values treated like Boolean false:
""
-0
0
NaN
null
undefined
All other values are truthy, treated like Boolean true
JavaScript, Sixth Edition
54
Logical Operators
Compare two Boolean operands for equality
Table 2-10 Logical operators
JavaScript, Sixth Edition
55
Special Operators
Table 2-11 Special operators
56
Special Operators (cont’d.)
Table 2-12 Values returned by typeof operator
JavaScript, Sixth Edition
57
Understanding Operator Precedence
Operator precedence
Order in which operations in an expression evaluate
Associativity
Order in which operators of equal precedence execute
Left to right associativity
Right to left associativity
JavaScript, Sixth Edition
58
Understanding Operator Precedence
(cont’d.)
Evaluating associativity
Example: multiplication and division operators
Associativity of left to right
Figure 2-16 Conceptual illustration
JavaScript, Sixth Edition of left to right associativity
59
Understanding Operator Precedence
(cont’d.)
Evaluating associativity (cont’d.)
Example: Assignment operator and compound assignment operators
Associativity of right to left
x = y *= ++x
var x = 3;
var y = 2;
x = y *= ++x;
Figure 2-17 Conceptual illustration
of right-to-left associativity
JavaScript, Sixth Edition
60
Summary
Functions
Similar to methods associated with an object
Pass parameters
To execute, must be called
Variable scope
Where a declared variable can be used
Global and local variables
Data type
Specific category of information a variable contains
Static typing and dynamic typing
JavaScript, Sixth Edition
61
Summary (cont’d.)
Numeric data types: integer and floating point
Boolean values: true and false
Strings: one or more character surrounded by double or single
quotes
String operators
Escape character
Operators build expressions
Operator precedence
Order in which operations in an expression are evaluated
JavaScript, Sixth Edition