COMP 1537
JavaScript Basics (Syntax, Operators, Control
Constructs)
Copyright Ⓒ 2022, Arron Ferguson 1
WORKFLOW (1/2)
1. Create an HTML document
2. Use the script element to either:
a) Embed the JavaScript right in the HTML document
b) Link to an external JavaScript script (BEST SOLUTION)
3. Open up your browser's (e.g., Chrome/Firefox) development tools
4. Start coding in your text editor, save work
5. Go to your browser, refresh the page
6. Observe the development tools console for messages/warnings/errors
Copyright Ⓒ 2022, Arron Ferguson 2
WORKFLOW (2/2)
Developer tools:
Elements – highlights HTML elements within the document
Console – displays info/warnings/errors (very important to use this!)
Sources – the different places where resources come from (e.g., ad networks)
Memory – memory usage of your app (includes JavaScript, connections, etc.)
Network – displays all data send/received
Performance – shows info on memory usage/function calls, etc.
Copyright Ⓒ 2022, Arron Ferguson 3
SYNTAX (1/2)
Computer programming language syntax
Set of rules for characters and symbols of a given programming language
Many programming languages (roughly) follow the C-programming language
syntax:
Java, C#, C++, ActionScript, JavaScript, PHP, etc.
With variations – but minor ones making it easy to learn another
When programming
You must (strictly) adhere to the language syntax
Or you will receive syntax errors in your program
Copyright Ⓒ 2022, Arron Ferguson 4
SYNTAX (2/2)
JavaScript syntax rules:
Lines should end with a semi-colon
Most other programming languages require this – so get used to it!
JavaScript is case-sensitive
'myVariable' is not the same as 'myvariable'
Use the 'var‘ & ‘let’ keyword to declare a variable (declare before using it)
// single line comment
/* */ multi-line comment
Copyright Ⓒ 2022, Arron Ferguson 5
DATA TYPES AND VARIABLES (1/3)
Computer programs process data
Quite often text-based data
But sometimes other types of data:
Images, videos, sound clips, etc.
Data can be:
Processed
Displayed
Both
Copyright Ⓒ 2022, Arron Ferguson 6
DATA TYPES AND VARIABLES (2/3)
Types of text-based data:
Character data (AKA string)
Series of characters
Must be wrapped with quotes (either double or single)
Can use escape characters for using quotes within quotes
Dates (including the time)
Numbers (with or without decimal places, so floating point, integer)
Boolean (true or false)
Variables are placeholders for data – that can be reused by using their name
E.g., var x = 4;
Copyright Ⓒ 2022, Arron Ferguson 7
DATA TYPES AND VARIABLES (3/3)
Variables can be declared and their values reassigned to something else
E.g., var x = 4; x = 2.4;
Some programming languages require you to declare a type with the variable
E.g., int x = 4;
These types of languages are strongly type
Meaning that the type is declared up front and all changes
JavaScript is loosely typed
You don't specify the type of variable
The type is inferred by the value that you give it
Copyright Ⓒ 2022, Arron Ferguson 8
OPERATORS (1/6)
Operators:
Several types of operators:
Assignment, arithmetic, comparison, bitwise, logical, string, special
Assignment operators:
Assign a value from right operand to left operand
var x = 4;
Arithmetic operators:
+, -, /, *
var x = (4 + 3);
Copyright Ⓒ 2022, Arron Ferguson 9
OPERATORS (2/6)
Can combine arithmetic operators with assignment:
Operator Example Same As
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
Copyright Ⓒ 2022, Arron Ferguson 10
OPERATORS (3/6)
String operator ‘+’
When used with strings it is a ‘concatenation’ operator
Which means it joins strings (two or more) together to create a new string of characters
Comparison operators
Comparing things to other things is fundamental in programming – JavaScript being no
exception
Comparing and acting on comparing utilizes two tools:
Equality/relational/logical operators
Conditional statement/(ternary)operator/switch
Copyright Ⓒ 2022, Arron Ferguson 11
OPERATORS (4/6)
The equals/not equals signs are for equality
The less than/greater than signs are relational
i.e., greater than, less than
Operator Description Comparing Returns
x == 8 false
== equal to
x == 5 true
x === "5" false
=== equal value and equal type
x === 5 true
!= not equal x != 8 true
x !== "5" true
!== not equal value or not equal type
x !== 5 false
> greater than x>8 false
< less than x<8 true
>= greater than or equal to x >= 8 false
<= less than or equal to x <= 8 true
Copyright Ⓒ 2022, Arron Ferguson 12
OPERATORS (5/6)
Logical operators
Check logical conditions
AND: all conditions must be met
E.g., it is sunny AND it Friday
OR: any one of the conditions must be met
E.g., It is Friday or it is Saturday
Operator Description Example
&& and (x < 10 && y > 1) is true
|| or (x == 5 || y == 5) is false
! not !(x == y) is true
Copyright Ⓒ 2022, Arron Ferguson 13
OPERATORS (6/6)
String operator:
'+'
Looks like the plus operator for arithmetic
What's the difference?
None between the symbol, difference is between the data types
We call this operator overloading
Meaning an operator is used in different contexts – and behaves differently based on the type
What happens when we mix data types?
Copyright Ⓒ 2022, Arron Ferguson 14
CONDITIONAL CONSTRUCTS
JavaScript offers the following in order to create conditional processing logic:
The if-else-if structures
The switch structure
The conditional operator
Copyright Ⓒ 2022, Arron Ferguson 15
IF-ELSE-IF STATEMENT
Allow for Boolean expressions to dictate the outcome of execution
The 'if' can be on it's own
Or also have an 'else'
Or also have one or more following 'else if' statements
Or have one or more 'else if' statements, then 'else'
If you have many conditions, may want to use a switch statement instead
Copyright Ⓒ 2022, Arron Ferguson 16
SWITCH STATEMENT
Functions similar to an 'if-else-if' structure
With multiple conditions being checked
Each 'case' handles a condition
Each 'case' needs to have a break
Otherwise the logic 'falls through' to following 'case's
Can have an optional 'default' handling
If none of the cases are met
Copyright Ⓒ 2022, Arron Ferguson 17
CONDITIONAL OPERATOR
Is a ternary operator (AKA conditional operator)
condition ? expr1 : expr2
Ternary because it has three parts to it:
The condition (which should evaluate to true or false)
The expression that is returned if the condition is true
The expression that is returned if the condition is false
Copyright Ⓒ 2022, Arron Ferguson 18
INTRO TO LOOPS
Execute one or more blocks of code a specified number of times
Based on conditions given
Several choices available:
For loop
For-in loop
While
Do while
Copyright Ⓒ 2022, Arron Ferguson 19
FOR LOOP
Consists of three optional expressions:
for ([initialization]; [condition]; [final-expression])
statement
Initialization: one or more variables
Condition: the expression that is evaluated at the end of each loop
If it evaluates to false, the loop breaks outs
Final expression: Statement: one or more statements that get executed each iteration
As long as the final expression evaluates to true
Copyright Ⓒ 2022, Arron Ferguson 20
FOR … IN LOOP
Enumerates over the enumerable properties of an object:
for (variable in object) {
statement
}
Variable: a different property name is assigned to variable on each iteration
Object: object whose enumerable properties are iterated
Statement: one or more statements that get executed each iteration
As long as the final expression evaluates to true
Copyright Ⓒ 2022, Arron Ferguson 21
WHILE LOOP
A loop that executes a specified statement as long as the test condition evaluates
to true:
while (condition) {
statement
}
Condition: the expression that is evaluated at the end of each loop
Statement: one or more statements that get executed each iteration
As long as the final expression evaluates to true
Copyright Ⓒ 2022, Arron Ferguson 22
DO … WHILE LOOP
Creates a loop that executes a specified statement until the test condition
evaluates to false:
do
statement
while (condition);
Condition: the expression that is evaluated at the end of each loop
Statement: one or more statements that get executed each iteration
As long as the final expression evaluates to true
Copyright Ⓒ 2022, Arron Ferguson 23
DIFFERENCES BETWEEN LOOPS (1/2)
For loop:
The "all inclusive" loop
i.e., initialization, condition, final expression
May not execute at all – depending on conditions
For in loop:
Used to iterate over the enumerable properties
The property order is arbitrary (i.e., not significant)
Copyright Ⓒ 2022, Arron Ferguson 24
DIFFERENCES BETWEEN LOOPS (2/2)
While loop
Requires variables and expressions to be made outside of loop
May not execute at all – depending on conditions
Do while loop
Requires variables and expressions to be made outside of loop
Executes at least once
Copyright Ⓒ 2022, Arron Ferguson 25
WHEN TO USE WHAT LOOP
For loop:
When you need fine control over conditions/incrementing/initialization
For in loop:
When going over a set of things in an object
While loop:
When you have an indefinite number of iterations
E.g., reading lines of text from a file
Do while loop:
When performing input checking
where loop body needs to be executed atleast once.
Copyright Ⓒ 2022, Arron Ferguson 26
HOW TO 'BREAK' OUT
The break statement
Terminates the current loop, switch, or label statement
When to use a break statement:
Switch statements
Usually avoided in most programming languages since they may cause the code to be
harder to read/understand
Copyright Ⓒ 2022, Arron Ferguson 27
JAVASCRIPT STRINGS (1/2)
Text processing is at the heart of most computing/processing
Web apps rely heavily on this!
HTML is markup, made with text
CSS is text
JavaScript is text
JavaScript has extensive support for processing of text
Via dozens of functions that:
Find/Search/replace text strings, find first instance of a character
Split strings up into arrays (known as tokenizing)
Change text case, add style/markup
Copyright Ⓒ 2022, Arron Ferguson 28
JAVASCRIPT STRINGS (2/2)
Types of text processing we may wish to do:
Add/modify/delete HTML elements to a page
Add/modify/delete CSS styling for elements in a page
Add/modify/delete JavaScript scripts for elements in a page
Yes, we can dynamically attach JavaScript scripts to a page – but we must be careful
Read through other site's web pages and find content
E.g., stories, pictures, galleries, user profiles, videos, news feeds, etc.
Retrieving/deciphering/displaying text-based data from web services
E.g., HTML snippets, XML, JSON
Copyright Ⓒ 2022, Arron Ferguson 29
RESOURCES (1/1)
https://developer.mozilla.org/en-
US/docs/Learn/Getting_started_with_the_web/JavaScript_basics
https://javascript.info/
Copyright Ⓒ 2022, Arron Ferguson 30