Webdev Intro To Js
Webdev Intro To Js
Introduction to JavaScript
Introduction to JavaScript
Web Development
What is JavaScript?
History of JavaScript
• There are lot more things you can do with JavaScript such as:
• You can modify the content of a web page by adding or removing elements.
• You can change the style and position of the elements on a web page.
• You can monitor events like mouse click, hover, etc. and react to it.
• You can perform and control transitions and animations.
• You can create alert pop-ups to display info or warning messages to the user.
• You can perform operations based on user inputs and display the results.
• You can validate user inputs before submitting it to the server.
Introduction to JavaScript
Web Development
• Embedding the JavaScript code between a pair of <script> and </script> tag.
• Creating an external JavaScript file with the .js extension and then load it within
the page through the src attribute of the <script> tag.
• Placing the JavaScript code directly inside an HTML tag using the special tag
attributes such as onclick, onmouseover, onkeypress, onload, etc.
• You can embed the JavaScript code directly within your web pages by placing it
between the <script> and </script> tags. The <script> tag indicates the
browser that the contained statements are to be interpreted as executable script
and not HTML.
Introduction to JavaScript
Web Development
Example: Create an HTML file named “embeddedjs.html” and place the following
code in it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Embedding JavaScript</title>
</head>
<body>
<script>
var greet = "Hello World!";
document.write(greet); // Prints: Hello World!
</script>
</body>
</html>
Introduction to JavaScript
Web Development
• You can also place your JavaScript code into a separate file with a .js extension,
and then call that file in your document through the src attribute of the <script>
tag, like this:
• <script src="js/hello.js"></script>
• This is useful if you want the same scripts available to multiple documents. It
saves you from repeating the same task over and over again, and makes your
website much easier to maintain.
Introduction to JavaScript
Web Development
Example: Create a JavaScript file named “hello.js” and place the following code in it:
Create an HTML file named “extenaljs.html” and place the following code in it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Including External JavaScript File</title>
</head>
<body>
<button type="button" id="myBtn">Click Me</button>
<script src="hello.js"></script>
</body>
</html>
Introduction to JavaScript
Web Development
• You can also place JavaScript code inline by inserting it directly inside the HTML tag
using the special tag attributes such as onclick, onmouseover, onkeypress, onload, etc.
• However, you should avoid placing large amount of JavaScript code inline as it clutters
up your HTML with JavaScript and makes your JavaScript code difficult to maintain.
Introduction to JavaScript
Web Development
Example: Create an HTML file named “inlineljs.html” and place the following code in it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inlining JavaScript</title>
</head>
<body>
<button onclick="alert('Hello World!')">Click
Me</button>
</body>
</html>
Introduction to JavaScript
Learning Activity 1
Create a page that shows a message “I’m JavaScript!” using the three ways of
adding a JavaScript to a web page.
Introduction to JavaScript
Learning Activity 2
Create a page that shows your Name and biography as your main page then
by clicking the “next” button it goes to other page “My Favorite Movies” and
required “Previous” button to go back to your first page.
Page 1 Page 2
Introduction to JavaScript
Web Development
JavaScript Syntax
• The syntax of JavaScript is the set of rules that define a correctly structured JavaScript
program.
Example:
var x = 5;
var y = 10;
var sum = x + y;
document.write(sum); // Prints variable value
Introduction to JavaScript
Web Development
JavaScript Comments
JavaScript Variables
• Most of the time, a JavaScript application needs to work with information. Here are two
examples:
• An online shop – the information might include goods being sold and a shopping cart.
• A chat application – the information might include users, messages, and much more.
• A variable is a “named storage” for data. We can use variables to store goodies, visitors,
and other data.
Introduction to JavaScript
Web Development
What is Variable?
var message;
• Now, we can put some data into it by using the assignment operator =:
var message;
• The string is now saved into the memory area associated with the variable. We can
access it using the variable name:
var message;
message = 'Hello!';
• To be concise, we can combine the variable declaration and assignment into a single line:
alert(message); // Hello!
Introduction to JavaScript
Web Development
• We can also declare multiple variables in one line but a multiline declaration is more
easier to read:
var user = 'John', age = 25, message = 'Hello';
var user = 'John';
var age = 25;
var message = 'Hello';
• A variable should be declared only once.
• A repeated declaration of the same variable is an error:
var message = "This";
• Data types basically specify what kind of data can be stored and manipulated within a
program.
• There are six basic data types in JavaScript which can be divided into three main
categories:
o Primitive (or primary)
String
Number
Boolean
o Composite (or reference)
Object
Array
Functions
o Special data types
Undefined
Null
Introduction to JavaScript
Web Development
• The string data type is used to represent textual data (i.e. sequences of characters).
Strings are created using single or double quotes surrounding one or more characters,
as shown below:
var a = 'Hi there!'; // using single quotes
var b = "Hi there!"; // using double quotes
• You can include quotes inside the string as long as they don't match the enclosing
quotes.
var a = "Let's have a cup of coffee."; // single quote inside double quotes
var b = 'He said "Hello" and left.'; // double quotes inside single quotes
var c = 'We\'ll never give up.'; // escaping single quote with backslash
Introduction to JavaScript
Web Development
• The number data type is used to represent positive or negative numbers with or without
decimal place, or numbers written using exponential notation e.g. 1.5e-4 (equivalent to
1.5x10-4).
• The Boolean data type can hold only two values: true or false. It is typically used to
store values like yes (true) or no (false), on (true) or off (false), etc. as demonstrated
below:
var a = 2, b = 5, c = 10;
• The undefined data type can only have one value-the special value undefined. If a
variable has been declared, but has not been assigned a value, has the value
“undefined”.
var a;
var b = "Hello World!"
• This is another special data type that can have only one value-the null value. A null
value means that there is no value. It is not equivalent to an empty string ("") or 0, it is
simply nothing.
• A variable can be explicitly emptied of its current contents by assigning it the null value.
var a = null;
alert(a); // Output: null
b = null;
alert(b) // Output: null
Introduction to JavaScript
Web Development
• The object is a complex data type that allows you to store collections of data.
• An object contains properties, defined as a key-value pair. A property key (name) is
always a string, but the value can be any data type, like strings, numbers, booleans, or
complex data types like arrays, function and other objects. You'll learn more about
objects in upcoming chapters.
• The following example will show you the simplest way to create an object in JavaScript.
var emptyObject = {};
var person = {"name": "Clark", "surname": "Kent", "age": "36"};
• You can omit the quotes around property name if the name is a valid JavaScript name.
That means quotes are required around "first-name" but are optional around firstname.
So the car object in the above example can also be written as:
var car = {
modal: "BMW X3",
color: "white",
doors: 5
}
Introduction to JavaScript
Web Development
• An array is a type of object used for storing multiple values in single variable. Each
value (also called an element) in an array has a numeric position, known as its index,
and it may contain data of any data type-numbers, strings, booleans, functions, objects,
and even other arrays. The array index starts from 0, so that the first array element is
arr[0] not arr[1].
• The simplest way to create an array is by specifying the array elements as a comma-
separated list enclosed by square brackets, as shown in the example below:
• The function is callable object that executes a block of code. Since functions are objects,
so it is possible to assign them to variables, as shown in the example below:
• In fact, functions can be used at any place any other value can be used. Functions can
be stored in variables, objects, and arrays. Functions can be passed as arguments to
other functions, and functions can be returned from functions. Consider the following
function:
function createGreeting(name){
return "Hello, " + name;
}
function displayGreeting(greetingFunction, userName){
return greetingFunction(userName);
}
The if Statement
• The if statement is used to execute a block of code only if the specified condition
evaluates to true. This is the simplest JavaScript's conditional statements and can be
written like:
if(condition) {
// Code to be executed
}
Example:
The following example will output "Have a nice weekend!" if the current day is Friday:
if(dayOfWeek == 5) {
alert("Have a nice weekend!");
}
Introduction to JavaScript
Web Development
• You can enhance the decision making capabilities of your JavaScript program by
providing an alternative choice through adding an else statement to the if statement.
• The if...else statement allows you to execute one block of code if the specified condition
is evaluates to true and another block of code if it is evaluates to false. It can be
written, like this:
if(condition) {
// Code to be executed if condition is true
} else {
// Code to be executed if condition is false
}
Introduction to JavaScript
Web Development
Example:
The JavaScript code in the following example will output "Have a nice weekend!" if the
current day is Friday, otherwise it will output the text "Have a nice day!"
if(dayOfWeek == 5) {
alert("Have a nice weekend!");
} else {
alert("Have a nice day!");
}
Introduction to JavaScript
Web Development
• The if...else if...else a special statement that is used to combine multiple if...else
statements.
if(condition1) {
// Code to be executed if condition1 is true
} else if(condition2) {
// Code to be executed if the condition1 is false and condition2 is true
} else {
// Code to be executed if both condition1 and condition2 are false
}
Introduction to JavaScript
Web Development
Example:
The following example will output "Have a nice weekend!" if the current day is Friday,
and "Have a nice Sunday!" if the current day is Sunday, otherwise it will output "Have
a nice day!"
if(dayOfWeek == 5) {
alert("Have a nice weekend!");
} else if(dayOfWeek == 0) {
alert("Have a nice Sunday!");
} else {
alert("Have a nice day!");
}
Introduction to JavaScript
Web Development
Switch...Case Statement
switch(x){
case value1:
// Code to be executed if x === value1
break;
case value2:
// Code to be executed if x === value2
break;
...
default:
// Code to be executed if x is different from all values
}
Introduction to JavaScript
Web Development
var d = new Date();
switch(d.getDay()) {
case 0:
Switch...Case Statement alert("Today is Sunday.");
break;
case 1:
Example: alert("Today is Monday.");
break;
Consider the following example, which display case 2:
the name of the day of the week. alert("Today is Tuesday.");
break;
case 3:
alert("Today is Wednesday.");
break;
case 4:
alert("Today is Thursday.");
break;
case 5:
alert("Today is Friday.");
break;
case 6:
alert("Today is Saturday.");
break;
default:
alert("No information available for that day.");
break;
}
Introduction to JavaScript
Web Development
while Loop
while Loop
while(condition) {
// Code to be executed
}
• The following example defines a loop that will continue to run as long as the variable i is
less than or equal to 5. The variable i will increase by 1 each time the loop runs:
var i = 1;
while(i <= 5) {
document.write("<p>The number is " + i + "</p>");
i++;
}
Introduction to JavaScript
Web Development
do...while Loop
do...while Loop
do...while Loop
• The JavaScript code in the following example defines a loop that starts with i=1. It will
then print the output and increase the value of variable i by 1. After that the condition
is evaluated, and the loop will continue to run as long as the variable i is less than, or
equal to 5.
var i = 1;
do {
document.write("<p>The number is " + i + "</p>");
i++;
}
while(i <= 5);
Introduction to JavaScript
Web Development
for Loop
for Loop
• The following example defines a loop that starts with i=1. The loop will continued until the
value of variable i is less than or equal to 5. The variable i will increase by 1 each time the
loop runs:
1. Write a JavaScript program that accept two integers and display the larger
2. Write a JavaScript conditional statement to sort three numbers. Display an
alert box to show the result.
3. Write a JavaScript conditional statement to find the largest of five numbers.
Display an alert box to show the result.
4. Write a JavaScript for loop that will iterate from 0 to 15. For each iteration, it
will check if the current number is odd or even, and display a message to the
screen.
Sample output
"0 is even"
"1 is odd"
"2 is even"