0% found this document useful (0 votes)
9 views

Webdev Intro To Js

The document provides an introduction to JavaScript, covering what JavaScript is, its history and evolution, what can be done with JavaScript, and the different ways to add JavaScript to web pages. It also discusses JavaScript syntax, case sensitivity, comments, variables, and data types.

Uploaded by

Vincent Siaron
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Webdev Intro To Js

The document provides an introduction to JavaScript, covering what JavaScript is, its history and evolution, what can be done with JavaScript, and the different ways to add JavaScript to web pages. It also discusses JavaScript syntax, case sensitivity, comments, variables, and data types.

Uploaded by

Vincent Siaron
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Web Development

Introduction to JavaScript
Introduction to JavaScript
Web Development

What is JavaScript?

• JavaScript was initially created to “make web pages alive”.


• The programs in this language are called scripts. They can be written right in a
web page’s HTML and run automatically as the page loads.
• Scripts are provided and executed as plain text. They don’t need special
preparation or compilation to run.
Introduction to JavaScript
Web Development

History of JavaScript

• JavaScript was originally developed as LiveScript by Netscape in the mid-1990s.


• It was later renamed to JavaScript in 1995, and became an ECMA standard in
1997.
• JavaScript is officially maintained by ECMA (European Computer Manufacturers
Association) as ECMAScript. ECMAScript 6 (or ES6) is the latest major version of
the ECMAScript standard.
Introduction to JavaScript
Web Development

What can you do with 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

There are typically three ways to add JavaScript to a web page:

• 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.

Embedding the JavaScript Code

• 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

Calling an External JavaScript File

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

// A function to display a message


function sayHello() {
alert("Hello World!");
}
// Call function on click of the button
document.getElementById("myBtn").onclick = sayHello;
Introduction to JavaScript
Web Development

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

Placing the JavaScript Code Inline

• 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.

• A JavaScript consists of JavaScript statements that are placed within the


<script></script> HTML tags in a web page, or within the external JavaScript file
having .js extension.

Example:

var x = 5;
var y = 10;
var sum = x + y;
document.write(sum); // Prints variable value
Introduction to JavaScript
Web Development

Case Sensitivity in JavaScript

• JavaScript is case-sensitive. This means that variables, language keywords, function


names, and other identifiers must always be typed with a consistent capitalization of
letters.
• For example, the variable myVar must be typed myVar not MyVar or myvar. Similarly,
the method name getElementById() must be typed with the exact case not as
getElementByID().
Introduction to JavaScript
Web Development

JavaScript Comments

• JavaScript support single-line as well as multi-line comments. Single-line comments


begin with a double forward slash (//), followed by the comment text. Here's an
example:

// This is my first JavaScript program


document.write("Hello World!");

/* This is my first program


in JavaScript */
document.write("Hello World!");
Introduction to JavaScript
Web Development

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?

• To create a variable in JavaScript, use the var keyword.


• The statement below creates (in other words: declares) a variable with the name
“message”:

var message;

• Now, we can put some data into it by using the assignment operator =:

var message;

message = 'Hello'; // store the string


Introduction to JavaScript
Web Development

• 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!';

alert(message); // shows the variable content

• To be concise, we can combine the variable declaration and assignment into a single line:

var message = 'Hello!'; // define the variable


and assign the value

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

// repeated 'var' leads to an error

var message = "That"; // SyntaxError: 'message' has


already been declared
Introduction to JavaScript
Web Development

JavaScript Data Types

• 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

String Data Type

• 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

Number Data Type

• 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).

var a = 25; // integer


var b = 80.5; // floating-point number
var c = 4.25e+6; // exponential notation, same as 4.25e6 or 4250000
var d = 4.25e-6; // exponential notation, same as 0.00000425
Introduction to JavaScript
Web Development

Boolean Data Type

• 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 isReading = true; // yes, I'm reading


var isSleeping = false; // no, I'm not sleeping

• Boolean values also come as a result of comparisons in a program. The following


