Javascript Basics: Study Guide For Module No. 5.1
Javascript Basics: Study Guide For Module No. 5.1
0 10-July-2020
JavaScript Basics
MODULE OVERVIEW
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.
CTIVITY 1
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.
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>
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:
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>
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.
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
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:
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?
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:
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:
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
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:
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
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:
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;
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
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.
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
}
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!");
}
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:
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!");
}
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!"
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
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.
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.
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.
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.
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:
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"
SUMMARY
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