[go: up one dir, main page]

0% found this document useful (0 votes)
19 views55 pages

Javascript - Unit 4 (1)

Unit IV covers the basics of JavaScript, including its applications, core concepts, and differences from Java. It discusses obtaining user input, memory concepts, data types, and operators, as well as how to structure JavaScript code within HTML. The unit emphasizes JavaScript's versatility and interactivity in web development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views55 pages

Javascript - Unit 4 (1)

Unit IV covers the basics of JavaScript, including its applications, core concepts, and differences from Java. It discusses obtaining user input, memory concepts, data types, and operators, as well as how to structure JavaScript code within HTML. The unit emphasizes JavaScript's versatility and interactivity in web development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

UNIT IV JAVASCRIPT BASICS

Introduction to Scripting – Obtaining user input – Memory Concepts –


Arithmetic – Decision Making: Equality and Relational Operators – JavaScript
Control Statements – Functions – Program Modules – Programmer-defined
functions – Scope rules – functions – Recursion – Arrays – Declaring and
Allocating Arrays – References and Reference Parameters – Passing Arrays to
Functions – Multidimensional arrays.

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 1


Introduction to Javascript
Javascript is a powerful programming language that can add interactivity to a website
Javascript is versatile, beginner-friendly, compact and very flexible

Applications created using core Javascript Language


a. Browser Application Programming Interfaces (API’s) built into web browsers, providing functionality such as
dynamically creating HTML and setting CSS styles; collecting and manipulating a video stream from user ‘s webcam, or
generating 3D graphics and audio samples
b. Third party API’s allow developers to incorporate functionality in sites from other content providers, such as
Twitter or Facebook (companies such as FB, Twitter or Google allow you to access their functionality via Javascript and use
it on your site)
c. Third party frameworks and libraries that you can apply to HTML to accelerate the work of building sites and
applications.

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 2


Javascript
Javascript is a cross-platform, object-oriented scripting languages used to make webpages interactive (eg. Having complex
animations, clickable buttons, popup menus etc.)

Core Javascript can be extended for a variety of purposes by supplementing it with additional objects.
a. Client side Javascript supply object to control the browser and its Document. For example, client side extensions
allow an application to place elements on an HTML form and respond to user events such as mouse clicks, form input and
page navigation. It is simply running scripts on the client device, usually within a browser.
b. Server side Javascript is relevant to running javascript on a server. For example, server side extensions allow an
application to communicate with a database, provide continuity of information from one invocation to another to the
application, or perform file manipulations on a server.
c. Imperative Language : It simply controls the flow of consumption. The source code is a series of commands which
specify what the computer has to do.
d. Declarative programming : Requirement of Logical Computation. Main goal is to describe the desired result
without direct dictation on how to get it.

Note:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 3


Javascript and Java

JavaScript Java

Object – oriented. No Distinction between types of Class-based.


objects.
Objects are divided into classes and instances with all
Inheritance is through the prototype mechanism, inheritance through the class hierarchy.

properties and methods can be added to any object Classes and instances cannot have properties or methods
dynamically added dynamically
Variable data types are not declared Variable data types must be declared

Cannot automatically write to hard disk Can automatically write to hard disk

Tryit:
https://www.w3schools.com/js/default.asp
UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 4
https://www.w3schools.com/js/js_intro.asp
Javascript can be added to your HTML file in two ways:
Internal JS: We can add Javascript directly to your HTML External JS: We can write JavaScript code in other file having
file by writing the code inside the <script> tag. The <script> an extension.js and then link this file inside the <head> tag of
tag can either be placed inside the <head> or the <body> the HTML file in which we want to add this code.
tag according to the requirement, but preferred in <head>
tag index.html
Index.html <!DOCTYPE html>
<!DOCTYPE html> <html>
<html> <head>
<head> <script type="text/javascript" src="script.js"></script>
<script> </head>
</script>
</head> <body>
<body> </body>
</body> </html>
</html>
script.js
<<Script code here …. >>
When to Use Internal and External JavaScript Code?
If you have only a few lines of code that is specific to a particular webpage, then it is better to keep your JavaScript code
internally within your HTML document.
On the other hand, if your JavaScript code is used in many web pages, then you should consider keeping your code in a
separate file. In that case, if you wish to make some changes to your code, you just have to change only one file which makes
code maintenance easy. If your code is too long, then also it is better to keep it in a separate file. This helps in easy debugging.
5
UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC
Obtaining users output in JavaScript
JavaScript can “output/display" data in different ways:

1) Writing the HTML output using document.write().


2) Writing into an HTML element, using innerHTML.
3) Writing into the browser console, using console.log() – eg. console.log(4+4);
4) window.alert() - Shows the message in a small message box – eg. window.alert(“wel to JS”);
5) window.status() - shows the message in the status bar – eg. window.status(“wel to JS”);

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 6


1) Writing into the HTML output using document.write()
For testing purposes, it is convenient to use document.write():
index.html
Index.html <!DOCTYPE html>
<!DOCTYPE html> <html>
<html> <head>
<head> <title>My First JavaScript</title>
<title>My First JavaScript</title> </head>
</head> <body>
<body> <h1>My First JavaScript</h1>
<h1>My First JavaScript</h1> <script type="text/javascript" src="script.js"></script>
<script> </body>
document.write('<p style="color:red;">web page</p>'); </html>
</script>
</body> script.js
</html> document.write("<p style='color:red;'>web page</p>");
Output: Output:

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 7


