Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
118 views

JavaScript Is The Programming Language of HTML and The Web

1. JavaScript code must be inserted between <script> and </script> tags in HTML. Scripts can be placed in the <head>, <body>, or both sections. 2. External JavaScript files have the .js extension and are referenced using a <script> tag's src attribute for reuse across web pages. 3. JavaScript displays data by writing to HTML elements using innerHTML, document.write(), alerts, or the browser console. Semicolons separate statements for readability.

Uploaded by

Gerald Guarino
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
118 views

JavaScript Is The Programming Language of HTML and The Web

1. JavaScript code must be inserted between <script> and </script> tags in HTML. Scripts can be placed in the <head>, <body>, or both sections. 2. External JavaScript files have the .js extension and are referenced using a <script> tag's src attribute for reuse across web pages. 3. JavaScript displays data by writing to HTML elements using innerHTML, document.write(), alerts, or the browser console. Semicolons separate statements for readability.

Uploaded by

Gerald Guarino
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

JavaScript is the programming

language of HTML and the Web.


JavaScript Where To

The <script> Tag


In HTML, JavaScript code must be
inserted between <script> and
</script> tags.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerH
TML = "My First JavaScript";
</script>
</body>
</html>
JavaScript in <head> or
<body>
You can place any number of
scripts in an HTML document.
Scripts can be placed in the
<body>, or in the <head> section
of an HTML page, or in both.

JavaScript in <head>
In this example, a JavaScript
function is placed in the <head>
section of an HTML page.
The function is invoked (called)
when a button is clicked:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
   
document.getElementById("demo")
.innerHTML = "Paragraph
changed.";
}
</script>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="
myFunction()">Try it</button>
</body>
</html>

JavaScript in <body>
In this example, a JavaScript
function is placed in the <body>
section of an HTML page.
The function is invoked (called)
when a button is clicked:

Example
<!DOCTYPE html>
<html>
<body> 

<h1>A Web Page</h1>


<p id="demo">A Paragraph</p>
<button type="button" onclick="m
yFunction()">Try it</button>

