2. Content
• Table Of Content:-
1.1 Prompt Dialog Box
1.2 parseInt
1.3 Arrays
1.3.1 Array Methods
1.4 Callback Functions
1.5 function Hosting In JavaScript
1.6 Arrow Function
1.7 == and === Operator in JavaScript
1.9 Higher Order Function
2.0 Call()
2.0.1 Apply()
2.0.2 Bind()
2.1 Class In JavaScript
2.2.1 Set
2.2.2 Weakest In JavaScript
2.3.1 Eval function
2.3.2 Generator-Function
• Assignment's:-
1. Prompt tag
2. parseInt
3. Declare an array
4. Pop()
5. push ()
6. Shift()
7. Slice()
8. Sort()
9. Splice()
10. Unshift()
11. Call Back Function
12. Arrow Function
13. Boolean constructor ()
14.Boolean Prototype()
15.Higher-Order Function
16. Class-Prototype
17. Class-Constructor
18. Set In JavaScript
19. WeakSet In JavaScript
20. Binary Function in an array
21. Right Rotation of an array
22. Eval ()
23. Generator()
3. 1.1 Prompt Dialog Box:-
• The prompt dialog box is very useful when you want to pop-up a text
box to get user input. Thus, it enables you to interact with the user.
The user needs to fill in the field and then click OK.
Syntax:-
<script>
function getValue()
{
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
4. Assignment no:-01
• Prompt tag:-
<html>
<head>
<script type="text/javascript">
function getValue()
{
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getValue();" />
</form>
</body>
</html>
5. 1.2 parseInt:-
• The parseInt() function is a built-in function in JavaScript which allows
users to convert a string to an integer value.
The parseInt() function takes the following parameters as input:
• String: The string to convert to an Integer value
• Radix: Specifies the numeral system i.e., the base of the number
7. 1.3 Arrays
• The Array object lets you store multiple values in a single variable. It
stores a fixed-size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same
type.
You can create array by simply assigning values as follows:
Var Array=[“apple”, ”mango”, “Orange’s”]
You can create array by simply assigning values as follows:
var fruits = new Array( "apple", "orange", "mango" );
8. Assignment no:-03
• Declare an array:-
<Script>
var array = [“apple”, “mango”, “orange”]
document.write(array);
</script>
9. Task no:-01
• Declare String & alphabets in an array by printing in console.log.
• get the element of an array by using parseInt and then print an array.
10. 1.3.1 Array Methods:-
• filter() :- Creates a new array with all of the elements of this array for
which the provided filtering function returns true
• pop() :- Removes the last element from an array and returns that element.
• push() :- Adds one or more elements to the end of an array and returns the
new length of the array.
• shift():- Removes the first element from an array and returns that element.
• slice() :- Extracts a section of an array and returns a new array
• splice() :- Adds and/or removes elements from an array.
• unshift() :- Adds one or more elements to the front of an array and returns
the new length of the array.
11. Assignment no:-04
• Pop():-
<html>
<head>
<title>JavaScript Array pop Method</title>
</head>
<body>
<script>
var numbers = [1, 4, 9];
var element = numbers.pop();
document.write("element is : " + element );
var element = numbers.pop();
document.write("<br />element is : " + element );
</script>
</body>
</html>
12. Assignment no:-05
• push ():-
<html>
<head>
<title>JavaScript Array push Method</title>
</head>
<body>
<script>
var numbers = new Array(1, 4, 9);
var length = numbers.push(10);
document.write("new numbers is : " + numbers );
length = numbers.push(20);
document.write("<br />new numbers is : " + numbers );
</script>
</body>
</html>
17. Assignment no:-10
• Unshift():-
<html>
<head>
<title>JavaScript Array unshift Method</title>
</head>
<body>
<script>
var arr = new Array("orange", "mango", "banana", "sugar");
var length = arr.unshift("water");
document.write("Returned array is : " + arr );
document.write("<br /> Length of the array is : " + length );
</script>
</body>
</html>
18. 1.4 Callback Functions:-
A callback function is a function that is passed as an argument to another function.
Callback functions are a technique that’s possible in JavaScript because of the fact
that functions are objects
Writing functions with callbacks
Here’s a simple example function, doMath, that accepts a callback function as an
argument
Syntax:-
function doMath(number1,number2,callback)
{
var result = callback(number1,number2);
document.write (“The result is: “: + result);
}
19. Assignment no:-11
• Call Back Function:-
// function
function greet(name, callback) {
console.log('Hi' + ' ' + name);
callback();
}
// callback function
function callMe() {
console.log('I am callback function');
}
// passing function as an argument
greet('Peter', callMe);
20. 1.5 function Hosting In JavaScript
• Hoisting is a JavaScript technique which moves variables and function
declarations to the top of their scope before code execution begins.
Within a scope no matter where functions or variables are declared,
they're moved to the top of their scope.
• Note that hoisting only moves the declaration while assignments are
left in place
• Hosting is a Default behavior of JavaScript where all the variables and
Fucntion Declared are moved on top.
21. • Hosting In javaScript:-
Examples:-
Fucntion dosomething()
{
X=33;
console.log(x);
Var x;
}
console.log(functionBelow("Hello"));
function functionBelow(greet)
{
return `${greet} world`;
}
console.log(functionBelow("Hi"));
22. 1.6 Arrow Function:-
• It is a sort of an abbreviated way to write compact functions.
• The following are a few facts about arrow functions:
• Using the arrow function, curly braces, parenthesis, function, and
return keywords become optional.
• The arrow function has a lexical scoping to this context.
• One of the main differences between arrow functions and regular
functions is that arrow functions can only be anonymous. They are
not bound to any identifier
23. Assignment no:-12
• Arrow Function :- ADD
<script>
let add = (x, y) => x + y;
console.log(add(10, 20));
</script>
• Array sort using arrow function:-
let numbers = [4,2,6];
numbers.sort((a,b) => b - a);
console.log(numbers);
25. 1.7 == and === Operator in JavaScript
• In JavaScript, the double and triple equals are used for comparison
between two operands. The difference between both the equals is:
Sr. No. Key Double Equals (==) Triple Equals (===)
1
Naming Double equals named as Equality Operator. Triple equals named as Identity / Strict equality Operator.
2
Comparison Double equals used as Type converting the conversion Triple equals used as Strict conversion without performing
any conversion in operands.
3
Syntax Double equals has syntax for comparison as (a == b) Triple equals has syntax for comparison as (a === b)
4
Implementation Double equals first convert the operands into the same
type and then compare i.e comparison would perform
once both the operands are of the same type. This is also
known as type coercion comparison.
On the other hand, triple equals do not perform any type
of conversion before comparison and return true only if
type and value of both operands are exactly the same.
26. var x = 2;
var y = "2";
(x == y) // Returns true since the value of both x and y is the same
(x === y) // Returns false since the typeof x is "number" and typeof y is
"string"
27. 1.8 Boolean
• The Boolean object represents two values, either "true" or "false". If value
parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty
string (""), the object has an initial value of false
• Syntax:-
var val = new Boolean(value);
• properties of Boolean object:
constructor:- Returns a reference to the Boolean function that created the
object.
prototype :- The prototype property allows you to add properties and
methods to an object.
28. Assignment no:-14
• constructor () :-
<html>
<head>
<title>JavaScript constructor() Method</title>
</head>
<body>
<script>
var bool = new Boolean( );
document.write("bool.constructor() is : " + bool.constructor);
</script>
</body>
</html>
29. Assignment no:-15
• Prototype():-Syntax :- object.prototype.name = value
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
this.title = title;
this.author = author;
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
book.prototype.price = null;
myBook.price = 100;
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
30. 1.9 Higher Order Function
• Functions that operate on other functions, either by taking them as
arguments or by returning them, are called higher-order functions.
Higher order functions are a result of functions being first-class citizens
in javascript
function higherOrder(fn)
{
fn();
}
higherOrder(function() { console.log("Hello world") });
31. Assignment no:-16
• Higher-Order Function:-
const add = (a, b) => a + b;
const isEven = num => num % 2 === 0;
const data = [2, 3, 1, 5, 4, 6];
const evenValues = data.filter(isEven); // [2, 4, 6]
const evenSum = data.filter(isEven).reduce(add); // 12
In the above example, we define two simple functions that we then use as
callbacks in Array.prototype.reduce() and Array.prototype.filter() to get the
result we want. Both of these functions are higher-order functions, allowing
us to create an abstraction layer for any action we might want to perform
without having to rewrite how the filtering or reduction algorithm is to be
applied every single time.
32. 2.0 Call()
• call():- It’s a predefined method in javascript. This method invokes a
method (function) by specifying the owner object.
function sayHello()
{
return "Hello " + this.name;
}
var obj = {name: "Sandy"};
sayHello.call(obj);
33. 2.0.1 Apply()
• apply():- The apply method is similar to the call() method. The only
difference is that , call() method takes arguments separately whereas,
apply() method takes arguments as an array.
function saySomething(message)
{
return this.name + " is " + message;
}
var person4 = {name: "John"};
saySomething.apply(person4, ["awesome"]);
34. 2.0.2 Bind()
• bind() :- This method returns a new function, where the value of “this” skeyword will be bound to
the owner object, which is provided as a parameter.
var bikeDetails =
{
displayDetails: function(registrationNumber,brandName)
{
return this.name+ " , "+ "bike details: "+ registrationNumber + " , " + brandName;
}
}
var person1 = {name: "Vivek"};
var detailsOfPerson1 = bikeDetails.displayDetails.bind(person1, "TS0122", "Bullet");
// Binds the displayDetails function to the person1 object
detailsOfPerson1();
// Returns Vivek, bike details: TS0452, Thunderbird
35. 2.1 Class In JavaScript
• What Is a class in Javascript?
A class encapsulates data and functions that manipulate data. Unlike other programming languages
such as Java and C#, JavaScript classes are syntactic sugar over the prototypal inheritance. In other
words, ES6 classes are just special functions.
The Object class represents one of JavaScript's data types. It is used to store various keyed
collections and more complex entities.
Constructor: This is a special method for initializing an instance of that class. So what that means is
that whenever we create a new instance of the class, it will invoke the constructor
Prototype Method: A prototype method is a method that is only accessible when you create an
instance of the class.
36. Assignment no:-17
• Class-Prototype in javaScript:-
function student(name,rollno,grade,section)
{
this.name=name;
this.rollno=rollno;
this.grade=grade;
this.section=section;
}
student.prototype.getDetails = function()
{
return 'name: ${this.name},rollno: ${this.rollno},grade: ${this.grade},section:
${this.section}';
}
let student1 = new student ("boney","24","6th","A");
student1.getDetails();
console.log(student1);
37. Assignment no:-18
• Class-Constructor in JavaScript:-
class student
{
constructor (name,rollno,grade,section)
{
this.name=name;
this.rollno=rollno;
this.grade=grade;
this.section=section;
}
getDetails()
{
return 'Name: ${this.name},Rollno: ${this.rollno},Grade: ${this.grade},Section: ${this.section}';
}
}
let student1 = new student ("boney","24","6th","A");
student1.getDetails();
console.log(student1);
38. 2.2.1 Set
• Set data type:- It represents a set of elements (a collection) and you
can iterate through the elements of a set in insertion order. Another
important point is that sets are ordered lists of values that contain no
duplicate items and are accessed using keys, instead indexes
39. Assignment no:-19
• Set In JavaScript:-
(Removes Duplicate value from an array):-
const array=[1,1,2,2,3,3,3,3,4,4,4,4,5,5,5,5,5,6,6,7,7,8,8,9,9]
const mySet = new Set(array);
console.log([Array.from (new Set(array))]);
////create Set
const set1 = new Set(); // an empty set
console.log(set1); // Set {}
// Set with multiple types of value
const set2 = new Set([1, 'hello', {count : true}]);
console.log(set2); // Set {1, "hello", {count: true}}
// Set with duplicate values
const set3 = new Set([1, 1, 2, 2]);
console.log(set3); // Set {1, 2}
40. 2.2.2 Weakest In JavaScript
• WeakSet are basically the same as Set with two important
differences:
1 — The values stored in WeakSet cannot be primitive values (Boolean,
Number, String, or undefined)
2 — WeakSet is weak: If there is no other reference to an object stored
in the WeakSet, they can be garbage collected. Becasuse this, we
cannot interate over WeakSet items
41. Assignment no:-20
• WeakSet In JavaScript:-
const adam = new WeakSet([{a:1},{b:2},{c:3},{d:4},{e:5},{f:7}]);
console.log(adam);
////////////////////////////
const weakSet = new WeakSet();
console.log(weakSet); // WeakSet {}
let obj = {
message: 'Hi',
sendMessage: true
}
// adding object (element) to WeakSet
weakSet.add(obj);
console.log(weakSet); // WeakSet {{message: "Hi", sendMessage: true}}
42. Assignment no:-21
• Binary Function in an array:-
var a = [1,2,4,6,1,100,0,10000,3];
a.sort(function (a, b)
{
return a - b;
});
console.log('a,', a);
function binarySearch(arr, i)
{
var mid = Math.floor(arr.length / 2);
console.log(arr[mid], i);
43. if (arr[mid] === i )
{
console.log('match', arr[mid], i);
return arr[mid];
}
else if (arr[mid] < i && arr.length > 1)
{
console.log('mid lower', arr[mid], i);
binarySearch(arr.splice(mid, Number.MAX_VALUE), i);
}
else if (arr[mid] > i && arr.length > 1)
{
console.log('mid higher', arr[mid], i);
binarySearch(arr.splice(0, mid), i);
} else
{
console.log('not here', i);
return -1;
}
}
var result = binarySearch(a, 4);
console.log(result);
44. Assignment no:-22
• Right Rotation of an array:-
function rotationRight(arr,rotations)
{
if (rotations == 0)
{
return arr;
}
for (let i=0; i<rotations; i++)
{
let element= arr.pop();
arr.unshift(element);
console.log(arr);
}
return arr;
}
rotationRight([2,3,4,5,7],2);
45. 2.3.1 Eval function
• Eval():- eval( ) is a global method that evaluates a string of JavaScript
code in the current lexical scope. If code contains an expression, eval
evaluates the expression and returns its value. If code contains a
JavaScript statement or statements, eval( ) executes those statements
and returns the value, if any, returned by the last statement. If code
does not return any value, eval( ) returns undefined. Finally, if code
throws an exception, eval( ) passes that exception on to the caller.
46. 2.3.2 Generator-Function
• Generator-Function :- A generator-function is defined like a normal
function, but whenever it needs to generate a value, it does so with
the yield keyword rather than return. The yield statement suspends
function’s execution and sends a value back to caller, but retains
enough state to enable function to resume where it is left off. When
resumed, the function continues execution immediately after the last
yield run.
47. Assignment no:-23
• Eval ():-
<html>
<body>
<script>
let a = 1;
function f() {
let a = 2;
eval('alert(a)');
}
f();
</script>
</body>
</html>