JavaScript
Introduction
JavaScript
JavaScript is a programming language that adds interactivity to your website
Example
Add HTML
Add CSS
JavaScript
JavaScript is a programming language that adds interactivity to your website
Example
Add JavaScript to Implement Dynamic Behavior
JavaScript
A very common use of JavaScript is to dynamically modify HTML and CSS to update a
user interface, via the Document Object Model API
Note that the code in your web documents is generally loaded and executed in the order
it appears on the page.
Errors may occur if JavaScript is loaded and run before the HTML and CSS that it is
intended to modify.
JavaScript
When the browser encounters a block of JavaScript, it generally runs it in order, from top
to bottom.
Here we are selecting a text paragraph (line 1), then attaching an event
listener to it (line 3) so that when the paragraph is clicked, the
updateName() code block (lines 5–8) is run.
JavaScript
JavaScript is a lightweight interpreted programming language.
In interpreted languages, the code is run from top to bottom and the result of running
the code is immediately returned. You don't have to transform the code into a different
form before the browser runs it.
Compiled languages on the other hand are transformed (compiled) into another form
before they are run by the computer. For example, C/C++ are compiled into machine
code that is then run by the computer.
The program is executed from a binary format, which was generated from the original
program source code.
What can JavaScript Do?
JavaScript
1. Change HTML Content
The example below "finds" an HTML element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript":.
document.getElementById("demo").innerHTML
document.getElementById("demo").innerHTML == "Hello
"Hello JavaScript";
JavaScript";
JavaScript accepts both double and single
quotes:
JavaScript
2. JavaScript Can Change HTML Attribute Values
In this example JavaScript changes the value of the src (source) attribute of an <img>
tag:
JavaScript
3. JavaScript Can Change HTML Styles (CSS)
Changing the style of an HTML element, is a variant of changing an HTML attribute:
document.getElementById("demo").style.fontSize
document.getElementById("demo").style.fontSize == "35px";
"35px";
JavaScript
4. JavaScript Can Hide HTML Elements
Hiding HTML elements can be done by changing the display style:
document.getElementById("demo").style.display
document.getElementById("demo").style.display == "none";
"none";
JavaScript
5. JavaScript Can Show HTML Elements
Showing hidden HTML elements can also be done by changing the display style:
document.getElementById("demo").style.display
document.getElementById("demo").style.display == "block";
"block";
Where is JavaScript Placed?
JavaScript
1. Internal JavaScript
Head Section
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or
<!DOCTYPE
in both.
<!DOCTYPE html>
html>
<html>
<html>
<head>
<head>
<script>
<script>
function
function myFunction()
myFunction() {{
document.getElementById("demo").innerHTML
document.getElementById("demo").innerHTML == "Paragraph
"Paragraph
changed.";
changed.";
}}
</script>
</script>
</head>
</head>
</html>
</html>
JavaScript
Internal JavaScript
Body Section
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or
<!DOCTYPE
in both.
<!DOCTYPE html>
html>
<html>
<html>
<body>
<body>
<h1>A
<h1>A Web
Web Page</h1>
Page</h1>
<p
<p id="demo">A
id="demo">A Paragraph</p>
Paragraph</p>
<button
<button type="button"
type="button" onclick="myFunction()">Try
onclick="myFunction()">Try
it</button>
it</button>
</body>
</body>
</html
</html>>
JavaScript
External JavaScript
Scripts can also be placed in external files
External scripts are practical when the same code is used in many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute of a
<script> tag::
<script
<script src="myScript.js"></script>
src="myScript.js"></script>
JavaScript
External JavaScript
Scripts can also be placed in external files:
You can place an external script reference in <head> or <body> as
you like.
The script will behave as if it was located exactly where the
JavaScript
External JavaScript
Placing scripts in external files has some advantages:
It separates HTML and code
It makes HTML and JavaScript easier to read and maintain
Cached JavaScript files can speed up page loads
To add several script files to one page - use several script tags:
JavaScript
External References
An external script can be referenced in 3 different ways:
• With a full URL (a full web address)
• With a file path (like /js/)
• Without any path
This example uses a full URL to link to myScript.js:
Activity
Activity
Go to your test site and create a new folder named scripts. Within the scripts folder,
create a new file called main.js, and save it.
In your index.html file, enter this code on a new line, just before the closing </body> tag
Activity
Add this code to the main.js file
Make sure the HTML and JavaScript files are saved. Then load index.html in your
browser.
Activity
Example 2
In HTML, JavaScript code is inserted between <script> and </script> tags.
<script>
<script>
document.getElementById("demo").innerHTML
document.getElementById("demo").innerHTML == "My
"My First
First
JavaScript";
JavaScript";
</script>
</script>
JavaScript Output
JavaScript
JavaScript Display Possibilities
JavaScript can "display" data in different ways:
Writing into an HTML element, using innerHTML.
Writing into the HTML output using document.write().
Writing into an alert box, using window.alert().
Writing into the browser console, using console.log().
JavaScript
1. Using innerHTML
To access an HTML element, JavaScript can use the
document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the
HTML content:
JavaScript
2. Using document.write()
For testing purposes, it is convenient to use document.write():
JavaScript
2. Using document.write()
For testing purposes, it is convenient to use document.write():
Using document.write() after an HTML document is loaded, will delete all existing HTML:
JavaScript
3. Using window.alert()
You can use an alert box to display data:
JavaScript
4. Using Console.log()
For debugging purposes, you can call the console.log() method in the browser to
display data.
JavaScript
5. Using window.print()
JavaScript does not have any print object or print methods.
You cannot access output devices from JavaScript.
The only exception is that you can call the window.print() method in the browser
to print the content of the current window.
JavaScript Statements
JavaScript
JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
This statement tells the browser to write "Hello Dolly." inside an HTML element
with id="demo":
JavaScript
JavaScript Key Words
JavaScript statements are composed of:
JavaScript
JavaScript Variables
In a programming language, variables are used to store data values.
JavaScript uses the keywords var, let and const to declare variables.
An equal sign is used to assign values to variables.
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables#an_aside_on_variable_naming_rules
JavaScript
JavaScript Variables
Numbers
Strings
JavaScript
JavaScript Variables
Booleans
JavaScript
JavaScript Variables
let
JavaScript variables
Declaring a variable
Var score
Assigning a value to a variable
Var score = 0
JavaScript variables
Reassigning a variable
JavaScript variables
Const
You can use const keyword to declare variable in JavaScript
Eg The example below uses const to declare a variable
On the console window, the value of score will be displayed as follows
JavaScript variables
Const
The value assigned to const does not change eg : if you try changing the value of const as per the
example below, you will get an error
You cannot reassign a value to const
You cannot redeclare a const
JavaScript variables
Strings
You can use either a single quote or a double quote
If you have multiple lines add a backslash to show continuation
JavaScript variables
Transform and manipulate a string
JavaScript treats string as objects that have properties and methods behind the scene
The output on the console will show the length of the string
The property (ie length) of the object (passphrase) is accessed using a dot (.)
JavaScript variables
Transform and manipulate a string
A method is an action you can perform with the object
JavaScript provides methods for strings eg
Example:
The parenthesis indicates that you are working with a method
JavaScript variables
Transform and manipulate a string
Using methods such as toLowerCase() does not change the variable
Output
The parenthesis indicates that you are working with a method
JavaScript variables
Capture Input
Prompt()
A way to collect information from a site user
Output
JavaScript variables
Capture Input
Prompt()
A way to collect information from a site user
Output
JavaScript variables
Combine Strings
Concatenation of strings
A way to combine strings
JavaScript variables
Combine Strings
Template Literals
Template literals are literals delimited with backtick characters, allowing for multi-line strings and
string interpolation with embedded expressions
String interpolation : To create strings by doing substitution of placeholders
JavaScript variables
Combine Strings
Template Literals
Replacement of concatenation
String interpolation : To create strings by doing substitution of placeholders
JavaScript variables
Combine Strings
Combining everything so far
JavaScript variables
Display the Value of a String on a Page
Example HTML page
Example JS page
JavaScript variables
Display the Value of a String on a Page
Example using query selector to display string on a page
The Output
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
JavaScript variables
Find more string properties and methods
Strings
https://developer.mozilla.org/en-US/docs/Web/JavaScript
JavaScript Conditionals
JavaScript Conditionals
Display the Value of a String on a Page
If else
Replacement of concatenation
JavaScript Conditionals
Boolean
Boolean Values
a Boolean is a logical data type that can have only the values true or false
JavaScript Conditionals
Unary Plus
Unary Plus
The unary plus (+) operator precedes its operand and evaluates to its operand but attempts to
convert it into a number, if it isn't already.
JavaScript Conditionals
Conditional Statements
Example
Final code:
JavaScript Conditionals
Conditional Statements
Example if else
Final code:
JavaScript Conditionals
Display the Value of a String on a Page
If else
Replacement of concatenation
JavaScript Arrays
JavaScript
Array
An array is a single object that contains multiple values enclosed in square brackets and
separated by commas
In an array we can store various data types
JavaScript
Accessing Array
Once these arrays are defined, you can access each value by their location within the
array.
JavaScript
Length of Array
You can find out the length of an array (how many items are in it) using the length
property
JavaScript
Associative Array
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
In JavaScript, objects use named indexes.
JavaScript Functions
JavaScript Functions
Function
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
JavaScript Functions
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code
after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the
"caller":
JavaScript Functions
Why Functions?
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different
results.
JavaScript Functions
Why Functions?
Accessing a function without () will return the function object instead of the function
result.
JavaScript Functions
Why Functions?
Functions can be used as variable values
JavaScript Objects
JavaScript
Objects
Creating
To retrieve the information stored in the object, you can use the following syntax:
JavaScript
Objects
Creating
JavaScript
Accessing Objects
1. Dot Notation
Accessing Objects using the dot notation
JavaScript
Sub-Name Space
It is even possible to make the value of an object member another object. For example,
try changing the name member from
JavaScript
Sub-Name Space
To access these items you just need to chain the extra step onto the end with another
dot.
JavaScript
2. Bracket Notation
Accessing objects using the bracket notation
JavaScript
Objects
Creating a method in an object
JavaScript
This keyword
In a function definition, this refers to the "owner" of the function.
The this keyword refers to the current object the code is being written inside
In the example above, this is the person object that "owns" the fullName function.
In other words, this.firstName means the firstName property of this object.
JavaScript
This keyword
In a function definition, this refers to the "owner" of the function.
Questions?