<script>
function myFunction() {
   document.getElementById("demo
").innerHTML = "Paragraph
changed.";
}
</script>

</body>
</html>

External JavaScript
Scripts can also be placed in
external files:
External file: myScript.js
function myFunction() {
   document.getElementById("demo
").innerHTML = "Paragraph
changed.";
}
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:
Example
<!DOCTYPE html>
<html>
<body>

<h2>External JavaScript</h2>

<p id="demo">A Paragraph.</p>

<button type="button"
onclick="myFunction()">Try it</button>

<p>(myFunction is stored in an external file


called "myScript.js")</p>

<script src="myScript.js"></script>
</body>
</html>

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
<script> tag is located.
External scripts cannot contain
<script> tags.

External JavaScript
Advantages
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:

Example
<script src="myScript1.js"></scr
ipt>
<script src="myScript2.js"></scr
ipt>

This example links to a script


located in the same folder as the
current page:
Example
<script src="myScript1.js"></scr
ipt>

JavaScript Output
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().

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:

Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").
innerHTML = 5 + 6;
</script>
</body>
</html>
Changing the innerHTML property
of an HTML element is a common
way to display data in HTML.

Using document.write()
For testing purposes, it is
convenient to
use document.write():
Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>
Using document.write() after an
HTML document is loaded,
will delete all existing HTML:
Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<button type="button" onclick="d
ocument.write(5 + 6)">Try
it</button>

</body>
</html>
The document.write() method
should only be used for testing.
Using window.alert()
You can use an alert box to
display data:

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>
</body>
</html>

Using console.log()
For debugging purposes, you can
use the console.log() method to
display data.
You will learn more about
debugging in a later chapter.

Example
<!DOCTYPE html>
<html>
<body>

<script>
console.log(5 + 6);
</script>
</body>
</html>

JavaScript Statements
Example
var x, y, z;    // Statement 1
x = 5;          // Statement 2
y = 6;          // Statement 3
z = x + y;      // Statement 4

JavaScript Programs
A computer program is a list of
"instructions" to be "executed" by
a computer.
In a programming language, these
programming instructions are
called statements.
A JavaScript program is a list of
programming statements.
In HTML, JavaScript programs are
executed by the web browser.

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":

Example
document.getElementById("demo").
innerHTML = "Hello Dolly.";
Try it Yourself »
Most JavaScript programs contain
many JavaScript statements.
The statements are executed, one
by one, in the same order as they
are written.
JavaScript programs (and
JavaScript statements) are often
called JavaScript code.
Semicolons ;
Semicolons separate JavaScript
statements.
Add a semicolon at the end of
each executable statement:
var a, b, c;     // Declare 3
variables
a = 5;           // Assign the
value 5 to a
b = 6;           // Assign the
value 6 to b
c = a + b;       // Assign the
sum of a and b to c
When separated by semicolons,
multiple statements on one line
are allowed:
a = 5; b = 6; c = a + b;
On the web, you might see
examples without semicolons. 
Ending statements with semicolon
is not required, but highly
recommended.

JavaScript White Space


JavaScript ignores multiple
spaces. You can add white space
to your script to make it more
readable.
The following lines are equivalent:
var person = "Hege";
var person="Hege";
A good practice is to put spaces
around operators ( = + - * / ):
var x = y + z;

JavaScript Line Length and


Line Breaks
For best readability, programmers
often like to avoid code lines
longer than 80 characters.
If a JavaScript statement does not
fit on one line, the best place to
break it is after an operator:
Example
document.getElementById("demo").
innerHTML =
"Hello Dolly!";

JavaScript Code Blocks


JavaScript statements can be
grouped together in code blocks,
inside curly brackets {...}.
The purpose of code blocks is to
define statements to be executed
together.
One place you will find statements
grouped together in blocks, is in
JavaScript functions:
Example
function myFunction() {
   
document.getElementById("demo1")
.innerHTML = "Hello Dolly!";
   
document.getElementById("demo2")
.innerHTML = "How are you?";
}

JavaScript Syntax
JavaScript syntax is the set
of rules, how JavaScript programs
are constructed:
var x, y ,z;  // How to declare
variables
x = 5; y = 6;      // How to
assign values
z = x + y;         // How to
compute values

JavaScript Values
The JavaScript syntax defines two
types of values: Fixed values and
variable values.
Fixed values are called literals.
Variable values are
called variables.

JavaScript Literals
The most important rules for
writing fixed values are:
Numbers are written with or
without decimals:
10.50

1001
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Numbers</h2>
<p>Number can be written with or without
decimals.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerH
TML = 10.50;
</script>
</body>
</html>

Strings are text, written within


double or single quotes:
"John Doe"

'John Doe'
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>Strings can be written with double or


single quotes.</p>
<p id="demo"></p>

<script>
document.getElementById("demo").innerH
TML = 'John Doe';
</script>

</body>
</html>

JavaScript Variables
In a programming
language, variables are used
to store data values.
JavaScript uses the var keyword
to declare variables.
An equal sign is used to assign
values to variables.
In this example, x is defined as a
variable. Then, x is assigned
(given) the value 6:
var x;

x = 6;
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p>In this example, x is defined as a


variable.
Then, x is assigned the value of 6:</p>
<p id="demo"></p>

<script>
var x;
x = 6;
document.getElementById("demo").innerH
TML = x;
</script>

</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Variables</h2>
<p>In this example, x is defined as a
variable.
Then, x is assigned the value of 6:</p>
<p id="demo"></p>
<h1 id="sample"></h1>

<script>
var x;
x = 6;
y = 7;
z = 10;
result = y + z;

document.getElementById("demo").innerH
TML = x;
document.getElementById("sample").inner
HTML = z;
document.write(result);
</script>
</body>
</html>

JavaScript Operators
JavaScript uses arithmetic
operators ( + - *  / )
to compute values:
(5 + 6) * 10
JavaScript uses an assignment
operator ( = ) to assign values
to variables:
var x, y;
x = 5;
y = 6;

JavaScript Expressions
An expression is a combination of
values, variables, and operators,
which computes to a value.
The computation is called an
evaluation.
For example, 5 * 10 evaluates to
50:
5 * 10
Expressions can also contain
variable values:
x * 10
The values can be of various
types, such as numbers and
strings.
For example, "John" + " " +
"Doe", evaluates to "John Doe":
"John" + " " + "Doe"

JavaScript Keywords
JavaScript keywords are used to
identify actions to be performed.
The var keyword tells the browser
to create variables:
var x, y;
x = 5 + 6;
y = x * 10;

JavaScript Comments
Not all JavaScript statements are
"executed".
Code after double slashes // or
between /* and */ is treated as
a comment.
Comments are ignored, and will
not be executed:
var x = 5; // I will be executed

// var x = 6;   I will NOT be


executed

JavaScript Identifiers
Identifiers are names.
In JavaScript, identifiers are used
to name variables (and keywords,
and functions, and labels).
The rules for legal names are
much the same in most
programming languages.
In JavaScript, the first character
must be a letter, or an underscore
(_), or a dollar sign ($).
Subsequent characters may be
letters, digits, underscores, or
dollar signs.
Numbers are not allowed as the
first character.
This way JavaScript can easily
distinguish identifiers from
numbers.
Example:
_asg
$shsi
Shshs1123
Shshs_1234

JavaScript is Case Sensitive


All JavaScript identifiers are case
sensitive. 
The
variables lastName and lastnam
e, are two different variables.
var lastname, lastName;
lastName = "Doe";
lastname = "Peterson";
JavaScript does not
interpret VAR or Var as the
keyword var.
JavaScript and Camel Case
Historically, programmers have
used different ways of joining
multiple words into one variable
name:
Hyphens:
first-name, last-name, master-
card, inter-city.
Hyphens are not allowed in
JavaScript. They are reserved for
subtractions.
Underscore:
first_name, last_name,
master_card, inter_city.
Upper Camel Case (Pascal
Case):
FirstName, LastName, MasterCard,
InterCity.

Lower Camel Case:


JavaScript programmers tend to
use camel case that starts with a
lowercase letter:
firstName, lastName, masterCard,
interCity.
JavaScript Comments
JavaScript comments can be used
to explain JavaScript code, and to
make it more readable.
JavaScript comments can also be
used to prevent execution, when
testing alternative code.

Single Line Comments


Single line comments start with //.
Any text between // and the end
of the line will be ignored by
JavaScript (will not be executed).
This example uses a single-line
comment before each code line:
Example
// Change heading:
document.getElementById("myH").i
nnerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").i
nnerHTML = "My first
paragraph.";
This example uses a single line
comment at the end of each line
to explain the code:

Example
var x = 5;      // Declare x,
give it the value of 5
var y = x + 2;  // Declare y,
give it the value of x + 2
Multi-line Comments
Multi-line comments start with /*
and end with */.
Any text between /* and */ will be
ignored by JavaScript.
This example uses a multi-line
comment (a comment block) to
explain the code:

Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id =
"myP"
in my web page:
*/
document.getElementById("myH").i
nnerHTML = "My First Page";
document.getElementById("myP").i
nnerHTML = "My first
paragraph.";

Using Comments to Prevent


Execution
Using comments to prevent
execution of code is suitable for
code testing.
Adding // in front of a code line
changes the code lines from an
executable line to a comment.
This example uses // to prevent
execution of one of the code lines:
Example
//document.getElementById("myH")
.innerHTML = "My First Page";
document.getElementById("myP").i
nnerHTML = "My first
paragraph.";
This example uses a comment
block to prevent execution of
multiple lines:

Example
/*
document.getElementById("myH").i
nnerHTML = "My First Page";
document.getElementById("myP").i
nnerHTML = "My first
paragraph.";
*/
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comments</h2>

<h1 id="myH"></h1>

<p id="myP"></p>

<script>
/*
document.getElementById("myH").innerHT
ML = "Welcome to my Homepage";
document.getElementById("myP").innerHT
ML = "This is my first paragraph.";
*/
document.getElementById("myP").innerHT
ML = "The comment-block is not
executed.";
</script>

</body>
</html>

JavaScript Variables
JavaScript variables are containers
for storing data values.
In this example, x, y, and z, are
variables:

Example
var x = 5;
var y = 6;
var z = x + y;
From the example above, you can
expect:
 x stores the value 5
 y stores the value 6
 z stores the value 11

Much Like Algebra


In this example, price1, price2,
and total, are variables:
Example
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
In programming, just like in
algebra, we use variables (like
price1) to hold values.
In programming, just like in
algebra, we use variables in
expressions (total = price1 +
price2).
From the example above, you can
calculate the total to be 11.
JavaScript variables are containers
for storing data values.

JavaScript Identifiers
All JavaScript variables must
be identified with unique
names.
These unique names are
called identifiers.
Identifiers can be short names
(like x and y) or more descriptive
names (age, sum, totalVolume).
The general rules for constructing
names for variables (unique
identifiers) are:
 Names can contain letters,
digits, underscores, and dollar
signs.
 Names must begin with a letter
 Names can also begin with $
and _ (but we will not use it in
this tutorial)
 Names are case sensitive (y
and Y are different variables)
 Reserved words (like JavaScript
keywords) cannot be used as
names
JavaScript identifiers are case-
sensitive.

The Assignment Operator


In JavaScript, the equal sign (=) is
an "assignment" operator, not an
"equal to" operator.
This is different from algebra. The
following does not make sense in
algebra:
x = x + 5
In JavaScript, however, it makes
perfect sense: it assigns the value
of x + 5 to x.
(It calculates the value of x + 5
and puts the result into x. The
value of x is incremented by 5.)
The "equal to" operator is written
like == in JavaScript.

JavaScript Data Types


JavaScript variables can hold
numbers like 100 and text values
like "John Doe".
In programming, text values are
called text strings.
JavaScript can handle many types
of data, but for now, just think of
numbers and strings.
Strings are written inside double
or single quotes. Numbers are
written without quotes.
If you put a number in quotes, it
will be treated as a text string.

Example
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';

Declaring (Creating)
JavaScript Variables
Creating a variable in JavaScript is
called "declaring" a variable.
You declare a JavaScript variable
with the var keyword:
var carName;
After the declaration, the variable
has no value. (Technically it has
the value of undefined)
To assign a value to the variable,
use the equal sign:
carName = "Volvo";
You can also assign a value to the
variable when you declare it:
var carName = "Volvo";
In the example below, we create a
variable called carName and
assign the value "Volvo" to it.
Then we "output" the value inside
an HTML paragraph with
id="demo":

Example
<p id="demo"></p>

<script>
var carName = "Volvo";
document.getElementById("demo").
innerHTML = carName; 
</script>
It's a good programming practice
to declare all variables at the
beginning of a script.
One Statement, Many
Variables
You can declare many variables in
one statement.
Start the statement with var and
separate the variables by comma:
var person = "John Doe", carName
= "Volvo", price = 200;
A declaration can span multiple
lines:
var person = "John Doe",
carName = "Volvo",
price = 200;

Value = undefined
In computer programs, variables
are often declared without a value.
The value can be something that
has to be calculated, or something
that will be provided later, like
user input.
A variable declared without a
value will have the
value undefined.
The variable carName will have
the value undefined after the
execution of this statement:

Example
var carName;
You can also add strings, but
strings will be concatenated:
Example
var x = "John" + " " + "Doe";

You might also like