0% found this document useful (0 votes)
2K views

Javascript Basics: Study Guide For Module No. 5.1

The document provides learning materials for a module on JavaScript basics. It introduces JavaScript, discusses its history and uses. It then describes three ways to add JavaScript to web pages: embedded, external, and inline. It also covers JavaScript syntax, variables, and data types. The module aims to help students understand the fundamentals of JavaScript like conditional statements, loops, and integrating JavaScript into HTML pages.

Uploaded by

Dhan Cabugao
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views

Javascript Basics: Study Guide For Module No. 5.1

The document provides learning materials for a module on JavaScript basics. It introduces JavaScript, discusses its history and uses. It then describes three ways to add JavaScript to web pages: embedded, external, and inline. It also covers JavaScript syntax, variables, and data types. The module aims to help students understand the fundamentals of JavaScript like conditional statements, loops, and integrating JavaScript into HTML pages.

Uploaded by

Dhan Cabugao
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

FM-AA-CIA-15 Rev.

0 10-July-2020

Study Guide in (Course Code and Course Title) Module No.__

STUDY GUIDE FOR MODULE NO. 5.1

JavaScript Basics
MODULE OVERVIEW

JavaScript is a lightweight, interpreted programming language. It is designed for creating network-centric


applications. It is complimentary to and integrated with Java. JavaScript is very easy to implement because it is
integrated with HTML. It is open and cross-platform. This lesson will help you learn the fundamentals of
JavaScript.

MODULE LEARNING OBJECTIVES

At the end of this module, students are expected to:

1. Understand what is JavaScript?


2. Understand and demonstrate the three ways of adding JavaScript to a web page
a. Embedded JavaScript
b. External JavaScript
c. Inline JavaScript
3. Understand JavaScript Syntax
4. Understand the use of Variables and Data Types
5. Understand and demonstrate conditional and looping statements using JavaScript

LEARNING CONTENTS (Introduction to JavaScript)

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.

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.

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.
CTIVITY 1

LEARNING CONTENTS (Three ways to add JavaScript to a web page)

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

PANGASINAN STATE UNIVERSITY 1


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (Course Code and Course Title) Module No.__

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

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>

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.

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;

 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>

PANGASINAN STATE UNIVERSITY 2


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (Course Code and Course Title) Module No.__

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.

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>

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.

LEARNING CONTENTS (Understanding JavaScript Syntax)

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

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

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:

Example:

// This is my first JavaScript program


document.write("Hello World!");

PANGASINAN STATE UNIVERSITY 3


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (Course Code and Course Title) Module No.__

/* This is my first program


in JavaScript */
document.write("Hello World!");

LEARNING CONTENTS (JavaScript Variables and Data Types)

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.

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

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

 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

PANGASINAN STATE UNIVERSITY 4


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (Course Code and Course Title) Module No.__

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

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

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

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

PANGASINAN STATE UNIVERSITY 5


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (Course Code and Course Title) Module No.__

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!

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

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
}

 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
}

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

PANGASINAN STATE UNIVERSITY 6


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (Course Code and Course Title) Module No.__

 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

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!

 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

LEARNING CONTENTS (Conditional and Looping Statements)


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

PANGASINAN STATE UNIVERSITY 7


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (Course Code and Course Title) Module No.__

Image 1. Flowchart for if-else statement

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!");
}

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
}

Example:

PANGASINAN STATE UNIVERSITY 8


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (Course Code and Course Title) Module No.__

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!");
}

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
}

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!");
}

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

PANGASINAN STATE UNIVERSITY 9


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (Course Code and Course Title) Module No.__

break;
...
default:
// Code to be executed if x is different from all values
}

Example:
Consider the following example, which display the name of the day of the week.

var d = new Date();

switch(d.getDay()) {
case 0:
alert("Today is Sunday.");
break;
case 1:
alert("Today is Monday.");
break;
case 2:
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;
}

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.

PANGASINAN STATE UNIVERSITY 10


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (Course Code and Course Title) Module No.__

Image 2. Flowchart for while loop statement

 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++;
}

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.

PANGASINAN STATE UNIVERSITY 11


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (Course Code and Course Title) Module No.__

Image 3. Flowchart for do…while loop statement

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

do {
// Code to be executed
}
while(condition);

 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);

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.

PANGASINAN STATE UNIVERSITY 12


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (Course Code and Course Title) Module No.__

Image 4. Flowchart for For loop statement

 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>");
}

LEARNING ACTIVITY 2

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"

PANGASINAN STATE UNIVERSITY 13


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in (Course Code and Course Title) Module No.__

SUMMARY

 JavaScript is a lightweight, interpreted programming language.


 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.
 There are three ways to add JavaScript to your web page
o Embedded JavaScript
o External JavaScript
o Inline JavaScript

REFERENCES

 https://www.tutorialrepublic.com/javascript-tutorial/
 https://javascript.info/
 https://www.guru99.com/interactive-javascript-tutorials.html
 https://www.tutorialspoint.com/javascript/index.htm

 JAVASCRIPT & JQUERY: interactive front-end web development by Jon Duckett

PANGASINAN STATE UNIVERSITY 14

You might also like