Lecture 15 Java Script Part 2
Lecture 15 Java Script Part 2
Module 2
Content
• Statements
• Syntax
• Function
• Objects
JavaScript Statements • A computer program is a list of
<!DOCTYPE html> "instructions" to be "executed" by a
<html>
<body> computer.
• Expressions
• Keywords
• Comments.
JavaScript Statements • Most JavaScript programs contain many
<!DOCTYPE html> JavaScript statements.
<html>
<body>
• The statements are executed, one by one, in
<h2>JavaScript Statements</h2> the same order as they are written.
<p>A <b>JavaScript program</b> is a list of <b>statements</b> to be
executed by a computer.</p>
• JavaScript programs (and JavaScript
statements) are often called JavaScript code
<p id="demo"></p>
<script> Semicolons:
let x, y, z; // Statement 1
x = 5; // Statement 2 • Semicolons separate JavaScript statements.
y = 6; // Statement 3
z = x + y; // Statement 4 • Add a semicolon at the end of each executable
document.getElementById("demo").innerHTML = "The value of z is " + z + statement
".";
</script> • When separated by semicolons, multiple
</body> statements on one line are allowed
</html>
• Ending statements with semicolon is not
required, but highly recommended
JavaScript Statements
<!DOCTYPE html>
JavaScript White Space
<html>
<body> • JavaScript ignores multiple spaces.
<p id="demo"></p>
• A good practice is to put spaces around
operators ( = + - * / )
<script>
let x, y, z; // Statement 1
x = 5; // Statement 2 JavaScript Line Length and Line Breaks
y = 6; // Statement 3
z = x + y; // Statement 4 • For best readability, programmers often
document.getElementById("demo").innerHTML = "The value of z is " + z + like to avoid code lines longer than 80
".";
</script> characters.
</body>
</html>
JavaScript Statements
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello!";
document.getElementById("demo2").innerHTML = "How are
you?";
}
</script>
</body>
</html>
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be performed.
JavaScript Values
The JavaScript syntax defines two types of values:
• Fixed values – Literals
• Variable values – Variables
JavaScript Variables
JavaScript Literals
• In a programming language, variables are used
The two most important syntax rules for fixed values are:
to store data values.
1. Numbers are written with or without decimals
• JavaScript uses the keywords var, let and const to
2. Strings are text, written within double or single
declare variables.
quotes
• An equal sign is used to assign values to
variables.
JavaScript
Syntax
JavaScript syntax is the set of rules, how JavaScript programs are constructed
JavaScript Operators
• Arithmetic operators: + , - , * , / , ** , % , ++ , --
• Assignment operator: = , += , -= , *= , /= , %= , **=
• String operator: + , +=
• Comparison Operator: == (Equal to) , === (Equal Value and Equal Type), != , < , > , <= , >= , ?
• Logical Operator: && , || , !
• Type Operators: typeof, instanceof
• Bitwise Operators: & , | , ~ , ^ , << , >>
JavaScript Syntax
JavaScript syntax is the set of rules, how JavaScript programs are constructed
JavaScript Operators
Arithmetic operators: Addition ( + ), Subtraction( - ), Multiplication( * ), Division ( / )
Assignment operator: ( = )
JavaScript Expressions
• In JavaScript, identifiers are used In JavaScript, the first character must be a letter, or an
underscore (_), or a dollar sign ($).
to name variables (and
keywords, and functions, and Subsequent characters may be letters, digits, underscores, or
labels). dollar signs.
programming languages.
JavaScript programmers tend to use camel case that starts
with a lowercase letter:
JavaScript function name(parameter1, parameter2, parameter3)
Functions {
// code to be executed
}
• It is a block of code designed to
It is defined with the function keyword, followed by a name, followed by
perform a particular task parentheses ().
• It is executed when "something" Function names can contain letters, digits, underscores, and dollar
signs (same rules as variables).
<p>This example calls a function which performs a • When it is invoked (called) from JavaScript code
calculation and returns the result:</p>
• Automatically (self invoked)
<p id="demo"></p>
<script>
var x = myFunction(4, 3); Function Return
document.getElementById("demo").innerHTML = x;
• When JavaScript reaches a return statement, the
function myFunction(a, b) {
function will stop executing.
return a * b;
}
• If the function was invoked from a statement,
</script>
JavaScript will "return" to execute the code after
</body>
the invoking statement.
</html>
• Functions often compute a return value. The
return value is "returned" back to the "caller
JavaScript Functions
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p id="demo"></p>
<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
</body>
</html>
JavaScript Functions Function Invocation
<!DOCTYPE html>
Accessing a function without () will return
<html>
<body> the function object instead of the function
<h2>JavaScript Functions</h2> result.
<script>
function toCelsius(f) {
return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML = toCelsius;
</script>
</body>
</html>
JavaScript Objects
JavaScript Objects
Real Life Objects, Properties, and Methods
• In real life, a car is an object.
• A car has properties like weight and color, and methods like start and stop
• All cars have the same properties, but the property values differ from car to car.
• All cars have the same methods, but the methods are performed at different times.
JavaScript Objects
• Objects are variables but it contain many values.
• The values are written as name:value pairs (name and value separated by a colon).
• It is a common practice to declare objects with the const keyword.
• We can define (and create) a JavaScript object with an object literal
• Spaces and line breaks are not important.
• An object definition can span multiple lines
Object Definition on Single Line
JavaScript Objects
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
const car = {type:"Fiat", model:"500", color:"white"};
</body>
</html>
JavaScript Objects Object Definition on Multiple Line
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
</body>
</html>
JavaScript Objects
Object Properties
The name:values pairs in JavaScript objects are called properties:
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "John",
lastName : "Doe",
id : 5566
};
</body>
</html>
JavaScript Object Methods
Objects
<!DOCTYPE html>
Objects can also have methods.
<html> Methods are actions that can be performed on objects.
<body>
Methods are stored in properties as function definitions.
<h2>JavaScript Objects</h2>
A method is a function stored as a property.
<p>An object method is a function definition, stored
as a property value.</p>
<p id="demo"></p>
// Display data from the object: {return this.firstName + " " + this.lastName;}
document.getElementById("demo").innerHTML =
person.fullName();
</script>
</body>
</html>
JavaScript
Objects
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p>An object method is a function definition, stored
as a property value.</p>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
</body>
</html>
JavaScript
Objects
<!DOCTYPE html>
<html>
<body> Accessing Object Methods
<h2>JavaScript Objects</h2>
<p>An object method is a function definition, stored We can access an object method with the following
as a property value.</p>
syntax:
<p id="demo"></p>
objectName.methodName()
<script>
// Create an object:
const person = { If you access a method without the () parentheses, it will
firstName: "John",
lastName: "Doe",
return the function definition
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
</body>
</html>
JavaScript Date
JavaScript Date
• JavaScript Date Object lets us work with dates
• JavaScript will use the browser's time zone and display a date as a full text string
new Date( )
new Date(milliseconds)
</body>
</html>
JavaScript Date new Date(year, month, ...)
<h2>JavaScript new Date()</h2> const d = new Date(2018, 11, 24, 10, 33, 30, 0);
<p>Using new Date(), creates a new date object
• JavaScript counts months from 0 to 11:
with the current date and time:</p>
January = 0.
<p id="demo"></p>
<script>
const d = new Date(2018, 11, 24, 10, 33, 30, 0);
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
JavaScript Date new Date(dateString)
<p id="demo"></p>
<script>
const d = new Date("October 13, 2014 11:13:00");
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
JavaScript Date new Date(milliseconds)
<!DOCTYPE html>
• It creates a new date object as zero time plus milliseconds
<html> • Example
<body>
const d = new Date(0);
<h2>JavaScript new Date()</h2>
• JavaScript stores dates as number of milliseconds since
<p>A Date object can be created with a specified
January 01, 1970, 00:00:00 UTC (Universal Time
date and time:</p>
Coordinated).
<p id="demo"></p>
• Zero time is January 01, 1970 00:00:00 UTC.
</body>
</html>
JavaScript Date
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const d = new Date(0);
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
Date Methods
JavaScript
• When a Date object is created, a number of methods allow you to operate on it.
Date
• Date methods allow you to get and set the year, month, day, hour, minute, second,
and millisecond of date objects, using either local time or UTC (universal, or GMT) time.
• JavaScript will (by default) output dates in full text string format:
document.getElementById("demo").innerHTML = d.toDateString();
Date Formats
JavaScript
There are generally 3 types of JavaScript date input formats:
Date
Type Example
• The other formats are not so well defined and might be browser specific
JavaScript
Date
JavaScript ISO Dates
• ISO 8601 is the international standard for the representation of dates and times.
• The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date format
• ISO dates can be written with added hours, minutes, and seconds (YYYY-MM-DDTHH:MM:SSZ):
• If you want to modify the time relative to UTC, remove the Z and add +HH:MM or -HH:MM
instead:
JavaScript Short Dates
JavaScript
• Short dates are written with an "MM/DD/YYYY" syntax like
Date
• Example: const d = new Date("03/25/2015");
• In some browsers, months or days with no leading zeroes may produce an error:
• Some browsers will try to guess the format. Some will return NaN.
• Some browsers will try to guess the format. Some will return NaN.
Example
1970)
<h2>JavaScript getMonth()</h2>
<p>The getMonth() method returns the month as a number:</p>
<p>You can use an array to display the name of the month:</p>
<p id="demo"></p>
<script>
const d = new Date();
const months =
["January","February","March","April","May","June","July","August","September","October","Novem
ber","December"];
document.getElementById("demo").innerHTML = months[d.getMonth()];
</script>
</body>
</html>
JavaScript
JavaScript Set Date Methods
Date
Method Description
<h2>JavaScript setFullYear()</h2>
<p>The setFullYear() method can optionally set month and day.</p>
<p>Please note that month counts from 0. December is month
11:</p>
<p id="demo"></p>
<script>
const d = new Date();
d.setFullYear(2020, 11, 3);
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
Comparing Dates
JavaScript Date
Dates can be easily compared
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let text;
const today = new Date();
const someday = new Date();
someday.setFullYear(2100, 0, 14);
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
JavaScript Regular
Expression
JavaScript Regular
Expression
• A regular expression is a sequence of characters that forms a search pattern.
• When you search for data in a text, you can use this search pattern to describe what you are
searching for.
• Regular expressions can be used to perform all types of text search and text replace operations.
Syntax
/pattern/modifiers;
Example
/w3schools/i;
• In JavaScript, regular expressions are often used with the two string methods: search()
and replace().
• The search() method: It uses an expression to search for a match, and returns the
• The replace() method: It returns a modified string where the pattern is replaced.
JavaScript Regular
Expression
String search() With a String
• The search() method searches a string for a specified value and returns the position of the match:
let n = text.search("W3Schools");
let n = text.search(/w3schools/i);
• The replace() method replaces a specified value with another value in a string
• Example:
• Regular expression arguments (instead of string arguments) can be used in the methods
• Regular expressions can make your search much more powerful (case insensitive for example)
Modifier Description
g Perform a global match (find all matches rather than stopping after the first match)
Expression Description
Metacharacter Description
\d Find a digit
\b Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\ \
uxxxx Find the Unicode character specified by the hexadecimal number xxxx
JavaScript Regular
Expression
Regular Expression Patterns
Quantifiers Description
Using test()
• It searches a string for a pattern, and returns true or false, depending on the result.
Example:
Since there is an "e“ in the string, the output of the code above will be: true
• You don't have to put the regular expression in a variable first. The two lines above can be shortened to
one:
JavaScript Regular
Expression
Using the RegExp Object
In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.
Using exec()
• It searches a string for a specified pattern, and returns the found text as an object.
Example