JavaScript UNIT I
1.1 Using Comments in Script
JavaScript comments are used to explain the code to make it more readable.
It can be used to prevent the execution of a section of code if necessary.
The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the
browser.
To make code easy to understand. It can be used to elaborate the code so that end user
can easily understand the code.
To avoid the unnecessary code. It can also be used to avoid the code being executed.
Sometimes, we add the code to perform some action. But after sometime, there may
be need to disable the code. In such case, it is better to use comments.
There are two types of comments in JavaScript.
1. Single-line Comment
2. Multi-line Comment
JavaScript Single line Comment
It is represented by double forward slashes (//).
It can be used before and after the statement.
Example of single-line comment
<script>
var
a=10;
var
b=20;
var c=a+b; //It adds values of a and b variable
[Link](c); //prints sum of 10 and 20
JavaScript Multi line Comment
It can be used to add single as well as multi line comments. So, it is more convenient.
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 1
[Link]
JavaScript UNIT I
It is represented by forward slash with asterisk (/* ) then asterisk with forward slash(*/ ).
Syntax : /* your code here */
Example:
<script>
/* It is multi line comment.
It will not be displayed */
[Link]("example of javascript multiline comment");
</script>
1.2 Using the noScript
The <noscript> tag defines an alternate content to be displayed to users that have
disabled scripts in their browser or have a browser that doesn't support script.
The <noscript> element can be used in both <head> and <body>.
When used inside <head>, the <noscript> element could only contain <link>, <style>,
and <meta> elements.
This tag is used in those browsers only which does not support scripts.
Syntax:
<noscript> Contents... </noscript>
Example:
<html>
<body style="text-align: center;">
<h1 style="color:green;">
NIIT Nanded
</h1>
<p>HTML noscript Tag</p>
<script>
[Link]("nosript tag is used in those browsers
only which does not support scripts.")
</script>
<!-- noscript tag starts -->
<noscript>A computer science portal</noscript>
<!-- noscript tag ends -->
</body>
</html>
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 2
[Link]
JavaScript UNIT I
1.3 Creating Alert Dialogs
An alert dialog box is mostly used to give a warning message to the users.
Alert box gives only one button "OK" to select and proceed.
For example, if one input field requires to enter some text but the user does not
provide any input, then as a part of validation, you can use an alert box to give a
warning message.
Rather than showing the warnings or errors, the alert dialog box can be used for
normal messages such as 'welcome NIIT', 'Hello NIIT', etc.
Syntax:
[Link]("sometext");
OR
alert("sometext"); // method can be written without the window prefix.
Example:
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 3
[Link]
JavaScript UNIT I
<html>
<head>
<script
type="text/javascript">
function show() {
alert("It is an Alert dialog box");
}
</script>
</head>
<body style="text-align: center;">
<p>Alert Box Example</p>
<h1 style="color:green;">
Welcome to NIIT Nanded
</h1>
<p>Click the following button </p>
<input type="button" value="Click Me" onclick="show();"/>
</body>
</html>
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 4
[Link]
JavaScript UNIT I
1.4 Understanding Conditional Statement
Conditional statements in JavaScript allow you to execute specific blocks of code
based on conditions. If the condition meets then a particular block of action will be
executed otherwise it will execute another block of action that satisfies that particular
condition.
There are several methods that can be used to perform Conditional Statements in
JavaScript.
1. if Statement
2. if-else Statement
3. if….else if….statement
4. nested if statements
1. The if statement
It is one of the simplest decision-making statement which is used to decide
whether a block of JavaScript code will execute if a certain condition is true.
Syntax:
if (condition)
{
// block of code to be executed if the condition is
true
}
If the condition evaluates to true, the code within if statement will execute, but
if the condition evaluates to false, then the code after the end of if statement
(after the closing of curly braces) will execute.
Example:
let num = 20;
if (num % 2 === 0) {
[Link]("Given number is even number.");
}
if (num % 2 !== 0) {
[Link]("Given number is odd number.");
};
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 5
[Link]
JavaScript UNIT I
2. The if….else statement
The if….else statement includes two blocks that are if block and else block. It
is the next form of the control statement, which allows the execution of
JavaScript in a more controlled way. It is used when you require to check two
different conditions and execute a different set of codes. The else statement is
used for specifying the execution of a block of code if the condition is false.
Syntax:
if (condition)
{
// block of code to be executed if the condition is
true
}
else
{
// block of code to be executed if the condition is
false
}
If the condition is true, then the statements inside if block will be executed, but
if the condition is false, then the statements of the else block will be executed.
Example:
let age = 25;
if (age >= 18) {
[Link]("You are eligible of driving licence")
} else {
[Link]("You are not eligible for driving
licence")
};
3. The if….else if…..else statement
It is used to test multiple conditions. The if statement can have multiple or
zero else if statements and they must be used before using the else statement.
You should always be kept in mind that the else statement must come after the
else if statements.
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 6
[Link]
JavaScript UNIT I
Syntax:
if (condition1)
{
// block of code to be executed if condition1 is
true
}
else if (condition2)
{
// block of code to be executed if the condition1
is false and condition2 is true
}
else
{
// block of code to be executed if the condition1
is false and condition2 is false
}
Example:
const num = 0;
if (num > 0) {
[Link]("Given number is positive.");
} else if (num < 0) {
[Link]("Given number is negative.");
} else {
[Link]("Given number is zero.");
};
4. The nested if statements:
JavaScript allows us to nest if statements within if statements. i.e, we can
place an if statement inside another if statement. A nested if is an if statement
that is the target of another if or else.
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 7
[Link]
JavaScript UNIT I
Syntax:
if condition1
{
// code to be executed if condition1 is
true
if condition2
{
// code to be executed if both condition1 and
condition2 are true
}
}
Example:
let i = 10;
if (i == 10) { // First if
statement if (i < 15) {
[Link]("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
[Link]("i is smaller than 12
too"); else
[Link]("i is greater than 15");
}
}
1.5 Getting Conformation From Users
JavaScript confirm method invokes a function that asks the user for a confirmation
dialogue on a particular action.
The confirm () method uses a window object to invoke a dialogue with a question and
two option buttons, OK and Cancel. If the user selects the OK option, it will continue
to the function execution; selecting the Cancel option will abort the block code's
execution.
It returns true if the user selects the OK option; otherwise, it returns false.
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 8
[Link]
JavaScript UNIT I
The JavaScript confirm () method is used to display a specific message on a dialogue
window with the OK and Cancel options to confirm the user action
It is used to accept or verify something.
It stops all the actions until the confirmation window is closed.
Syntax:
confirm(message);
Parameters: It takes a "message" value in string format to display in the confirmation dialogue
you want to show the user.
Return value: The confirm method returns a Boolean output, either true or false, if the OK is
selected. A boolean indicating whether OK (true) or Cancel (false) was selected. If a browser
ignores in-page dialogues, then the returned value is always false.
Example:
<html>
<head>
<script
type="text/javascript">
function show() {
alert("It is an Alert dialog box");
}
</script>
</head>
<body style="text-align: center;">
<h1 style="color:green;">
Welcome to NIIT Nanded
</h1>
<h2>
Window confirm() Method
</h2>
<p>Click the button to display a confirm box.</p>
<button onclick="callNiit()">Click me!</button>
<script>
function callNiit() {
confirm("Press OK to close this option");
}
</script>
</
body>
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 9
[Link]
JavaScript UNIT I
1.6 Creating Prompts For Users
The prompt() method in JavaScript is used to display a prompt box that prompts the
user for the input.
It is generally used to take the input from the user before entering the page.
It can be written without using the window prefix.
When the prompt box pops up, we have to click "OK" or "Cancel" to proceed.
The box is displayed using the prompt() method, which takes two arguments.
The first argument is the label which displays in the text box, and the second
argument is the default string, which displays in the textbox.
The prompt box consists of two buttons, OK and Cancel. It returns null or the string
entered by the user.
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 10
[Link]
JavaScript UNIT I
When the user clicks "OK," the box returns the input value. Otherwise, it returns null
on clicking "Cancel".
The prompt box takes the focus and forces the user to read the specified message. So,
it should avoid overusing this method because it stops the user from accessing the
other parts of the webpage until the box is closed.
Syntax:
prompt(message, default);
OR
[Link](message, default);
Message: is a string of text to display to the user. It can be omitted if there is nothing to
show in the prompt window i.e. it is optional.
Default: is a string containing the default value displayed in the text input field. It is also
optional.
Return value: The input value is returned if the user clicks the ‘OK’ button. If not so
then null is returned.
Example:
<html lang="en">
<head>
<title>Document</title>
</head>
<body style="text-align: center;">
<h1 style="color:green;"> NIIT Nanded </h1>
<h2> Window prompt() Method </h2>
<button onclick="callNiit()"> Click me </button>
<p id="g"></p>
<script>
function callNiit() {
let doc = prompt("Please enter some
text"); if (doc != null) {
[Link]("g").innerHTML ="Welcome to " +
doc;
}
}
</script>
</
body>
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 11
[Link]
JavaScript UNIT I
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 12
[Link]
JavaScript UNIT I
1.7 Understanding Functions
A function is the set of input statements, which performs specific computations and
produces output.
It is a block of code that is designed for performing a particular task. It is executed
when it gets invoked (or called).
Functions allow us to reuse and write the code in an organized way.
Functions in JavaScript are used to perform operations.
In JavaScript, functions are defined by using function keyword followed by a name
and parentheses ().
The function name may include digits, letters, dollar sign, and underscore.
The brackets in the function name may consist of the name of parameters separated by
commas.
The body of the function should be placed within curly braces {}.
function functionName(parameter1, parameter2, parameter3)
{
//code to be executed
}
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
Function Invocation:
The code inside the function will execute when "something" invokes (calls) the function:
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code
Automatically (self invoked)
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 13
[Link]
JavaScript UNIT I
Example:
<html>
<body style="text-align: center;">
<h1
style="color:green;">
NIIT Nanded
</h1>
<script>
function msg()
{
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute
the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to
the "caller":
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 14
[Link]
JavaScript UNIT I
Example:
<html>
<body style="text-align: center;">
<h1 style="color:green;">
NIIT Nanded
</h1>
<h2>
Return by Function
</h2>
<script>
function getInfo(number){
return number*number;
}
</script>
<script>
[Link](getInfo(3));
</script>
</body>
</html>
Arrow Function:
It is one of the most used and efficient methods to create a function in JavaScript because of
its comparatively easy implementation. It is a simplified as well as a more compact version of
a regular or normal function expression or syntax.
Syntax:
let function_name = (argument1, argument2 ,..) => expression
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 15
[Link]
JavaScript UNIT I
Example:
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];
const a2 = [Link](function
(s) { return [Link];
});
[Link]("Normal way ", a2); // [8, 6, 7,
9] const a3 = [Link]((s) => [Link]);
[Link]("Using Arrow Function ", a3); // [8, 6, 7, 9]
NANDIGRAM INSTITUTE OF INFORMATION TECHNOLOGY, NANDED 16
[Link]