Javascript - Unit 4 (1)
Javascript - Unit 4 (1)
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
JavaScript Java
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:
</body>
</html>
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?");
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
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.
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
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
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
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;
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.
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.
<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);
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)
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.
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
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.
<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>
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.
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.
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>");
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
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
<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
<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