tryit: https://www.w3schools.com/js/js_whereto.asp
2) Writing into an HTML element, using innerHTML.
Using innerHTML
To access an HTML element, JavaScript can use the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the HTML content:
<!DOCTYPE html>
<html>
<body>

<h1>My First java Script</h1>


<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "web page";
</script>

</body>
</html>

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 8


Keywords are words with special meaning in JavaScript
Keyword var
Used to declare the names of variables
A variable is a location in the computer’s memory where a value can be stored for use by a script
All variables have a name, type and value, and should be declared with a var statement before they are used in a script
A variable name can be any valid identifier consisting of letters, digits, underscores ( _ ) and dollar signs ($) that does not
begin with a digit and is not a reserved JavaScript keyword.

difference between var, let, and const in javascript


<script>
// for var - redeclare, and can update also
var num2=10;
var num2=100; //redeclare
num2=1000; //update
document.write(num2+"<br>");

// for let – no redeclare and can update


let num1=20;
//let num1=200; //no redeclare
num1=2000; //update
document.write(num1+"<br>");

//for const – no redeclare and no update OUTPUT


const num3=30;
//const num3=300; //no redeclare 1000
//num3=3000 //no update
document.write(num3+"<br>");
2000
30
</script> UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 9
Obtaining User Input in JavaScript
Ways of obtaining user input in JavaScript, by using prompt() or confirm() function
1) We use the prompt() function to ask the user for input.
The prompt() gathers information from the user before the page is loaded.
This prompt box asks for a choice between “OK” and “Cancel”
The prompt() accepts two parameters, is used to show the message box.
Syntax
prompt(text, defaultText)
Eg: var name = prompt(“Please enter your name”);
var num = prompt(“please enter your favorite number?”);
The prompt() function displays a dialog box that prompts the user
for input
The prompt() function returns the input value if the user clicks “OK”,
otherwise it return null
<!DOCTYPE html>
<html>
<head>
<h1>The Window Object</h1>
<h2>The prompt() Method</h2>
<script>
let person = prompt("Please enter your name", "Jim");
if (person != null) {
document.writeln("Hello " + person + " using writeln?")
}
</script>
</head> UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 10
<body></body>
2) The window.confirm() method in JavaScript is used to display a dialog box with a specified message, along with "OK" and
"Cancel" buttons. This method pauses the execution of the script and waits for the user's response.
It returns: true if the user clicks "OK“, false if the user clicks "Cancel"

Syntax:
window.confirm(message);
message: The text to display in the dialog box.

