JavaScript Basics for Web Development
JavaScript Basics for Web Development
JavaScript
What is JavaScript?
• Javascript is a programming language (no relation to Java, it is named just for
marketing reason 😀)
What is JavaScript?
History:
• Originally developed by Brendan Eich at Netscape (named
LiveScript at that time)
• Became a joint venture of Netscape and Sun in 1995 (renamed
JavaScript)
• Now standardized by the ECMA (ECMA-262, also ISO 16262)
What is JavaScript?
ECMAScript (ES): a standard for scripting languages
JavaScript: a programming language based on ECMAScript (the most
popular implementation of ES)
Why JavaScript?
+ produces
Basic Features of JS
An interpreter language (no compilation by developers, it is compiled and executed
on-the-fly by browser)
Supports the OOP approach (but lack of some basic features of OOP such as
polymorphism)
Internal JS Code
JS code can be embedded directly in an HTML page using <script> tag:
<script>
... JavaScript code ...
</script>
vNote: Placing scripts at the bottom of the <body> element improves the
display speed, because script compilation slows down the display
External JS Code
JS script (code) can also be placed in external files and linked to HTML
pages
JS script files have the extension .js
To link a JS script, use the <script> tag with the src attribute:
<script src="<script ULR>"></script>
External JS script advantages:
• Separate JS code and HTML code (easy to read and maintain)
• JS code can be reused/shared in HTML pages
• Cached JS files can speed-up page load, and much more…
Recommended!
ĐẠI HỌC CẦN THƠ
CTU
12 [Link] 12
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Using JS in HTML Documents
External JS Code
External scripts can be referenced with a full URL (placed in other sites or the
same site) or with a relative path (placed in the same site)
Example:
<script src="scripts/[Link]"></script>
<script src="[Link]
vNotes:
• External JS scripts cannot contain <script> tags
• The <script> tag can be placed anywhere in the HTML page
• An HTML page can use multiple script files: use multiple <script>
tags to link to multiple script files
ĐẠI HỌC CẦN THƠ
CTU
13 [Link] 13
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Using JS in HTML Documents
JS script execution:
There is no main function as other programming languages
⇒ The script code is executed from the top to the bottom
JS functions in the script file are only executed when called
Output of JS
JS can display data in different ways:
• Writing into an HTML element, using innerHTML property
• Writing into HTML page, using [Link]()
(Note: Using [Link]() after an HTML document is loaded,
will delete all existing HTML)
• Writing into an alert box, using [Link]()
• Output to browser console, using [Link]()
(usually used for debugging purpose)
Output of JS
Writing to an HTML element:
<!DOCTYPE html>
<html>
<body>
<h1>Today is: <span id="curdate"></span></h1>
<p>5 + 6 = <span id="calc"></span></p>
<script>
var d = (new Date()).toString().substring(0, 15);
[Link]("curdate").innerHTML = d;
[Link]("calc").innerHTML = 5 + 6;
</script>
</body>
</html>
Output of JS
Writing into an alert box:
<!DOCTYPE html>
<html>
<body>
<h2>JS Output</h2>
<button onclick="alert('Hello!')">Click me to say Hello</button>
</body>
</html>
Output of JS
Output to browser console:
<!DOCTYPE html>
<html>
<body>
<h2>JS to console</h2>
<script>
[Link]('Hello, world!');
</script>
</body>
</html>
Output of JS
Output to browser console (cont.):
for
debugging
1. Right click
3. Choose Console
2. Click
Inspect
Statements
• Script/Program = { set of instructions/statements}
• A statement is composed of: values (constant/literals or variable), operators,
expressions, keywords, and comments
• A statement ends with a semicolon ;
• Multiple while-space are ignored (so we can add as much as white-space for
readability)
• A statement can be broken into multiple lines
• A set of statements can be grouped in code block, using {…}
Comments
For code readability and maintenance
Will be ignored by JS (doesn’t interpret and execute)
Single line comments:
• Start with //
• … to the end of line
Multiline comments:
• Start with /*
• End with */
Good practice to use comments as much as possible
Variables
Variables
Declaring a variable without assigning value: the variable will have the
value undefined
var age; // ⇒ age = undefined
Re-declaring a variable doesn’t erase its value
var myAge = 40;
var myAge; // ⇒ age still = 40
Get the datatype of a variable: use the typeof operator
Example: typeof myAge returns a string “number”
We can declare multiple variables in one statement (using comma to
separate variable names)
Variables
Hoisting is moving all declarations to the top of the current scope
When to Use var, let, or const?
1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed (Arrays and Objects)
4. Only use let if you cannot use const
5. Never use var if you can use let or const.
Operators
Assignment
Arithmetic
ĐẠI HỌC CẦN THƠ
CTU
26 [Link] 26
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics
Operators
Logical
String
Datatypes
JS variables don’t have types, but the values do
Primitive datatypes:
• Boolean: true or false
• Number: everything is double (no integers)
• String: in 'single' or "double" quotes
• Null: null, a value meaning “this has no value” (null is an object)
• Undefined: undefined, i.e. “not assigned”
Object types:
• Array, Date, Object, ...
null == undefined: true
null === undefined: false
ĐẠI HỌC CẦN THƠ
CTU
28 [Link] 28
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics
Number
All numbers in JS are real numbers, no integer
Operators are like C/C++ or Java
Precedence like C/C++ or Java
Some special values:
NaN == NaN: false
NaN (not-a-number) NaN != NaN: true
+Infinity
-Infinity
There is a Math class, which provide basic math functions (such as
[Link](), [Link](), etc.)
String
Object type
Can be defined with single quote (preferred) or double quote
Immutable
No char type: letters are strings with length 1
Methods: charAt, charCodeAt, fromCharCode, indexOf, lastIndexOf,
replace, split, substring, toLowerCase, toUpperCase
Property: length
The only operator: +
Boolean
Literal values: true and false
Operators: &&, || and !
Non-boolean values can be used as a boolean value with the following
type coercion (implicitly conversion):
null, undefined, 0, NaN, '', and "" are evaluated to false
Everything else is evaluated to true
We can also explicitly convert an arbitrary value to boolean using the
Boolean() constructor or !! operator
Boolean
let complete = true;
let age = 40;
let old = age > 60; //false
let boolValue = Boolean("to ambiguous"); //true
let boolValue1 = !!(""); //false
if (username) {
// username is defined
}
else {
//username is not defined
}
Equality
JavaScript operators == and != are basically broken: they do an implicit
type conversion before the comparison
Equality
ECMAScript standard added === and !== operators with the better
behavior
Array
An Object type used to store multiple values in a single variable
0-based indexing
Mutable
Can check size via length property
const list = []; // Creates an empty array
Arrays
An array can be used as a list, queue, stack, etc.
Basic methods:
• push/pop: add/remove the element at the end, return an element
• shift/unshift: remove/add an element at the head, return an element
• concat: joints two or more arrays, return the jointed array
• splice: add/remove elements from an array, return the array after
adding/removing
• sort/reserve: soft/reverse the order of elements in the array, return
the result after sorted, reserved
• slice: select a part of an array, return the selected part
[Link]
ĐẠI HỌC CẦN THƠ
CTU
38 [Link] 38
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Language Basics
Arrays
const a = ["Truc", "Lan"];
[Link](); //a=["Lan", "Truc"]
[Link]("Cuc"); //a=["Lan", "Truc", "Cuc"]
[Link]("Mai"); //a=["Mai", "Lan", "Truc", "Cuc"]
Date
The Date class is used to manipulate date and time data types.
Create Date:
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds,
milliseconds);
Methods:
getDate(), getDay(), getMonth(), getFullYear()
getHours(), getMinutes(), getSeconds(), getMilliseconds()
setDate(), setMonth(), setFullYear()
setHours(), setMinutes(), setSeconds(), setMilliseconds()
Date
Example:
let today = new Date()
let d1 = new Date("October 13, 1975 11:13:00")
let d2 = new Date(79,5,24)
let d3 = new Date(79,5,24,11,33,0)
Date
Example:
let x = new Date();
[Link] (2100, 0, 14);
let today = new Date();
if (x > today)
{
alert("Today is before 14th January 2100");
}
else
{
alert("Today is after 14th January 2100");
}
RegExp Type
Regular expression:
A sequence of characters that forms a search pattern
Regex is a common shorthand for a regular expression
JavaScript RegExp is an Object for handling Regular Expressions
Syntax
let txt=new RegExp(pattern,modifiers); or
let txt=/pattern/modifiers;
Pattern: defines the pattern of the expression.
Modifiers: specifies whether the search should be global and case-
sensitive.
Modifiers
g - Performs a global match (find all)
i - Performs case-insensitive matching
m – Performs Multiline mode matching
Example:
// Match all instances of "at" in a string.
var pattern1 = /at/g;
//Match the first instance of "bat" or "cat",
//regardless of case
var pattern2 = /[bc]at/i;
RegExp Object
Brackets ([]): characters enclosed in square brackets [].
RegExp Object
Metacharacter: characters with a special meaning.
RegExp Object
Quantifiers: define the numbers of characters or expressions to match.
RegExp Object
Common example:
Email Address: \b[A-z0-9._%+-]+@[A-z0-9.-]+\.[A-z]{2,6}\b
Date String: dd/mm/yyyy
(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)[0-9]{2}
International phone number: ^\+(?:[0-9] ?){6,14}[0-9]$
Integer: \b\d+\b
Text with letters and digits:
^[A-Z0-9]+$
Text with length from 1 to 10:
^[A-Z]{1,10}$
RegExp Object
Example:
Loop – for
Syntax:
for (statement 1; statement 2; statement 3) {
//code block to be executed
}
Example:
for (let i = 1; i <= 6; i++) {
[Link]("<h" + i + ">");
[Link]("Heading " + i);
[Link]("</h" + i + ">");
}
do {
//code block to be executed
} while (condition);
break statement
Used to jump out a loop or a switch statement and continue executing the
code after the loop or switch
let count = 0;
while (true) {
count++;
let r = [Link]([Link]() * 10);
[Link](r + " ");
if (r == 5) {
[Link]("<p>Found '5' after "
+ count + " times</p>");
break;
}
}
continue statement
The continue statement jumps over an iteration of a loop
The condition of the loop is checked for a new iteration
for (let i = 0; i <= 10; i++) {
if (i % 2 == 0)
continue;
[Link](i + " ");
}
Function Declaration
Syntax:
function func_name(parameters) {
//function body (statements)
}
A function hasn’t been executed until it is called
A function call can be made before its declaration (hoisting)
hello("Messi");
function hello(name) {
[Link]("Hello " + name);
}
Function Expression
A JS function can also be defined using an expression
let x = function (a, b) {return a * b};
let z = x(4, 3);
alert(z); //alert “12”
Function Expression
function lessthan(a, b) { return a < b;}
function sort(lessthan, arr) { //pass function as a parameter
for (i=0; i<[Link]-1; i++) {
for (j=i+1; j<[Link]; j++) {
if (lessthan(arr[j], arr[i]))
swap(arr[i], arr[j]);
}
function d() {
}
function e() {
}
alert('E’);
}
return e; //returns function e()
}
d()(); //alerts 'E'
ĐẠI HỌC CẦN THƠ
CTU
62 [Link] 62
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• JS Functions
Arrow Functions
Introduced in ES6
Allow us to write shorter function syntax:
Regular syntax and function expression:
Function Parameters
Function parameters (formal parameter) are the names listed in the function
definition
Function arguments (actual parameter) are the real values passed to (and
received by) the function
Parameter rules:
• JS function definitions do not specify datatype for parameters
• JS functions don’t check the datatype of the passed arguments
• JS functions do not check the number of arguments received
The built-in object arguments contains an array of the arguments
Function Parameters
x = findMax(1, 123, 500, 115, 44, 88);
function findMax() {
var i;
var max = -Infinity;
for (i = 0; i < [Link]; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
Methods Description
Selecting HMTL element
[Link](id) Find an element by element id
[Link](tag) Find elements by tag name
[Link](class) Find elements by class name
[Link](css selectors) Returns the first child element that
matches the given CSS selector(s)
[Link](css selectors) Returns all elements that matches
the given CSS selector(s)
Methods Description
Adding and Deleting elements
[Link](element) Create an HTML element
[Link](text) Create a text node
[Link](node) Add an HTML element
[Link](node) Remove an HTML element
[Link](new, old) Replace an HTML element
[Link](text) Write into the HTML output stream
<body>
<p id="par1">The first paragraph</p>
<p id="par2">The second paragraph</p>
<script>
let p1 = [Link]("par1");
[Link] = "x-large";
let p2 = [Link]("par2");
[Link] = "blue";
[Link] = "2px dotted #0000FF";
</script>
</body>
ĐẠI HỌC CẦN THƠ
CTU
78 [Link] 78
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Document Object Model (DOM)
HTML Events
HTML provides event handler attributes to use JS code to handle the
events
<element event='some JS code'>
HTML Events
<html>
<head>
<script>
function displayDate(eid) {
let e = [Link](eid);
[Link] = Date();
}
</script>
</head>
<body>
<input type="button" value="Click me!" id="bt1"
onclick="displayDate('demo');"
onmouseover="[Link]='red';"
onmouseout="[Link]='black';"/>
<p id="demo">...</p>
</body>
</html>
ĐẠI HỌC CẦN THƠ
CTU
84 [Link] 84
Cộng đồng – Toàn diện – Ưu việt Faculty of Computer Network and Communication
• Events
HTML Events
<script>
function prompttext(getf, inp) {
if (getf && ([Link] == "enter your name")) {
[Link] = "";
[Link] = "black";
}
if (!getf && ([Link] == "")) {
[Link] = "enter your name";
[Link] = "gray";
}
}
</script>
JS Objects
In JS, almost "everything" is an object, except primitives
• Boolean can be objects (if defined with the new keyword)
• Number can be objects (if defined with the new keyword)
• String can be objects (if defined with the new keyword)
• Date are always objects
• Math are always objects
• Regular expressions are always objects
• Arrays are always objects
• Functions are always objects
• Objects are always objects
JS Objects
A variable can contain a single value
JS objects:
• A JS object can contain many named values (properties)
• The values are written in pair as name : value
• An object can also contain methods (actions that the object can
performed)
• A method can be considered as a property that contains a function
definition
Create a JS Object
Three ways to create an object:
Define and create a single object, using an object literal
var person = {firstName:"John", lastName:"Doe", age:50,
showInfo: function() {
alert([Link]);
}};
Define and create a single object with the keyword new
var person = new Object();
[Link] = "John";
[Link] = 50;
showInfo: function() { alert([Link]); };
Create a JS Object
Three ways to create an object (cont):
Define an object constructor function, and then create objects of the
constructed type
function User(uname, pass) {
[Link] = uname;
[Link] = pass;
[Link] = function() {
alert([Link] + ":" + [Link]);
} //showInfo()
} //User
Example:
for (let name in scores) {
[Link](name + ' got ' + scores[name]);
}
Prototype
JS is described as a prototype-based language
Prototype may be considered as a “class” of an object created by an object
constructor function
A prototype is created for every object constructor function
It is used to:
• create static (common) properties for objects
• add properties (inherit) to an existing object created by an object
constructor function
Prototype
function Person(first, last) {
[Link] = first;
[Link] = last;
}
var person1 = new Person("John", "Doe");
Prototype
Add a “static” property for a prototype:
function Person(first, last) {
[Link] = first;
[Link] = last;
[Link]++;
};
[Link] = 0;
JS Classes
class Dog extends Animal {
Creating classes in ES6: constructor(name, breed) {
//Call the constructor of the parent class
super(name);
[Link] = breed;
class Animal { }
constructor(name) {
[Link] = name; //Overriding the speak method of the parent class
} speak() {
[Link]('${[Link]} barks');
}
speak() {
//New method specific to the Dog class
[Link]('${[Link]} fetch() {
makes a sound'); [Link]('${[Link]}
} fetches a ball');
} }
}
Creating Objects
Creating objects in ES6:
//Creating an instance of the child class
let myDog = new Dog('Buddy', 'Golden Retriever’);
Alert Box
Used to make sure information comes through to the user
The user will have to click "OK" to proceed
Syntax: [window.]alert("sometext");
Confirm Box
Used verify that the user accept something or not
The user will have to click either "OK" or "Cancel" to proceed
If the user clicks "OK", the box returns true.
If the user clicks "Cancel", the box returns false
Syntax: [window.]confirm("sometext");
Prompt Box
Used to get an input value from users
The user will have to click either "OK" or "Cancel" to proceed
If the user clicks "OK" the box returns the input value.
If the user clicks "Cancel" the box returns null
Syntax: [window.]prompt("sometext","defaultText");
Finally is optional
Further Reading
Methods of JS basic datatypes:
• String: indexOf(), lastIndexOf(), slice(), split(), trim(), etc.
• Number: isFinite(), isInteger(), toString(), etc.
• Math: abs(), min(), max(), sqrt(), round(), random(), etc.
JS regular expression: [Link]
JS debugging: [Link]
JS style guide: [Link]
JS Browser Object Model (BOM, allows JS to "talk to" the browser): Window, Screen,
Location, History, Navigation, Cookies