BASIC JAVA SCRIPT INSTRUCTIONS
STATEMENTS
• A script is a series of instructions that a computer can follow one-by-
one. Each individual instruction or step is known as a statement.
Statements should end with a semicolon.
COMMENTS
• COMMENTS help make your code easier to read and understand. This
can help you and others who read your code.
WHAT IS A VARIABLE?
• A script will have to temporarily store the bits of information it needs
to do its job. It can store this data in variables.
var quantity;
var is a keyword
quantity is a variable name(case sensitive)
How to assign the them
[Link] TYPES
• JavaScript distinguishes between numbers, strings, and true or false
values known as Booleans.
USING A VARIABLE TO STORE A Declaring Variables:
NUMBER var price;, var quantity;, var total; declare three variables.
Assigning Values:
price = 5; → Each tile costs $5
quantity = 14; → The user wants to buy 14 tiles
Calculating Total Cost:
total = price * quantity;
Since 5 * 14 = 70, the total cost is $70.
Selecting an HTML Element:
[Link]('cost') finds the HTML <div> with id="cost".
Updating the Page Content:
[Link] = '$' + total; changes the content of that <div> to display "$70".
• Html
Heading (<h1>)
<h1>Elderflower</h1> → Displays the main title of the page.
Content Division (<div id="content">)
Groups everything inside a section.
Subheading (<h2>)
<h2>Custom Signage</h2> → Describes the type of product.
Cost Section (<div id="cost">)
Initially displays:pgsql
Cost: $5 per tile
JavaScript updates this content dynamically to display "$70" instead.
Image (<img>)
<img src="images/[Link]" alt="Sign" />
Displays a preview image of the signage.
Linking JavaScript (<script>)
<script src="js/[Link]"></script>
USING A VARIABLE TO STORE A
STRING
JavaScript (Makes the Page Interactive)
JavaScript allows you to change content dynamically without manually
editing the HTML every time.
• [Link]('name') finds the <span> with
id="name".
• [Link] = username; changes "friend" to "Molly".
• [Link]('note') finds the <div> with id="note".
• [Link] = message; updates "Take a look around..." to
"See our upcoming range".
HTML (Structure of the Page)
HTML provides the structure of the webpage. It defines elements like
headings, paragraphs, divs, and spans. In your case:
• The <span id="name">friend</span> is a placeholder for the
username.
• The <div id="note">Take a look around...</div> is where a message
will appear. These elements have IDs (name and note) so JavaScript
can find and modify them.
USING QUOTES INSIDE A
STRING
Declares two variables:
title and message to store text
Assigns the string "Molly's Special Offers" to the variable [Link] apostrophe (') in "Molly's" is
correctly used inside double quotes ("") to avoid errors. .
Assigns an HTML link (<a>) to [Link] double quotes for the href="[Link]" inside single quotes to prevent errors.
[Link]('title') finds the <div
id="title">.[Link] = title; replaces the content inside
that <div> with "Molly's Special Offers".
[Link]('note') finds <div
id="note">.[Link] = message; replaces the content
inside that <div> with a clickable link.
• Html
• A heading for the page.
• Groups related content inside a div container.
• Initially shows "Special Offers", but JavaScript will update
this with "Molly's Special Offers".
• Initially displays "Sign-up to receive personalized offers!",
but JavaScript will replace this with a clickable link (25%
off!).
• Links the JavaScript file so that it runs when the page loads.
USING A VARIABLE TO STORE A
BOOLEAN
SHORTHAND FOR CREATING
VARIABLES
CHANGING THE VALUE OF A
VARIABLE
RULES FOR NAMING VARIABLES
• The name must begin with a letter, dollar sign ($),or an underscore (_). It must
not start with a number.
• The name can contain letters, numbers, dollar sign ($), or an underscore (_). Note
that you must not use a dash(-) or a period (.) in a variable name.
• The name can contain letters, numbers, dollar sign ($), or an underscore (_). Note
that you must not use a dash(-) or a period (.) in a variable name.
• All variables are case sensitive, so score and Score would be different variable
names, but it is bad practice to create two variables that have the same name
using different cases.
• Use a name that describes the kind of information that the variable stores. For
example, firstName might be used to store a person's first name, lastName for
their last name, and age for their age.
• If your variable name is made up of more than one word, use a capital letter for
the first letter of every word after the first word. For example, firstName rather
than firstname(this is referred to as camel case). You can also use an underscore
between each word (you cannot use a dash).
ARRAYS
• An array is a special type of variable. It doesn't just store one value; it
stores a list of values.
For example, an array can be suited to storing the individual items on a
shopping list because it is a list of related items.
CREATING AN ARRAY
VALUES IN ARRAYS
• Values in an array are accessed as if they are in a numbered list. It is
important to know that the numbering of this list starts at zero (not
one).
NUMBERING ITEMS IN AN ARRAY
var colors; colors= ['white ' , 'black ' , ' custom ‘];
INDEX VALUE
0 ‘white ‘
1 ‘black’
2 ‘custom’
ACCESSING & CHANGING VALUES IN
AN ARRAY
EXPRESSIONS
• An expression evaluates into (results in) a single value. Broadly
speaking there are two types of expressions.
OPERATORS
• Expressions rely on things called operators; they allow programmers
to create a single value from one or more values.
ARITHMETIC OPERATORS
• JavaScript contains the following mathematical operators, which you
can use with numbers. You may remember some from math class.
USING ARITHMETIC OPERATORS
STRING OPERATOR
• There is just one string operator: the+ symbol. It is used to join the
strings on either side of it.
USING S'TRING We declare a variable greeting and assign it the string 'Howdy '.We
OPERATORS declare another variable name and assign it the string 'Molly'.
•We create a third variable welcomeMessage by concatenating (+)
the greeting, name, and '!' to form 'Howdy Molly!'.
•We use [Link]('greeting') to select the HTML
element with id="greeting".We then replace the text content of
that element with the welcomeMessage value ('Howdy Mol ly!').
<h1>Elderflower</h1>
This is just a heading.
<div id="content">...</div>
This wraps the content for better structure.
<div id="greeting" class="message">Hello <span
id="name">friend</span>!</div>
This contains the text "Hello friend!" initially.
JavaScript modifies this text dynamically.
<script src="js/[Link]"></script>
This links the JavaScript file ([Link]) so the script can
run.
FUNCTIONS METHODS
AND OBJECTS
WHAT IS A FUNCTION?
• Functions let you group a series of statements together to perform a
specific task. If different parts of a script repeat the same task, you
can reuse the function (rather than repeating the same set of
statements).
A BASIC
FUNCTION
• To create a function ,you give it a name and then write the statements
needed to achieve its task inside the curly braces. This is know as a
function declaration.
ANONYMOUS FUNCTIONS & FUNCTION EXPRESSIONS
• Expressions produce a value. They can be used where values are expected. If a function is placed
where a browser expects to see an expression, (e.g., as an argument to a function), then it gets
treated as an expression.
IMMEDIATELY INVOKED FUNCTION EXPRESSIONS
• This way of writing a function is used in several different situations. Often
functions are used to ensure that the variable names do not conflict with each
other (especially if the page uses more than one script).
VARIABLE SCOPE
• The location where you declare a variable will affect where it can be
used within your code. If you declare it within a function, it can only
be used within that function. This is known as the variable's scope.
HOW MEMORY & VARIABLES WORK
• Global variables use more memory. The browser has to remember
them for as long as the web page using them is loaded. Local variables
are only remembered during the period of time that a function is
being executed.
• Variables in global scope: have naming conflicts.
• Variables in function scope: there is no conflict between them.
WHAT IS AN OBJECT?
• Objects group together a set of variables and functions to create a
model of a something you would recognize from the real world. In an
object, variables and functions take on new names.
• This object represents a hotel. It has five properties and one method.
The object is in curly braces. It is stored in a variable called hotel .
.1Properties (Key-Value Pairs)
•name: "1 Quay 1" → Stores the name of the hotel.
•rooms: 40 → Stores the total number of rooms in the hotel.
•booked: 25 → Stores how many rooms are already booked.
3. Method (checkAvailability)
•The function checkAvaiability() calculates how many rooms are still available.
•It does this by subtracting booked rooms from rooms
•[Link] refers to the rooms property inside the hotel object.
•[Link] refers to the booked property inside the same object.
The function returns 40 - 25 = 15
this refers to the
current object
(hotel in this case).
and also
CREATING· OBJECTS USING LITERAL NOTATION
•Constructor notation uses a function
to create objects.
•Use this inside the function to assign
properties.
•Call it with new to create new objects.
CREATE & ACCESS OBJECTS
CONSTRUCTOR NOTATION
(The+= operator is used to add content to an
existing variable.)
ADDING AND REMOVING PROPERTIES
If an object is created using a constructor function, this
syntax only adds or removes the properties from the one
instance of the object (not all objects created with that
function).
THIS (IT IS A KEYWORD)
The keyword this is commonly used inside functions and objects. Where the
function is declared alters what this means. It always refers to one object, usually
the object in which the function operates.
The window object represents the current browser window or tab. It is the topmost object in the Browser Object
Model, and it contains other objects that tell you about the browser.
THE DOCUMENT OBJECT MODEL: THE
DOCUMENT OBJECT
The topmost object in the Document Object Model (or DOM) is the
document object. It represents the web page loaded into the current
browser window or tab.
GLOBAL OBJECTS: STRING O BJECT
• Whenever you have a value that is a string, you can use the properties
and methods of the String object on that value.
This example demonstrates the length property and many of the string object's methods shown on the previous slide.
DATA TYPES REVISITED
• In JavaScript there are six data types: Five of them are described as
simple (or primitive) data types. The sixth is the object (and is referred
to as a complex data type).
GLOBAL OBJECTS: NUMBER OBJECT
MATH OBJECT TO CREATE RANDOM
NUMBERS
Other examples are
Round()
Floor()
GLOBAL OBJECTS: DATE OBJECT
(AND TIME)
CREATING A DATE OBJECT
DECISION MAKING AND
LOOPING
EVALUATIONS
You can analyze values inyour scripts to determine whether or note they match expected results.
DECISIONS
Using the results of evaluations, you can decide which path your script should go down.
LOOPS
There are also many occasions where you will want to perform the same set of steps repeatedly.
DECISION MAKING
EVALUATING CONDITIONS AND
CONDITIONAL STATEMENTS
COMPARISON OPERATORS:
EVALUATING CONDITIONS
STRUCTURING
COMPARISON OPERATORS
USING
COMPARISON OPERATORS
USING EXPRESSIONS WITH
COMPARISON OPERATORS
COMPARING TWO EXPRESSIONS
LOGICAL OPERATORS
USING LOGICAL AND
USING LOGICAL OR & NOT •var score1 = 8; → The score the user achieved
in Round 1.
•var score2 = 8; → The score the user achieved
in Round 2.
•var pass1 = 6; → The minimum score required
to pass Round 1. var pass2 = 6; → The
minimum score required to pass Round 2.
|| (Logical OR Operator) → Checks if at least
one of the conditions is true. score1 >= pass1
→ 8 >= 6 → true
score2 >= pass2 → 8 >= 6 → true
Since at least one condition is true, minPass =
true.
!minPass inverts the result: minPass is true, so !
minPass becomes false.
IF STATEMENTS
USING IF STATEMENTS
•The first assignment (=) sets msg to 'Congratulations!'.
•The second assignment (+=) appends ' Proceed to the
next round.' to the existing msg.
IF…ELSE STATEMENTS
USING IF…ELSE STATEMENTS
SWITCH STATEMENTS
USING SWITCH STATEMENTS
TYPE COERCION & WEAK TYPING
• JavaScript can convert data types behind the scenes to complete
an operation. This is known as type coercion.
For example, a string 'l ' could be converted to a number 1 in the
following expression:(' 1' > 0).
• As a result, the above expression would evaluate to true.
• JavaScript is said to use weak typing because the data type for a
value can change.
• Some other languages require that you specify what data type
each variable will be. They are said to use strong typing.
• Type coercion can lead to unexpected values in your code (and
also cause errors).
• Therefore, when checking if two values are equal, it is considered
• better to use strict equals operators ===and ! == rather than ==
and ! = as these strict operators check that the value and data
types match.
TRUTHY & FALSY VALUES
TRUTHY & FALSY VALUES
CHECKING EQUALITY & EXISTENCE
SHORT CIRCUIT VALUES
SHORT CIRCUIT VALUES
LOOPS
LOOPS
LOOP COUNTERS
KEY LOOP CONCEPTS
KEYWORDS You will commonly see these two keywords used with
loops: break This keyword causes the termination of the loop and tells
the interpreter to go onto the next statement of code outside of the
loop. (You may also see it used in functions.) continue This keyword
tells the interpreter to continue with the current iteration, and then
check the condition again. (If it is true, the code runs again.)
LOOPS & ARRAYS Loops are very helpful when dealing with arrays
if you want to run the same code for each item in the array. For
example, you might want to write the value of each item stored in an
array into the page. You may not know how many items will be in an
array when writing a script, but. when the code runs, it can check the
total number of items in a loop. That figure can then be used in the
counter to control how many times a set of statements is run. Once
the loop has run the right number of times, the loop stops.
KEY LOOP CONCEPTS
PERFORMANCE ISSUES
• It is important to remember that when a browser comes across
JavaScript, it will stop doing anything else until it has processed
that script.
• If your loop is dealing with only a small number of items, this will
not be an issue. If, however, your loop contains a lot of items, it
can make the page slower to load. If the condition never returns
fa1se, you get what is commonly referred to as an infinite loop.
• The code will not stop running until your browser runs out of
memory (breaking your script). Any variable you can define
outside of the loop and that does not change within the loop should
be defined outside of it.
• If it were declared inside the loop, it would be recalculated every
time the loop ran, needlessly using resources.
USING FOR LOOPS
USING WHILE LOOPS
USING DO WHILE LOOPS
EXAMPLE DECISIONS & LOOPS
EXAMPLE DECISIONS & LOOPS
EXAMPLE DECISIONS & LOOPS
EXAMPLE DECISIONS & LOOPS
SUMMARY:
DECISIONS & LOOPS
• Conditional statements allow your code to make decisions about
what to do next.
• Comparison operators (===, ! ==, ==, ! =, , <=, =>) are used to
compare two operands.
• Logical operators allow you to combine more than one set of
comparison operators.
• if ... else statements allow you to run one set of code if a condition
is true, and another if it is false.
• switch statements allow you to compare a value against possible
outcomes (and also provides a default option if none match).
• Data types can be coerced from one type to another.
• All values evaluate to either truthy or falsy.
• There are three types of loop: for, while, and do ... while. Each
repeats a set of statements.