<script>
// Display a confirm dialog box
var result = window.confirm("Do you want to
continue?");

// Check user's response


if (result) {
alert("You clicked OK!");
} else {
alert("You clicked Cancel!");
}
</script>

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 11


Datatypes in JavaScript

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 12


Comments
A single-line comment begins with the characters // and terminates at the end of the line
Comments do not cause the browser to perform any action when the script is interpreted;
rather, comments are ignored by the JavaScript interpreter
Multiline comments begin with delimiter /* and end with delimiter *
All text between the delimiters of the comment is ignored by the interpreter.

null keyword
Signifies that a variable has no value
null is not a string literal, but rather a predefined term indicating the absence of value
Writing a null value to the document, however, displays the word “null”

Function parseInt
converts its string argument to an integer
JavaScript has a version of the + operator for string concatenation that enables a string and a
value of another data type (including another string) to be concatenated

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 13


Memory Concepts
JavaScript does not require variables to have a type before they can be used in a script
A variable in JavaScript can contain a value of any data type, and in many situations,
JavaScript automatically converts between values of different types for you
JavaScript is referred to as a loosely typed language
When a variable is declared in JavaScript, but is not given a value, it has an undefined
value.
Attempting to use the value of such a variable is normally a logic error.
When variables are declared, they are not assigned default values, unless specified
otherwise by the programmer.
To indicate that a variable does not contain a value, you can assign the value null to it.

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 14


Memory Management
Javascript Engine have two places to store data:
1. Stack
2. Heap

Stack : It is a data structure used to store static(fixed) data. Static data refers to data whose size is known by the engine during
compile time. In Javascript, static data includes primitive values like strings, numbers, Boolean, null and undefined.
References that point to objects and functions are also included. A fixed amount of memory is allocated for static data. This
process is known as static memory allocation.
Heap : It is used to store objects and functions in Javascript. The engine doesn’t allocate a fixed amount of memory
instead, allocated more space as required.

Stack and Heap Memory


Stack Heap
Primitive data types and references Objects and functions
Size is known at compile time Size is known at run time
Fixed memory allocated No Limit for object memory

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 15


1) object person, numperson, hobbies 3) newPerson=null

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 16


2) person=null 4) Hobbies only in heap
About let
https://www.w3schools.com/js/js_let.asp

About comments
https://www.w3schools.com/js/js_comments.asp

About JS Syntax
https://www.w3schools.com/js/js_syntax.asp

About variables
https://www.w3schools.com/js/js_variables.asp

About datatypes
https://www.w3schools.com/js/js_datatypes.asp

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 24


Operators and Types of Operators
(Arithmetic – Decision Making: Equality and Relational Operators)

Operators
Operators are used to performing specific mathematical and logical computations on operands. In other words, we can
say that an operator operates the operands. In JavaScript, operators are used to compare values, perform operations, etc

Types of Operators
1. Arithmetic Operators
2. Comparison Operators (Decision Making: Equality and Relational Operators)
3. Assignment Operators
4. Logical Operators
5. Conditional/Ternary Operators
6. Type Operators

Tryit:
https://www.w3schools.com/js/js_operators.asp
UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 25
Arithmetic Operators
The basic arithmetic operators (+, -, *, /, and %) are binary operators,
because they each operate on two operands
JavaScript provides the remainder operator, %, which yields the
remainder after division
Arithmetic expressions in JavaScript must be written in straight-line form
to facilitate entering programs into the computer

Comparison Operators - (Decision Making: Equality and Relational Operators)


 if statement allows a script to make a decision based on the truth
or falsity of a condition
If the condition is met (i.e., the condition is true), the statement
in the body of the if statement is executed
If the condition is not met (i.e., the condition is false), the
statement in the body of the if statement is not executed
 Conditions in if statements can be formed by using the equality
operators and relational operators
 Equality operators both (==, !==) have the same level of precedence,
which is lower than the precedence of the relational operators.
The equality operators associate from left to right.

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 26


Assignment Operators Logical Operators
The assignment operators are used to assign values to the The Logical operator return either True or False deponding
variable. upon the expression,its commonly used in decision making

Conditional (Ternary) Operator


The conditional operator assigns a value
The typeof Operator
The typeof operator returns the type of a variable, object, to a variable based on a condition.
function or expression:
Example Syntax Example
typeof "John" // Returns string
(condition) ? x : y (z < 18) ? x : y
typeof 3.14 // Returns number

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 27


Operators Example:
<!-- HTML document contains embedded JavaScript code that uses the // Comparison operators
document.write method to display the results of various let a = 5;
operators on a web page--> let b = 10;
document.write("<h2>Comparison Operators:</h2>");
<!DOCTYPE html> document.write("Equal (a == b): " + (a == b) + "<br>");
<html> document.write("Not Equal (a != b): " + (a != b) + "<br>");
<head> document.write("Greater than (a > b): " + (a > b) + "<br>");
<title>JavaScript Operators Example</title> document.write("Less than or equal (a <= b): " + (a <= b) + "<br>");
</head>
<body> // Logical operators
<script> let isTrue = true;
// Arithmetic operators let isFalse = false;
let num1 = 10; document.write("<h2>Logical Operators:</h2>");
let num2 = 5; document.write("Logical AND (isTrue && isFalse): " + (isTrue &&
isFalse) + "<br>");
document.write("<h2>Arithmetic Operators:</h2>"); document.write("Logical OR (isTrue || isFalse): " + (isTrue || isFalse) +
document.write("Addition: " + (num1 + num2) + "<br>"); "<br>");
document.write("Multiplication: " + (num1 * num2) + "<br>"); document.write("Logical NOT (!isTrue): " + (!isTrue) + "<br>");
document.write("Modulus: " + (num1 % num2) + "<br>");

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 28


// Assignment operators // Conditional (Ternary) operator
let x = 5;
document.write("<h2>Assignment Operators:</h2>"); let isEven = x % 2 === 0 ? "Even" : "Odd";
document.write("Assignment (=) x = " + x + "<br>"); document.write("<h2>Conditional (Ternary) Operator:</h2>");
x += 3; document.write("Is x even or odd? " +x+" " +isEven + "<br>");
document.write("Add and assign (+=) x = " + x + "<br>"); </script>
x *= 4; </body>
document.write("Multiply and assign (*=) x = " + x + "<br>"); </html>

// Increment and Decrement operators


let count = 0;

document.write("<h2>Increment and Decrement Operators:</h2>");


document.write("Initial count: " + count + "<br>");
count++;
document.write("After decrement (count--): " + count + "<br>");
--count;
document.write("After pre-decrement (--count): " + count + "<br>");

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 29


Output:

Arithmetic Operators:
Addition: 15 Increment and Decrement Operators:
Multiplication: 50
Modulus: 0 Initial count: 0
After decrement (count--): 1
Comparison Operators: After pre-decrement (--count): 0
Equal (a == b): false Conditional (Ternary) Operator:
Not Equal (a != b): true
Greater than (a > b): false Is x even or odd? 32 Even
Less than or equal (a <= b): true
Logical Operators:
Logical AND (isTrue && isFalse): false
Logical OR (isTrue || isFalse): true
Logical NOT (!isTrue): false
Assignment Operators:
Assignment (=) x = 5
Add and assign (+=) x = 8
Multiply and assign (*=) x = 32

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 30


CONTROL STATEMENTS
JavaScript Control Statements also known as Control Structures or Flow Control statements are statements which decide
the execution flow of the program. Typically the program execution begins from the first line in the to the last line of that JS
code. However, in between this the flow of the execution can be branched(based on some condtion) or re-iterated(loops) based
on some criterias. This the functionality that is provided by Control Statements in JavaScript.
They are mainly categorized in 2 types –
Conditional Control Statements
Whenever a condition is to be tested depending on which particular tasks are to be performed, Conditional control
statements are used.
Looping / Iterative Control Statements
Whenever a particular task has to be iterated for a particular number of times or depending on some condition, Looping
control statements are used.
Apart from these we have 2 miscellaneous statements as – break and continue which assist in the flow controlling mechanism.

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 31


Conditional Control Statements
Conditional statements are used to perform different actions based on various conditions
The conditional statement evaluates a condition before the execution of instructions

If Statement If – Else Statement


IF statement is a conditional branching statement. If – Else is a two-way decision statement.
In 'IF' statement, if the condition is true a group of It is used to make decisions and execute statements
statement is executed. And if the condition is false, the conditionally.
following statement is skipped. Syntax : If-Else statement
if (condition)
Syntax : If statement {
if(condition) //Statement 1;
{ }
//Statement 1; else if(condition)
//Statement 2; {
} //Statement 2;
}
else
{
//Statement 3;
}
Tryit:
https://www.w3schools.com/js/js_if_else.asp
UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC https://www.w3schools.com/js/js_switch.asp 32
Switch Statement For Loop
Switch is used to perform different actions on different For loop is a compact form of looping.
conditions. It is used to compare the same expression to It includes three important parts:
several different values. 1. Loop Initialization
Syntax 2. Test Condition
switch(expression) 3. Iteration
{ All these three parts come in a single line separated by
case condition 1: semicolons(;).
//Statements; Syntax
break; for(initialization; test-condition; increment/decrement)
… {
case condition n: //Statements;
//Statements; }
break;
default: For-in Loop
//Statement; For-in loop is used to traverse all the properties of an object.
} It is designed for looping through arrays. The code block inside
the loop is executed once for each property.
Syntax
for (variable_name in Object)
{
//Statements;
}
33
UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC
While Loop Do-While Loop
While loop is an entry/counter-controlled loop statement. Do-While loop is an exit-controlled loop statement.
It is the most basic loop in JavaScript. Similar to the While loop, the only difference is condition will
It executes a statement repeatedly as long as expression is be checked at the end of the loop.
true. The loop is executed at least once, even if the condition is false.
Once the expression becomes false, the loop terminates.
Syntax
Syntax do
while (condition) {
{ //Statements;
//Statements; }
} while(condition);

Continue Statement
Break Statement Continue statement causes the loop to continue with the next
Break statement is used to jump out of a loop. iteration.
It is used to exit a loop early, breaking out of the It skips the remaining code block.
enclosing curly braces.
Syntax: Syntax:
break; continue;

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 34


examples of control statements in JavaScript

<!DOCTYPE html> //Switch Statement:


<html> document.write("<h2>Switch statements:</h2>");
<head>
<title>JavaScript control statements Example</title> let day = "Monday";
</head>
<body> switch (day) {
<script> case "Monday":
document.writeln("It's the start of the workweek."+ "<br>");
//If Statement: break;
document.write("<h2>if else statements:</h2>"); case "Friday":
let x = 10; document.writeln("It's almost the weekend!"+ "<br>");
break;
if (x > 5) { default:
document.writeln("x is greater than 5"); document.writeln("It's a regular day."+ "<br>");
} else { }
document.writeln("x is not greater than 5");
} //For Loop:
document.write("<h2>For Loop statements:</h2>");
for (let i = 0; i < 5; i++) {
document.writeln("Iteration " + i+ "<br>");
}

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 35


//for in loop:
const cars = ["BMW", "Volvo", "Saab", "Ford"];
let text = "";
for (let x in cars) { //Break and Continue Statements:
text += cars[x] + " "; document.write("<h2>Break statements:</h2>");
} for (let i = 0; i < 5; i++) {
document.write(text); if (i === 2) {
break; // exit the loop when i equals 5
//While Loop: }
document.write("<h2>Whilte Loop statements:</h2>"); document.writeln("Value of i: " + i+ "<br>");
let count = 0; }
while (count < 3) { document.write("<h2>continue statements:</h2>");
document.writeln("Count: " + count+ "<br>"); for (let i = 0; i < 5; i++) {
count++; if (i === 2) {
} continue; // skip iteration when i equals 2
}
//Do...While Loop: document.writeln("Value of i: " + i+ "<br>");
document.write("<h2>Do...While Loop statements:</h2>"); }
let i = 0;
do { </script>
document.writeln(i+" This will run at least once."+ "<br>"); </body>
i++; </html>
} while (i < 3); UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 36
Output:

if else statements: Break statements:


x is greater than 5Switch statements: Value of i: 0
Value of i: 1
It's the start of the workweek. continue statements:
For Loop statements:
Value of i: 0
Iteration 0 Value of i: 1
Iteration 1 Value of i: 3
Iteration 2 Value of i: 4
Iteration 3
Iteration 4
For in Loop statements:
BMW Volvo Saab FordWhilte Loop statements:
Count: 0
Count: 1
Count: 2
Do...While Loop statements:
0 This will run at least once.
1 This will run at least once.
2 This will run at least once.

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 37


Difference between While Loop and Do – While Loop

While Loop Do – While Loop


In while loop, first it checks the condition and then In Do – While loop, first it executes the program and
executes the program. then checks the condition.
It is an entry – controlled loop. It is an exit – controlled loop.
The condition will come before the body. The condition will come after the body.
It runs at least once, even though the conditional is
If the condition is false, then it terminates the loop.
false.
It is a counter-controlled loop. It is a iterative control loop

https://www.w3schools.com/js/js_loop_for.asp
https://www.w3schools.com/js/js_loop_while.asp
UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 38
https://www.w3schools.com/js/js_break.asp
Functions in Javascript - Why Functions?
You can reuse code : Define the code once, and uses it many times
You can use the same code many times with different arguments, to produce different results.

Functions are a block of code designed to perform a particular task.


A Javascript function is executed when ‘something’ invokes it or calls it.

There are two types of functions. They are:

1. User Defined Functions


User-defined functions in JavaScript are defined by the programmer to perform specific operations. They are also known as
“tailor-made functions” which are built only to satisfy the given condition.

2. Predefined Functions
PREDEFINED/BUILT-IN functions are methods whose definition is already defined in the objects of JavaScript. More Formally, the
programmer sends a message to the Objects in the JavaScript to run its methods.

Tryit:
39
UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC https://www.w3schools.com/js/js_functions.asp
1. User Defined Functions(UDF)/ Programmer-defined functions
Function Definition
A Javascript function is defined with the ‘function’ keyword, followed by a name, followed by parentheses().
Function name can contain letters, digits, underscores and dollar signs, The parentheses may include parameter names separated
by commas: (parameter1, parameter2,……), The code to be executed, by the function, is placed inside curly brackets: {}
Syntax:
function fnname(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 behave as local variables.
Function Call/ 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)
Function arguments are listed inside the parentheses () in the function call. These values
are received by the function definition when it is invoked.
Syntax:
fnname(argument1, argument2);
UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 40
Returning Program Control from a Function Definition:
There are three ways to return control to the point at which a function was invoked.
If the function does not return a result, control returns when the program reaches the function-ending right brace
or by executing the statement
return;
If the function does return a result, the statement
return expression;
returns the value of expression to the caller. When a return statement is executed, control returns immediately to
the point at which the function was invoked.

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 41


There are 3 ways of writing a function in JavaScript:
a. Function Declaration
b. Function Expression
c. Arrow Function
a. Function Declaration: Function b. Function Expression: Function
Declaration is the traditional way to define a Expression is another way to define a
c. Arrow Functions: Arrow functions
function. It is somehow similar to the way we function in JavaScript. Here we define a
function using a variable and store the are been introduced in the ES6
define a function in other programming
returned value in that variable. version of JavaScript. It is used to
languages. We start declaring using the
keyword “function”. Then we write the Here, the whole function is an shorten the code. Here we do not use
function name and then parameters. expression and the returned value is the “function” keyword and use the
After defining a function, we call it stored in the variable. We use the arrow symbol
whenever the function is required. variable name to call the function

<script>
<script> <script>
// Function declaration
// Function Expression // Single line of code
function add(a, b) {
const add = function(a, b) {
document.writeln(a + b);
document.writeln(a+b); let add = (a, b) => a + b;
}
}
// Calling a function
// Calling function document.writeln(add(2, 3));
add(2, 3);
add(2, 3); </script>
</script>
</script>
OUTPUT: OUTPUT: OUTPUT:
5 5 5
UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 42
2. Pre-defined / Built-in functions
Built in functions are methods whose definition is already defined in the objects of JavaScript. More Formally, the programmer sends a message to the Objects in the
JavaScript to run its methods.
Syntax: objectname.functionname(arguments);

Methods in “String” Object


Sl. Method Return Value
No Name
1. length() Returns the length of the string. str=“STR”; str.length is 3
2. slice() Extracts a section of a string and returns a new string. str="Apples are round, and apples are juicy";
document.write(str.slice(3,-2)); //Output: les are round, and apples are jui
3. split() Splits a String object into an array of strings by separating the str="Apples are round, and apples are juicy";
string into substrings. document.write(str.split(" ", 3)); //Output: Apples,are,round,
4. toLowerCase() Returns the calling string value converted to lower case. str="Apples are round, and apples are juicy";
toUpperCase() Returns the calling string value converted to Upper case. document.write(str.toLowerCase( )); //Output: apples are round, and apples are juicy
6. concat() Combines the text of two strings and returns a new string. str1="Apples are round, " ; str2="and apples are juicy";
document.write(str1.concat(str2)); //Output: Apples are round, and apples are juicy
7. indexOf() Returns the index within the calling String object of str1="Apples are round, " ;
the first occurrence of the specified value, or -1 if not found. document.write(str1.indexOf("string")); // Output: -1
8. charAt() Returns the character at the specified index. str1="Apples are round, " ;
document.write(str1.charAt(0)); // Output: A
9. sort() The sort() method is used to sort the elements of an array. By const fruits = ["Banana", "Orange", "apple", "Apple", "Mango"];
default, it converts elements to strings and sorts them document.write("sorted array"+"<br>");
lexicographically. fruits.sort();
document.write(fruits+"<br>"); //OUTPUT: Apple,Banana,Mango,Orange,apple
document.write("reversed sorted array"+"<br>");
fruits.reverse();
document.write(fruits); //OUTPUT: apple,Orange,Mango,Banana,Apple

10 find() If you're working with an array of strings or objects, the find() const words = ["apple", "banana", "cherry"];
method can locate the first element that matches a given condition. const result = words.find(word => word.startsWith("b"));
document.write(result); // Output: "banana"

43
Methods in “Number” Object:
Sl.N Method Return Value var num = 177.1234;
o Name
1. toFixed() Formats a number with a specific number of digits, to right of decimal to var num = 177.1234; num.toFixed(6)) is 177.123400
the right of the decimal.
2. toString() Returns the string representation of the number's value. var num = 177.1234; num.toString() is 177.1234
3. valueOf() Returns the number's value. var flag = new Boolean(false); flag.valueOf is : false
4. sort() The sort() method is used to sort the elements of an array. By default, it converts let numbers = [4, 1, 10, 2, 8];
elements to strings and sorts them lexicographically. numbers.sort();
document.write(numbers); // Output: [1, 10, 2, 4, 8] (lexicographic sorting)
To sort numerically, provide a comparison function
the arrow function (a, b) => a - b acts as the comparison function for numeric Let numbers = [4, 1, 10, 2, 8];
sorting. numbers.sort((a, b) => a - b); // Ascending orde
document.write(numbers+"<br/>"); // Output: [1, 2, 4, 8, 10]
numbers.sort((a, b) => b - a); // Descending orde
document.write(numbers); // Output: [10, 8, 4, 2, 1]
5. find() Finds/search the first element that satisfies a condition. let numbers = [10, 20, 30, 40, 50];
findIndex() find index of the first element that satisfies the condition let result = numbers.find(num => num == 30);
//let result = numbers.find(num => num >30);
document.write(result); //OUTPUT: 30
const index = numbers.indexOf(30);
document.write(index); //OUTPUT: 2 (index of 30 is 2)

Methods in “String HTML wrappers” Object


Sl.No Method Name Return Value
1. fontcolor() Causes a string to be displayed in the specified str1="Apples are round, " ; document.write(str1.fontcolor("red"));
color as if it were in a <font color="color"> tag. Apples are round, - in red color
2. fontsize() Causes a string to be displayed in the specified font str1="Apples are round, " ; document.write(str1.fontsize( 3 ));
size as if it were in a <font size="size"> tag. Apples are round, - in size of 3
3. link() Creates an HTML hypertext link that requests str1="Apples are round, " ;
another URL. document.write(str1.link("http://www.google.com")); Apples are round,
5. bold() Creates a string to be displayed as bold as if it were in a <b> tag. str1="Apples are round, " ; document.write(str1.bold());
italics() Causes a string to be italic, as if it were in an <i> tag str1="Apples are round, " ; document.write(str1.italics());
Apples are round, - inbold, Apples are round, -in italic
44
Conversion and Comparison
Sl.No Method Return Value
Name
1. eval() Converts a string to integer or float value. str1="4*2" ; document.write(eval(str)); -> as 8
2. isNaN(value) If the value passed is a not a number, return true, if number, returns false. num1=4 ; document.write(isNaN(num)); -> as false
3. parseInt() Converts a string to an integer returning the first integer encountered which str1="4" ; document.write(parseInt(str)); ->as 4
is contained in the string. If no integer value, then a value of 0 is returned.

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 45


Modules
A module is a function or group of similar functions. They are grouped together within a file and contain the
code to execute a specific task when called into a larger application.

You create modules to better organize and structure your codebase. You can use them to break down large
programs into smaller, more manageable and more independent chunks of code which carry out a single or a
couple of related tasks.

Modules should be:

1. Independent/Self-contained : A module has to be as detached from other dependencies as possible

2. Specific : A module needs to be able to perform a single or a related group of tasks. The core essence of
creating them in the first place is to create separate functionalities. One module, one task

3. Reusable : A modules has to be easy to integrate into various kinds of programs to perform its task

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 46


Javascript Modules
A module in Javascript is just a file containing related code. In Javascript, we use the import and export keywords to share and
receive functionalities respectively across different modules.
The export keyword is used to make a variable, function, class or object accessible to other modules. It is a public code.
The import keyword is used to bring in public code from another module.

JavaScript modules allow you to break up your code into separate files. This makes it easier to maintain a code-base.
Modules are imported from external files with the import statement. Modules also rely on type="module" in the <script> tag.

Example - Modules
<!DOCTYPE html> person.js
<html> const name ="Jesse";
<body> const age =40;
<h1>JavaScript Modules</h1> export {name, age};
<p id="demo" style="color:red;"></p>
<script type="module">
import { name, age } from "./person.js"; OUTPUT:
let text = "My name is "+ name + ", I am " + age + ".";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 47
Function Scope
Scope determines the accessibility (visibility) of variables.
There are two types of Scope for any variable or a function in a program. They are:
Global Scope
Local Scope

Local Scope:
Javascript has function scope : Each function creates a new scope
Variables defined inside a function are not accessible from outside the function
Variables declared with var, let and const are quite similar when declared inside a function
Variables declared within a JavaScript function, become LOCAL to the function.

Global Scope:
A variable declared outside a function, becomes GLOBAL.
Variables declared Globally have Global Scope.
Global Variables can be accessed from anywhere in a Javascript program
Variables declared with var, let and const are quite similar when declared outside a block.

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 48


<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>

<h2>JavaScript Local Scope</h2> <h2>JavaScript Global Scope</h2>

<p><b>carName</b> is undefined outside myFunction():</p> <p>A GLOBAL variable can be accessed from any script or function.</p>

<script> <script>
myFunction(); let carName = "Volvo";
function myFunction() { myFunction();
let carName = "Volvo"; function myFunction() {
document.writeln(typeof carName + " " + carName+"<br>"); document.writeln(typeof carName + " " + carName+"<br>");
} }
document.writeln(typeof carName); document.writeln(typeof carName);
</script> </script>
</body> </body>
</html> </html>

OUTPUT OUTPUT
JavaScript Local Scope JavaScript Global Scope
local variable carName is undefined outside myFunction(): A GLOBAL variable can be accessed from any script or function.
string Volvo string Volvo
undefined string 49
UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC
Recursion
Recursion simply means a function that calls itself.
We use conditions to stop the recursive function calls, once we are done with the task. These conditions are
called Base Cases.
Example – recursive function
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript recursive Functions</h2>


<p>calls a function for calculation, returns the recursive result:</p>
<p id="demo"></p>
<script>
var x = factorial(3);
document.writeln(x);

// program to find the factorial of a number


function factorial(x) { OUTPUT:
// if number is 0
if (x === 0) {
return 1;
} // if number is positive
else if (x > 0) {
return x * factorial(x - 1);
}
}
</script>
</body>
</html> UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 50
Arrays
JavaScript array is an object that represents a collection of similar type of elements.

Characteristics of an Array:
JavaScript arrays are resizable and can contain a mix of different data types.
JavaScript arrays are zero-indexed: the first element of an array is at index 0, the second is at index 1, and so on — and the last
element is at the value of the array's length property minus 1.
The length property returns the length of an array.

Declaring and Allocating Arrays


There are three ways of declaring an array:
Type1-By array literal
Type2-By creating instance of Array directly (using new keyword)
Type3-By using an Array constructor (using new keyword)

Note:
New keyword in javascript - used to create an empty object;
A constructor is a special function that creates and initializes an object instance of a class.
In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a
constructor is to create a new object and set values for any existing object properties.

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 51


Type1 - JavaScript array literal: Type2- JavaScript Array directly (new Type3- JavaScript array constructor (new
The syntax of creating array using array keyword) keyword)
literal is given below: The syntax of creating array directly is Here, you need to create instance of
var arrayname=[value1,value2,…,valueN]; given below: array by passing arguments in
As you can see, values are contained inside var arrayname=new Array(); constructor so that we don't have to
[ ] and separated by , (comma). Here, new keyword is used to create provide value explicitly
instance of array

52
Example – To sort array of elements
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Sort</h2>
<p>The sort() method sorts an array alphabetically:</p>

<script>
const fruits = ["Banana", "Orange", "apple", "Apple", "Mango"];
//const fruits = [1,5,2,4]; //(only lexicographic sorting for single digit number)

document.write("original array"+"<br>");
document.write(fruits+"<br>");

document.write("sorted array"+"<br>"); JavaScript Array Sort


fruits.sort(); The sort() method sorts an array alphabetically:
document.write(fruits+"<br>"); original array
Banana,Orange,apple,Apple,Mango
document.write("reversed sorted array"+"<br>"); sorted array
fruits.reverse(); Apple,Banana,Mango,Orange,apple
document.write(fruits); reversed sorted array
</script> apple,Orange,Mango,Banana,Apple
</body>
</html> UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 53
References
The typeof value assigned to a variable decides whether the value is stored with assign-by-value or assign-by-reference
On variable assignment, the scalar primitive values (Number, String, Boolean, undefined, null, Symbol) are assigned-by-
value and compound values are assigned-by-reference.

Compound data types are made up of more than one component. Two primitive data types such as 10 multiplied by 7, can make
up compound data.
The references in Javascript only point at contained values and NOT at other variables, or references
In Javascript, scalar primitive values are immutable(cannot be altered) and compound values are mutable

Call by value
Pass by value in JavaScript means that a copy of the actual parameter’s value is made in memory i.e., a new memory allocation
is done, and all the changes are made in that new value (i.e., copied value).
The original value and the copied value are independent of each other as they both have a different space in memory i.e., on
changing the value inside the function, the variable outside the function is not affected.

Call by reference
Unlike pass by value in JavaScript, pass by reference in JavaScript does not create a new space in the memory, instead, we pass
the reference/address of the actual parameter, which means the function can access the original value of the variable. Thus, if
we change the value of the variable inside, then the original value also gets changed
It does not create a copy, instead, it works on the original variable, so all the changes made inside the function affect the original
variable as well
UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 54
Example – Assign by value, Assign by reference using function
Call by value Callby by reference/ References and Reference Parameters

<!DOCTYPE html> <!DOCTYPE html>


<html> <html>
<body> <body>
<h2>call by value using function</h2> <h2>call by reference using function</h2>
<script> <script>
var originalArr = 8; var originalArr = [8,8,8];
document.write("original"+originalArr+"<br>"); document.write("original "+originalArr+"<br>");
pushArray(originalArr); pushArray(originalArr);
document.write("in main"+originalArr+"<br>"); document.write("in main"+originalArr+"<br>");
function pushArray(originalArr)
{ function pushArray(originalArr)
originalArr++; {
document.write("in Function"+originalArr+"<br>"); originalArr.push(0);
} document.write("in Function"+originalArr+"<br>");
</script> }
</body> </script>
</html> </body>
</html>

call by value using function call by reference using function


original8 original 8,8,8
in Function9 in Function8,8,8,0
in main8 in main8,8,8,0 55
Passing Array to Functions
We can pass an array as an input to a function using the following 3 ways.
Arguments Object Apply() Method Spread Operator:
Apply() method The apply() method executes a function with The spread syntax is used in place where zero
Spread Operator this value and gives arguments as an array or or more arguments are expected. It can be
array-like object. used with iterators that expands in place
Argument Object: It is used on a particular function that has to be where there may not be a fixed number of
expected arguments (like function
In the below example we use the passed
In the apply() method this value is the first parameters).
arguments object to pass the names The required function is called as given the
parameter that calls to the function, and
array to displyName() function. We can arguments are the second with the array of arguments array using the spread syntax so
pass the entire array to the function as arguments to be passed that it would fill in the arguments of the
function from the array.
an argument to simplify the code.
Example:

57
UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC
Multidimenstional Arrays
Multidimensional arrays are not directly provided in JavaScript.

If we want to use anything which acts as a multidimensional array then we need to create a multidimensional
array by using another one-dimensional array. Multidimensional arrays are arrays inside another array.

Method 1:
var arr1 = ["ABC", 24, 18000];
var arr2 = ["EFG", 30, 30000];
var arr3 = ["IJK", 28, 41000];
var arr4 = ["EFG", 31, 28000];
var arr5 = ["EFG", 29, 35000];
// "salary" defines like a 1D array but it already contains some 1D array
var salary = [arr1, arr2, arr3, arr4, arr5];

Method 2:
var salary = [
["ABC", 24, 18000],
["EFG", 30, 30000],
["IJK", 28, 41000],
["EFG", 31, 28000],
];
UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 58
Example - Multidimensional Arrays
Example:
<script>
// Prints a simple multidimensional array in JavaScript
// where we just print the salary of a specific person
var salary = [
["ABC", 24, 18000],
["EFG", 30, 30000],
["IJK", 28, 41000],
["EFG", 31, 28000],
];
document.write("salary of 2nd person : " + salary[1][2] + "<br>");
document.write("salary of 4th person : " + salary[3][2] + "<br>");
</script>

Output:
salary of 2nd person : 30000
salary of 4th person : 28000

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 59


Assignment JS Programs:
Create a JavaScript program to perform factorial calculation with a recursive function.
Write a JS code to find the minimum and maximum element in an array. 10, 30, 40, 20, 60, 50 Output: Max = 60 Min=10
Write a JavaScript and display the output: to reverse the given number , to print whether the number is positive, negative or
zero.
Write a JS code to print all Armstrong numbers in an interval of 1 to 1000.
Create a simple calculator using the JavaScript functions to perform addition, subtraction, multiplication, division.
Write a JavaScript function to get the first and last element of an array.

<script>
// Array
let s = [3, 2, 3, 4, 5];
// Storing the first item in a variable
let f = s[0];
// Storing the last item
let l = s[s.length - 1];
document.write(f+" "+l); OUTPUT
</script>
35

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 60


ONE SINGLE PROGRAM FOR Write a JS code to SORT the elements, minimum and maximum element in an array,
FIND/SEARCH specific element in an array
<script>
let numbers = [4, 1, 10, 2, 8]; // Array of numbers

// Sort the array


document.write("Sort the array"+"<br/>")
numbers.sort((a, b) => a - b); // using comparison arrow operator
document.write("Sorted array:", numbers +"<br/>"); // [1, 2, 4, 8, 10]

// Find Min and Max values


document.write("Find Min and Max values"+"<br/>")
const min = Math.min(...numbers); // using spread operator
const max = Math.max(...numbers);
document.write("Min value:", min+"<br/>"); // 1
document.write("Max value:", max+"<br/>"); //10 OUTPUT:
// find/search for 10 exists in the array
document.write("Find element 10<br/>"); Sort the array
//indexOf()` to find the index, index found->element found, index not found->return -1 Sorted array:1,2,4,8,10
const indexoften = numbers.indexOf(10);
if (indexoften == -1) {
document.write("10 not found in the array."); Find Min and Max values
} else { Min value:1
document.write("Element found, Index of 10: " + indexoften); // indexoften is 2 Max value:10
}

</script> Find element 10


Element found, Index of 10: 4
UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 61
Write a JS code to find the minimum and maximum element in an array without using build in function

<html>
<body>
<p>The original array: [28, 45, 69, 20, 15, 7, 98]</p>
<script>
let array = [28, 45, 69, 20, 15, 7, 98];
let min = max = array[0];
for (let i = 1; i < array.length; i++) {
if (array[i] > max)
max = array[i];
else if (array[i] < min)
min = array[i];
}
document.write( "The max element: " + max + "<br>" + "The min element: " + min);
Output:
</script>
The original array: [28, 45, 69, 20, 15, 7, 98]
</body>
The max element of the array is: 98
</html> The min element of the array is: 7

UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC 62


<!-- Create a simple Program to build the Calculator in JavaScript using with HTML and CSS <input type = "button" value = "3" onclick = "form1.answer.value += '3' ">
web languages. --> <input type = "button" value = "+" onclick = "form1.answer.value += '+' ">
<!DOCTYPE html> <br> <br>
<head> <input type = "button" value = "4" onclick = "form1.answer.value += '4' ">
<title> JavaScript Calculator </title> <input type = "button" value = "5" onclick = "form1.answer.value += '5' ">
<style> <input type = "button" value = "6" onclick = "form1.answer.value += '6' ">
#clear{ <input type = "button" value = "-" onclick = "form1.answer.value += '-' ">
width: 100px; <br><br>
padding: 6px; <input type = "button" value = "7" onclick = "form1.answer.value += '7' ">
background-color: red; <input type = "button" value = "8" onclick = "form1.answer.value += '8' ">
} <input type = "button" value = "9" onclick = "form1.answer.value += '9' ">
input { <input type = "button" value = "*" onclick = "form1.answer.value += '*' ">
width: 20px; <br> <br>
background-color: green;
color: white; <input type = "button" value = "/" onclick = "form1.answer.value += '/' ">
padding: 6px; <input type = "button" value = "0" onclick = "form1.answer.value += '0' ">
} <input type = "button" value = "." onclick = "form1.answer.value += '.' ">
<!-- When we click on the '=' button, the onclick() shows the sum results on the calculator
#calc{ screen. -->
width: 100px; <input type = "button" value = "=" onclick = "form1.answer.value = eval(form1.answer.value)
padding: 6x; ">
} <br>
</style> <!-- Display the Cancel button and erase all data entered by the user. -->
<input type = "button" value = "Clear All" onclick = "form1.answer.value = ' ' " id= "clear" >
</head> <br>
<body>
<h1> Calculator Program in JavaScript </h1> </form>
<div class= "formstyle"> </div>
<form name = "form1"> </body>
<!-- This input box shows the button pressed by the user in calculator. --> </html>
<input id = "calc" type ="text" name = "answer"> <br> <br>
<!-- Display the calculator button on the screen. -->
<!-- onclick() function display the number prsses by the user. -->
<input type = "button" value = "1" onclick = "form1.answer.value += '1' ">
<input type = "button" value = "2" onclick = "form1.answer.value += '2' "> 63
UNIT IV JS BACIES, S.MEENAKSHI, DEPT.OF S&H,RMKEC

You might also like