JavaScript- KT Document
JavaScript- KT Document
• JavaScript is very easy to implement. All you need to do is put your code in the HTML
document and tell the browser that it is JavaScript.
• There are almost no limits to the things you can do with JavaScript on a web page like:
➢ Show or hide more information with the click of a button
➢ Change the color of a button when the mouse hovers over it
➢ Zooming in and out on an image
➢ Using dropdowns, enabling, and disabling it based on conditions.
• JavaScript can also be used to create browser games.
• Loading new content or data onto the page without reloading the page
• Validating input from Web forms
• JavaScript is relatively simple to learn .
Parsers in JS:
It checks for syntax. Parsing means analyzing and converting a program into an internal format
that a runtime environment can actually run, for example the JavaScript engine inside browsers.
In Parsing phase, code is broken down into tokens and the syntax parser converts these tokens
into abstract syntax tree(AST). AST is used by bytecode generator to form byte code which in turn
is used by the interpreter to run the code.
Interpreter lets the lets the AST to get converted into Byte code. In V8 engine, this process is
known as Ignition. The compiler Turbofan is used in v8. JavaScript Engine’s speed gets improved
since profiler and compiler will be producing and updating the optimized byte code.Tools that can
be used to generate the code for a parser are called parser generators or compiler.
E.g., 437 + 347
A lexer and a parser work in sequence: the lexer scans the input and produces the matching tokens,
the parser scans the tokens and produces the parsing result. A grammar is a list of rules that define
how each construct can be composed. For example, a rule for an if statement could specify that it
must starts with the “if” keyword, followed by a left parenthesis, an expression, a right parenthesis,
and a statement. In CFG(context free grammar), the start symbol is used to derive the string. You
can derive the string by repeatedly replacing a non-terminal by the righthand side of the production,
until all non-terminals have been replaced by terminal symbols.
Top-down parser: When the parser starts constructing the parse tree from the start symbol and
then tries to transform the start symbol to the input, it is called top-down parsing. It builds parse
trees from top(root) to bottom(leaves).It follows left most derivation.
E.g., Input String: abbcde
Bottom-up parser: It will start from string and proceed to start. It builds the parse trees from
leaves and work up to the root. It will follow rightmost derivation in reverse order.
E.g.,
Execution Context:
Whenever the JavaScript engine receives a script file, it first creates a default Execution Context
known as the Global Execution Context (GEC). JavaScript code is executed inside execution
context. It has two components in it: Memory(stores variables and functions) and code(code is
executed). Memory component is also known as variable environment. Code is also known as
Thread of execution.
E.g., Phase I(Memory)
Phase II(Execution)
Call Stack/Execution Stack – A stack data structure in which new execution context is created,
itis pushed on top of Global Execution context. The execution context is managed by call stack.
When the execution is completed it is popped off from the stack.
push
Exec 1 Exec 2
Script Tag:
Variables:
Variables in JavaScript are declared using ‘var’, ‘let’, ‘const’ keyword.
Syntax: var name = expression;
Rules while declaring variables:
1. Name must start with a letter, underscore (_), or dollar ($) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive.
var let const
• The scope of • The scope of • The scope is block
the var keyword is the a let variable is only scope.
global or function block scoped. It can’t • When users declare
scope. be accessible outside a const variable, they
• It can be declared the particular block need to initialize it,
without initialization • It can be declared otherwise, it returns
without initialization an error.
Arrays:
Syntax:
1. Declaring an empty array:
var name = []; E.g., const cars = [];
2. Initialize an array with prefilled values:
var name = [value, value, ..., value];
E.g.: const cars = ["Saab", "Volvo", "BMW"];
3. Storing the element by specifying index value:
name[index] = value; // store element
E.g. const cars = [];
cars [0] = “Saab”;
cars [1] = “Volvo”;
cars [2] = “BMW”;
• Array Methods:
concat, join, pop, push, reverse, shift, slice, sort, splice, toString, unshift
E.g. var a = ["Stef", "Jason", “Reena”]; // Stef, Jason, Reena
a. push("Brian"); // Stef, Jason, Reena, Brian
a.unshift("Kelly"); // Kelly, Stef, Jason, Reena, Brian
a.pop(); // Kelly, Stef, Jason, Reena
a.shift(); // Stef, Jason, Reena
a.sort(); // Jason, Reena, Stef
push and pop add / remove from back
unshift and shift add / remove from front
Map, Reduce, Filter:
• Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an
array and perform a transformation or computation. Each will return a new array based on
the result of the function.
• map() method: The map() method is used for creating a new array from an existing one,
applying a function to each one of the elements of the first array.
E.g., const numbers = [1, 2, 3, 4];
const doubled = numbers.map(item => item * 2);
console.log(doubled); // [2, 4, 6, 8]
• filter() method: The filter() method takes each element in an array and it applies a
conditional statement against it. If this conditional returns true, the element gets pushed
to the output array. If the condition returns false, the element does not get pushed to the
output array.
E.g., const numbers = [1, 2, 3, 4];
evens = numbers.filter(item => item % 2 === 0); [filter]
console.log(evens); // [2, 4]
• reduce() method: The reduce() method reduces an array of values down to just one value.
To get the output value, it runs a reducer function on each element of the array.
Syntax: arr.reduce(callback[, initialValue])
• The callback argument is a function that will be called once for every item in the
array. This function takes four arguments, but often only the first two are used.
1. accumulator - the returned value of the previous iteration
2. currentValue - the current item in the array
3. index - the index of the current item
4. array - the original array on which reduce was called.
person.firstname; //Rita
Dates:
• The JavaScript date object can be used to get year, month, and day.
Syntax:
var date = new Date();
• Some of the methods include : getDate(), getHours(), getMilliseconds(), getMonth(),
getSeconds(), setDate(), setDay(), setHours() etc.
var date=new Date();
document.write("<br>Current date is :"+date );
document.write("<br>Month :"+(date.getMonth() + 1));
document.write("<br>Year :"+date.getFullYear());
document.write("<br>Date :"+ date.getDate());
Math:
• The JavaScript math object provides several constants and methods to perform
mathematical operation.
• Some of the Methods are abs(), ceil(), cos(), floor(), log(), max(), min(), pow(), random(),
round(), sin(), sqrt(), tan()
Output:
apply() method:
apply() method is similar to call() method. The apply() method takes arguments as an array.
Output:
bind():
The bind() method sets the values to the function, but the function needs to be invoked
seperately.
Output:
add();//counter=1
add();//counter=2
add();// counter=3
eval():
The eval() function in JavaScript is used to evaluate the expression.
setTimeout(): The setTimeout() method in JavaScript is used to execute a function after waiting
for the specified time interval. Unlike the setInteval() method, the setTimeout() method executes
the function only once. The clearTimeout() method can be used to stop the timeout
E.g., var a;
a = setTimeout(fun, 2000);
function fun() {
alert(" This will be displayed after 2 sec!");
}
setInterval():The setInterval() method in JavaScript is used to repeat a specified function at every
given time-interval. It evaluates an expression or calls a function at given intervals. The
clearInterval() is used to stop the function being called. It will be executed multiple times.
E.g., var a;
a = setInterval(fun, 3000);
function fun() {
alert("The alert box will be displayed for every 3seconds");
}
JS Errors:
There are different types of error such as:
• EvalError – If an error occur during eval() function
• RangeError- If an out of range occurs
• ReferenceError- If an illegal reference occurs
• SyntaxError- If a syntax error occurs
• TypeError- If a type error occurs
An exception is a condition that disrupts the normal flow of execution. Exception handling is a
process or method used for handling the abnormal statements in the code and executing them.
Try catch:
• The try statement is used to execute a block of a code, and the catch block is used to handle
the error.
• The finally statement defines a block of code which has to be run regardless of exception
occurs or not.
• The throw statement is used to define custom error
throw syntax: try {
throw new Error(“This is a user defined statement!”);
} catch (e) {
document.write(e.message);
}
Output:
JS Collections
• Set: It stores a collection of unique values of any type.
Syntax: let setObject = new Set();
const letters = new Set(["a","b","c"]);
• size of set: To get the number of elements that the set holds, you use the size property of
the Set object.
let size = letters.size;
console.log(size); // 3
• To add an element to the set, add() method is used.
Adding an element:
let chars = new Set(['a', 'a', 'b', 'c', 'c']);
console.log(chars); // {a,b,c} [prints only unique elements]
chars.add('d');
console.log(chars); // {a,b,c,d}
• add() method is chainable, you can add multiple items to a set using a chain statement:
chars.add('e')
.add('f');
console.log(chars); //{a,b,c,d,e,f}
Check if value exists: The has() method returns true if the set contains the element, otherwise, it
returns false.
let exist = chars.has('b');
console.log(exist); // true
Remove an element: The delete() method is used to delete specified element from the set.
chars.delete('c');
console.log(chars); // {"a", "b", "d", "e"}
Iterating elements in set: The JavaScript Set entries() method returns an object of new set
iterator. This object contains an array of [value, value] for each element. It maintains an insertion
order. To keep the values unique it uses the key internally. Set considers the value of element as a
key. In array[value, value], the first value represents the key whereas the second value represents
the value of element.
<script>
var set = new Set();
set.add("jQuery");
set.add("AngularJS");
set.add("Bootstrap");
var itr=set.entries(); Output:
for(i=0;i<set.size;i++)
{
document.writeln(itr.next().value+"<br>");
}
</script>
forEach: The JavaScript Set forEach() method executes the specified function once for each value in the
Set object.
<script>
var set = new Set(["jQuery","AngularJS","Bootstrap"]);
document.writeln("Fetching values :"+"<br>"); Output:
set.forEach(function display(value1,value2,set)
{
document.writeln('key[' + value1 + '] = ' + value2+"<br>");
})
</script>
Weak Set:
The JavaScript WeakSet object is the type of collection that allows us to store weakly held objects.
WeakSet may be automatically garbage-collected.
let computer = {type: 'laptop'};
let server = {type: 'server'};
let equipment = new WeakSet([computer, server]);
if (equipment.has(server)) {
console.log('We have a server');
}
Output: We have a server
Map:
The JavaScript Map object is used to map keys to values. It stores each element as key-value pair.
It operates the elements such as search, update and delete on the basis of specified key.
Syntax: let map = new Map([iterable]);
iterable - It represents an array and other iterable object whose elements are in the form of key-
value pair
Passing an itearable object: An iterable object to the Map() constructor can also be passed:
var map = new Map([
[1, 'jQuery'],
[2, 'AngularJS'],
[3, 'BootStrap']
]);
Adding Elements: The JavaScript map set() method is used to add or updates an element to map
object with the particular key-value pair. Each value must have a unique key.
E.g., var map=new Map();
map.set(1,"jQuery");
map.set(2,"AngularJS");
map.set(3,"Bootstrap");
set() method is chainable, so multiple elements can be inserted to map using chain statement:
map.set(4, 'Java')
.set(5, ‘.Net’);
Accessing elements: The JavaScript map get() method returns the value of specified key of an
element from a Map object. If you pass a key that does not exist, the get() method will
return undefined.
Syntax:mapObj.get(key);
map.get(1); // jQuery
map.get(3); //BootStrap
map.get(4); //.Net
Check if value exists: To check if a key exists in the map, you use the has() method.
map.has(“Java”); //true
map.has(“sql”); //false
Deleting elements: The JavaScript map delete() method is used to remove all the elements
from Map object.
Syntax: mapObj.delete()
map.delete(2);
Iterating Elements:
entries()- The JavaScript map entries() method returns an object of new map iterator. This object
contains the key-value pair for each element. It maintains insertion order.
Syntax: mapObj.entries()
<script>
var map=new Map();
map.set(1,"jQuery");
map.set(2,"AngularJS"); Output:
map.set(3,"Bootstrap");
var itr=map.entries();
document.writeln(itr.next().value+"<br>");
document.writeln(itr.next().value+"<br>");
document.writeln(itr.next().value);
</script>
values()- The JavaScript map values() method returns an object of new Map iterator. This object
contains the value for each element. It maintains insertion order.
E.g., <script>
var map=new Map(); Output:
map.set(1,"jQuery");
map.set(2,"AngularJS");
map.set(3,"Bootstrap");
var itr=map.values();
document.writeln(itr.next().value+"<br>");
document.writeln(itr.next().value+"<br>");
document.writeln(itr.next().value);
</script>
Weak Map: The JavaScript WeakMap object is a type of collection which is almost similar to
Map. It stores each element as a key-value pair where keys are weakly referenced. Here, the keys
are objects and the values are arbitrary values. In WeakMap, if there is no reference to a key object,
they are targeted to garbage collection.
Syntax: new WeakMap([iterable])
<script>
var wm = new WeakMap();
var obj1 = {};
var obj2 = {};
var obj3= {};
wm.set(obj1, "jQuery");
wm.set(obj2, "AngularJS"); Output:
wm.set(obj3,"Bootstrap");
document.writeln(wm.get(obj1)+"<br>");
document.writeln(wm.get(obj2)+"<br>");
document.writeln(wm.get(obj3));
</script>
Event-Driven Programming:
Examples of events:
onload - The onload event occurs when an object has been loaded. The onload event can be used
to check the visitor's browser type and browser version information, and can also be used to deal
with cookies
onfocus - The onfocus event occurs when an element gets focus. It is often used with <input>,
<select>, <a>
onerror - The onerror event is triggered if an error occurs while loading an external file (e.g. a
document or an image).
BOM:
The Browser Object Model (BOM) is used to interact with the browser. The default object of
browser is window.
1.Window Object:
The window object represents a window in browser. Some of the methods include:
• alert() - displays the alert box containing message with ok button.
• confirm() - displays the confirm dialog box containing message with ok and cancel button.
• prompt() - displays a dialog box to get input from the user.
• open() - opens the new window.
• close() - closes the current window.
E.g. window.alert(“This is an window alert!”); confirm(“Are you sure you want to exit:”);
2. History Object:
The history object represents an array of URLs visited by the user. By using this object, one can
load previous page, forward or any particular page. It can be accessed by: window.history or
history
4.Screen Object:
The JavaScript screen object holds information of browser screen. It can be used to display
screen width, height, colorDepth, pixelDepth etc. The properties of screen object include:
• width - returns the width of the screen
• height - returns the height of the screen
• availWidth - returns the available width
• availHeight - returns the available height
• colorDepth - returns the color depth
E.g. alert("Screen With :"+screen.width+"\n Screen Height :"+screen.height+
"\nScreen Color Depth:"+screen.colorDepth+
"\nWindow width :"+window.innerWidth);
5.Location Object:
The location object can be used to get the current page address (URL) and to redirect the browser
to a new page. The properties of the location object include:
• href - returns the href (URL) of the current page
• hostname - returns the domain name of the web host
• pathname - returns the path and filename of the current page
• protocol - returns the web protocol used (http: or https:)
• assign() - loads a new document
DOM:
When a web page is loaded, the browser creates a Document Object Model of the page. The
document object represents the whole html document. By the help of document object, JS gets
power to create dynamic HTML. The HTML DOM defines:
Output:
Output:
HTML Objects:
Disabling a Button: The disabled property sets whether an input button should be disabled, or
not. A disabled element is unusable and un-clickable.
Syntax: buttonObject.disabled = true|false
AutoFocus a Button: The input button automatically gets focus when the page is loaded.
Disbaling a Radio Button:
The disabled property sets or returns whether a radio button should be disabled, or not. It returns
true if the radio button is disabled, otherwise it returns false.
Syntax: radioObject.disabled = true|false
Output:
DropDowns:
• A dropdown list is a toggleable menu that allows the user to choose one option from
multiple ones. When you click or choose this option, that function triggers and starts
performing.
• selectedIndex: The selectedIndex property sets or returns the index of the selected option
in a drop-down list. The index starts from 0.
• onchange - The onchange event occurs when the value of an element has been changed
You can also set the index value:
document.getElementById(“myList”).selectedIndex= “3”; //python
Validation.js
click event:
LoginSuccess.html
Registration Form.html
Registration Form:
Registration Validation.JS
Name validation:
Mouseover event:
Password Validation:
Phone validation: