JavaScript
JavaScript
JavaScript is the programming language of HTML and the
Web.
Programming makes computers do what you want them to do.
JavaScript is easy to learn.
This tutorial will teach you JavaScript from basic to
advanced.
Why Study JavaScript?
JavaScript is one of the 3 languages all web developers
must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behaviour of web pages
This lecture is about JavaScript, and how JavaScript
works with HTML and CSS.
JavaScript Introduction
JavaScript Can Change HTML Content
One of many HTML methods is getElementById().
This example uses the method to "find" an HTML element (with
id="demo"), and changes the element content (innerHTML) to
"Hello JavaScript”:
document.getElementById("demo").innerHTML = "Hello JavaScript”;
See JS.html
Example
<!DOCTYPE html>
<html>
<body>
<h1>What Can JavaScript Do?</h1>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button"
onclick="document.getElementById('demo').innerHTML = 'Hello
JavaScript!'">
Click Me!</button>
</body>
</html>
JavaScript Can Change HTML Attributes
This example changes an HTML image, by changing the src attribute of an <img> tag:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Can Change Images</h1>
<img id="myImage" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180">
<p>Click the light bulb to turn on/off the light.</p>
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif";
} else {
image.src = "pic_bulbon.gif";
}
}
</script>
</body>
</html>
See JSlight.html
JavaScript Can Change HTML Styles
(CSS)
<!DOCTYPE html>
<html>
<body>
<h1>What Can JavaScript Do?</h1>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<script>
function myFunction() {
var x = document.getElementById("demo");
x.style.fontSize = "25px";
x.style.color = "red";
}
</script>
<button type="button" onclick="myFunction()">Click Me!</button>
</body>
</html>
See JScss.html
JavaScript Can Validate Data
JavaScript is often used to validate input
Did You Know?
JavaScript and Java are completely different
languages, both in concept and design.
JavaScript was invented by Brendan Eich in 1995, and
became an ECMA standard in 1997.
ECMA-262 is the official name. ECMAScript 5
(JavaScript 1.8.5 - July 2010) is the current
standard
JavaScript Where To
JavaScript can be placed in the <body> and the
<head> sections of an HTML page.
The <script> Tag
In HTML, JavaScript code must be inserted between
<script> and </script> tag
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
JavaScript Functions and Events
A JavaScript function is a block of JavaScript code,
that can be executed when "asked" for.
For example, a function can be executed when an
event occurs, like when the user clicks a button.
You will learn much more about functions and events
in later chapters.
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.
Keeping all code in one place, is always a good
habit.
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>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
See JShead.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:
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
See JSbody.html
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 the <script> tag:
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
see JSetrnal.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 JavaScripts 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
JavaScript Output
JavaScript does not have any built-in print or display functions.
JavaScript Display Possibilities
JavaScript can "display" data in different ways:
1. Writing into an alert box, using window.alert().
2. Writing into the HTML output using document.write().
3. Writing into an HTML element, using innerHTML.
4. Writing into the browser console, using console.log().
Using window.alert()
You can use an alert box to display:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
See windowalert.html
Using document.write()
For testing purposes, it is convenient to use document.write():
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
See document.write.html
Using document.write()
Using document.write() after an HTML document is fully loaded, will
delete all existing HTML:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button onclick="document.write(5 + 6)">Try it</button>
</body>
</html>
See document.writedelet.html
The document.write() method should be used only for
testing.
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:
<!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>
See innerHTML.html
Using console.log()
In your browser, you can use the console.log() method to display data.
Activate the browser console with F12, and select "Console" in the menu.
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
console.log(5 + 6);
</script>
</body>
</html>
See console.log.html
JavaScript Syntax
JavaScript syntax is the set of rules, how JavaScript
programs are constructed.
JavaScript Programs
A computer program is a list of "instructions" to be
"executed" by the computer.
In a programming language, these program instructions are
called statements.
JavaScript is a programming language.
JavaScript statements are separated by semicolon.
Example
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Statements</h1>
<p>Statements are separated by semicolons.</p>
<p>The variables x, y, and z are assigned the values 5, 6, and 11:</p>
<p id="demo"></p>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>
</body>
</html>
In HTML, JavaScript programs can be executed by the web browser.
See JavaScriptStatements.html
JavaScript Statements
JavaScript statements are composed of:
• Values.
• Operators.
• Expressions.
• Keywords.
• Comments.
1-JavaScript Values
The JavaScript syntax defines two types of values:
Fixed values and variable values.
1.1-Fixed values are called literals.
2.1-Variable values are called variables.
1.1-JavaScript Literals
The most important rules for writing fixed values are:
Numbers are written with or without decimals:
10.50
1001
See JavaScript Numbers.html
Strings are text, written within double or single quotes:
"John Doe"
'John Doe’
See JavaScript Strings.html
Expressions can also represent fixed values:
5+6
5 * 10
See JavaScript Expressions.html
1.2-JavaScript Variables
In a programming language, variables are used to store data
values.
JavaScript uses the var keyword to define 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;
See JavaScript Variables.html
2-JavaScript Operators
JavaScript uses an assignment operator ( = ) to assign values to
variables:
var x = 5;
var y = 6;
See Assigning Values.html
JavaScript uses arithmetic operators ( + - * / ) to compute values:
(5 + 6) * 10
See JavaScript Operators.html
3-JavaScript Keywords
JavaScript keywords are used to identify actions to be
performed.
The var keyword tells the browser to create a new variable:
var x = 5 + 6;
var y = x * 10;
See Keyword Creates a Variable.html
4-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
See Comments.html
JavaScript is Case Sensitive
All JavaScript identifiers are case sensitive.
The variables lastName and lastname, are two different
variables.
lastName = "Doe";
lastname = “Peterson";
See Case Sensitive.html
JavaScript does not interpret VAR or Var as the keyword var.
JavaScript and Camel Case
Historically, programmers have used three ways of
joining multiple words into one variable name:
Hyphens:
first-name, last-name, master-card, inter-city.
Underscore:
first_name, last_name, master_card, inter_city.
Camel Case:
FirstName, LastName, MasterCard, InterCity.
Hyphens are not allowed in JavaScript. It is reserved for subtractions.
JavaScript Character Set
JavaScript uses the Unicode character set.
Unicode covers (almost) all the characters,
punctuations, and symbols in the world.
Complete Unicode Reference.
Lorem Ipsum Dolor
JavaScript
Statements
JavaScript Statements
In HTML, JavaScript statements are "instructions" to
be "executed" by the web browser.
This statement tells the browser to write "Hello
Dolly." inside an HTML element with id="demo":
Example
document.getElementById("demo").innerHTML = "Hello
Dolly.”;
see hello.html
JavaScript Programs
Most JavaScript programs contain many JavaScript statements.
The statements are executed, one by one, in the same order as they are
written.
In this example, x, y, and z is given values, and finally z is displayed:
Example:
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;
JavaScript programs (and JavaScript statements) are often called JavaScript
code.
See pro.html
Semicolons ;
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:
a = 5;
b = 6;
c = a + b;
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.
See semi.html
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:
document.getElementById("demo").innerHTML =
"Hello Dolly.”;
See line.html
JavaScript Code Blocks
JavaScript statements can be grouped together in code blocks, inside
curly brackets {...}.
The purpose of code blocks this is to define statements to be executed
together.
One place you will find statements grouped together in blocks, are in
JavaScript functions:
function myFunction() {
document.getElementById("demo").innerHTML = "Hello Dolly.";
document.getElementById("myDIV").innerHTML = "How are you?";
see block.html
JavaScript Keywords
JavaScript statements often start with a keyword to
identify the JavaScript action to be performed.
Here is a list of some of the keywords you will
learn about in this lecture:
JavaScript keywords are reserved words. Reserved words cannot be used as names for variables.
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 a line, will be ignored by JavaScript (will not be
executed).
This example uses a single line comment before each line, to explain the code:
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.”;
see single1.html
This example uses a single line comment at the end of each line, to explain the
code:
var x = 5; // Declare x, give it the value of 5
var y = x + 2; // Declare y, give it the value of x + 2
see single2.html
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:
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.”;
See multi.html
It is most common to use single line comments.
Block comments are often used for formal documentation.
Using Comments to Prevent Execution
Using comments to prevent execution of code, are 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:
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.”;
See pre1.html
This example uses a comment block to prevent execution of multiple lines:
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/
See pre2.html
JavaScript Variables
JavaScript variables are containers for storing data values.
In this example, x, y, and z, are variables:
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
See var1.html
Much Like Algebra
In this example, price1, price2, and total, are variables:
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
See var2.html
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 quotes around a number, it will be treated as a text string.
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!’;
See jsdata.html
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 is empty (it has no value).
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":
<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.
See vardec.html
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;
See many1.html
A declaration can span multiple lines:
var person = "John Doe",
carName = "Volvo",
price = 200;
See many2.html
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;
See value.html
Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable, it will not lose its
value.
The variable carName will still have the value "Volvo"
after the execution of these statements:
Example
var carName = "Volvo";
var carName;
See redec.html
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using
operators like = and +:
var x = 5 + 2 + 3;
See arth1.html
You can also add strings, but strings will be concatenated (added end-to-
end):
var x = "John" + " " + “Doe”;
See arth2.html
Also try this:
var x = “5” + 2 + 3;
See arth3.html
If you add a number to a string, the number will be treated as string, and
concatenated.