example compares two variables and shows the result in an alert dialog box:

var a = 2, b = 5, c = 10;

alert(b > a) // Output: true


alert(b > c) // Output: false
Introduction to JavaScript
Web Development

Undefined Data Type

• 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!"

alert(a) // Output: undefined


alert(b) // Output: Hello World!
Introduction to JavaScript
Web Development

Null Data Type

• 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

var b = "Hello World!"


alert(b); // Output: Hello World!

b = null;
alert(b) // Output: null
Introduction to JavaScript
Web Development

Object Data Type

• 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"};

// For better reading


var car = {
"modal": "BMW X3",
"color": "white",
"doors": 5
}
Introduction to JavaScript
Web Development

Object Data Type

• 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

Array Data Type

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

var colors = ["Red", "Yellow", "Green", "Orange"];


var cities = ["London", "Paris", "New York"];

alert(colors[0]); // Output: Red


alert(cities[2]); // Output: New York
Introduction to JavaScript
Web Development

Function Data Type

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

var greeting = function(){


return "Hello World!";
}

// Check the type of greeting variable


alert(typeof greeting) // Output: function
alert(greeting()); // Output: Hello World!
Introduction to JavaScript
Web Development

• 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);
}

var result = displayGreeting(createGreeting, "Peter");


alert(result); // Output: Hello, Peter
Introduction to JavaScript
Web Development

• While writing a program, there may be a situation


when you need to adopt one out of a given set of
paths. In such cases, you need to use conditional
statements that allow your program to make
correct decisions and perform right actions.
• JavaScript supports conditional statements which
are used to perform different actions based on
different conditions. Here we will explain the
if..else statement.

Image 1. Flowchart for if-else statement


Introduction to JavaScript
Web Development

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:

var now = new Date();


var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6

if(dayOfWeek == 5) {
alert("Have a nice weekend!");
}
Introduction to JavaScript
Web Development

The if...else Statement

• 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

The if...else Statement

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

var now = new Date();


var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6

if(dayOfWeek == 5) {
alert("Have a nice weekend!");
} else {
alert("Have a nice day!");
}
Introduction to JavaScript
Web Development

The if...else if...else Statement

• 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

The if...else if...else Statement

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

var now = new Date();


var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6

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

• The switch..case statement is an alternative to the if...else if...else statement, which


does almost the same thing. The switch...case statement tests a variable or expression
against a series of values until it finds a match, and then executes the block of code
corresponding to that match. It's syntax is:

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

• The most basic loop in JavaScript is the


while loop which would be discussed in this
chapter. The purpose of a while loop is to
execute a statement or code block
repeatedly as long as an expression is true.
Once the expression becomes false, the
loop terminates.

Image 2. Flowchart for while loop statement


Introduction to JavaScript
Web Development

while Loop

• The generic syntax of the while loop is:

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

• The do...while loop is similar to the while


loop except that the condition check
happens at the end of the loop. This means
that the loop will always be executed at
least once, even if the condition is false.

Image 3. Flowchart for do…while loop statement


Introduction to JavaScript
Web Development

do...while Loop

• The generic syntax of the do-while loop is:


do {
// Code to be executed
}
while(condition);
Introduction to JavaScript
Web Development

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

• The for loop repeats a block of code as


long as a certain condition is met. It is
typically used to execute a block of code
for certain number of times.

Image 4. Flowchart for For loop statement


Introduction to JavaScript
Web Development

for Loop

• The parameters of the for loop statement have following meanings:


o initialization — it is used to initialize the counter variables, and evaluated once
unconditionally before the first execution of the body of the loop.
o condition — it is evaluated at the beginning of each iteration. If it evaluates to true,
the loop statements execute. If it evaluates to false, the execution of the loop ends.
o increment — it updates the loop counter with a new value each time the loop runs.

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

for(var i=1; i<=5; i++) {


document.write("<p>The number is " + i + "</p>");
}
Introduction to JavaScript
Learning Activity 3

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"

You might also like