Javascript (JS) : Name-Shubham Madne Contact-7058163037
Javascript (JS) : Name-Shubham Madne Contact-7058163037
Email-madneshubham124@gmail.com
Contact-7058163037
JavaScript(js)
What is JavaScript?
Example:
JavaScript provides 3 places to put the JavaScript code: within body tag, within
head tag and external JavaScript file.
<script type="text/javascript">
document.write(" ");
</script>
The script tag specifies that we are using JavaScript. The text/javascript is the
content type that provides information to the browser about the data. The
document.write() function is used to display dynamic content through
JavaScript. We will learn about document object in detail later.
<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Hello </p>
</body>
</html>
JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types
of variables in JavaScript : local variable and global variable. There are some
rules while declaring a JavaScript variable (also known as identifiers).
Name must start with a letter (a to z or A to Z), underscore( _ ), or
dollar( $ ) sign.
After first letter we can use digits (0 to 9), for example value1.
JavaScript variables are case sensitive, for example x and X are different
variables.
1. Local variable:
A JavaScript local variable is declared inside block or function. It is
accessible within the function or block only.
<script>
If(a==b){
var y=20;//Js Local variable
}
</script>
2. Global variable:
A JavaScript global variable is accessible from any function. A variable
i.e. declared outside the function or declared with window object is
known as global variable.
<script>
var s=34;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling Js function
b();
</script>
JavaScript is a dynamic type language, means you don't need to specify type of
the variable because it is dynamically used by JavaScript engine. You need to
use var here to specify the data type. It can hold any type of values such as
numbers, strings etc.
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on
operands. For example:
var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator.
Arithmetic Operators
Comparison (Relational) Operators
Bitwise Operators
Logical Operators
Assignment Operators
Special Operators
1.Arithmetic Operators
+ Addition ex-10+20 = 30
- Subtraction ex-20-10 = 10
* Multiplication ex-10*20 = 200
/ Division ex-20/10 = 2
% Modulus (Remainder) ex-20%10 = 0
++ Increment ex-var a=10; a++; Now a = 11
-- Decrement ex-var a=10; a--; Now a = 9
2.Comparison Operators
== Is equal to ex-10==20 = false
=== Identical (equal and of same type) ex-10==20 = false
!= Not equal to ex-10!=20 = true
!== Not Identical ex-20!==20 = false
> Greater than ex-20>10 = true
>= Greater than or equal to ex-20>=10 = true
< Less than ex-20<10 = false
<= Less than or equal to ex-20<=10 = false
3.Bitwise Operators
& Bitwise AND ex- (10==20 & 20==33) = false
| Bitwise OR ex- (10==20 | 20==33) = false
^ Bitwise XOR ex- (10==20 ^ 20==33) = false
~ Bitwise NOT ex- (~10) = -10
<< Bitwise Left Shift ex- (10<<2) = 40
>> Bitwise Right Shift ex- (10>>2) = 2
>>> Bitwise Right Shift with Zero ex- (10>>>2) = 2
4.Logical Operators
&& Logical AND ex- (10==20 && 20==33) = false
|| Logical OR ex- (10==20 || 20==33) = false
! Logical Not ex-!(10==20) = true
5.Assignment Operators
= Assign ex-10+10 = 20
+= Add and assign ex-var a=10; a+=20; Now a = 30
-= Subtract and assign ex-var a=20; a-=10; Now a = 10
*= Multiply and assign ex-var a=10; a*=20; Now a = 200
/= Divide and assign ex-var a=10; a/=2; Now a = 5
%= Modulus and assign ex-var a=10; a%=2; Now a = 0
6.Special Operators
(?:) Conditional Operator returns value based on the condition. It is like
if-else.
, Comma Operator allows multiple expressions to be evaluated as single
statement.
delete Delete Operator deletes a property from the object.
in In Operator checks if object has the given property
instanceof checks if the object is an instance of given type
new creates an instance (object)
typeof checks the type of object.
void it discards the expression's return value.
yield checks what is returned in a generator by the generator's iterator.
If Statement
If else statement
if else if statement
1) If statement:
It evaluates the content only if expression is true. The signature of JavaScript if
statement is given below.
if(expression){
//content to be evaluated
}
Example:-
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
2) If...else Statement
It evaluates the content whether condition is true of false. The syntax of
JavaScript if-else statement is given below.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Example:-
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
3)If...else if statement
It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
Example:-
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
Example:-
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
JavaScript Loops:
The JavaScript loops are used to iterate the piece of code using for, while, do
while or for-in loops. It makes the code compact. It is mostly used in array.
for loop
while loop
do-while loop
for-in loop
1) For loop
The JavaScript for loop iterates the elements for the fixed number of times. It
should be used if number of iteration is known. The syntax of for loop is given
below.
Example:-
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
2) While loop
The JavaScript while loop iterates the elements for the infinite number of times.
It should be used if number of iteration is not known. The syntax of while loop
is -
while (condition)
{
code to be executed
}
Example:-
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
3) do while loop
The JavaScript do while loop iterates the elements for the infinite number of
times like while loop. But, code is executed at least once whether condition is
true or false. The syntax of do while loop is -
do{
code to be executed
}while (condition);
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
JavaScript Functions:-
JavaScript functions are used to perform operations. We can call JavaScript
function many times to reuse the code.
Example:-
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
Js Function Arguments:-
We can call function by passing arguments.
Example:-
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
Example:-
<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
Syntax
new Function ([arg1[, arg2[, ....argn]],] functionBody)
Parameter
arg1, arg2, .... , argn - It represents the argument used by function.
By array literal
By creating instance of Array directly (using new keyword)
By using an Array constructor (using new keyword)
1) JavaScript array literal
The syntax of creating array using array literal is
var arrayname=[value1,value2.....valueN];
Example:-
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
Example:-
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
By string literal
By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating string
using string literal is
var stringname="string value";
Example:
<script>
var str="This is string literal";
document.write(str);
</script>
Once a Date object is created, a number of methods allow you to operate on it.
Most methods simply allow you to get and set the year, month, day, hour,
minute, second, and millisecond fields of the object, using either local time or
UTC (universal, or GMT) time.
Syntax
You can use any of the following syntaxes to create a Date object using Date()
constructor.
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
Note − Parameters in the brackets are always optional.
7 agruments − To use the last form of the constructor shown above. Here is a
description of each argument −
year − Integer value representing the year. For compatibility (in order to avoid
the Y2K problem), you should always specify the year in full; use 1998, rather
than 98.
month − Integer value representing the month, beginning with 0 for January to
11 for December.
hour − Integer value representing the hour of the day (24-hour scale).
1 constructor
Specifies the function that creates an object's prototype.
2 prototype
The prototype property allows you to add properties and methods to an object
In the following sections, we will have a few examples to demonstrate the usage
of different Date properties.
Date Methods
Here is a list of the methods used with Date and their description.
1 Date()
Returns today's date and time
2 getDate()
Returns the day of the month for the specified date according to local time.
3 getDay()
Returns the day of the week for the specified date according to local time.
4 getFullYear()
Returns the year of the specified date according to local time.
5 getHours()
Returns the hour in the specified date according to local time.
6 getMilliseconds()
Returns the milliseconds in the specified date according to local time.
7 getMinutes()
Returns the minutes in the specified date according to local time.
8 getMonth()
Returns the month in the specified date according to local time.
9 getSeconds()
Returns the seconds in the specified date according to local time.
10 getTime()
Returns the numeric value of the specified date as the number of milliseconds
since January 1, 1970, 00:00:00 UTC.
11 getTimezoneOffset()
Returns the time-zone offset in minutes for the current locale.
12 getUTCDate()
Returns the day (date) of the month in the specified date according to universal
time.
13 getUTCDay()
Returns the day of the week in the specified date according to universal time.
14 getUTCFullYear()
Returns the year in the specified date according to universal time.
15 getUTCHours()
Returns the hours in the specified date according to universal time.
16 getUTCMilliseconds()
Returns the milliseconds in the specified date according to universal time.
17 getUTCMinutes()
Returns the minutes in the specified date according to universal time.
18 getUTCMonth()
Returns the month in the specified date according to universal time.
19 getUTCSeconds()
Returns the seconds in the specified date according to universal time.
The default object of browser is window means you can call all the functions of
window by specifying window or directly. For example:
Even the document object (of the HTML DOM) is a property of the window
object:
window.document.getElementById("header");
is the same as:
document.getElementById("header");
Window Size:
Two properties can be used to determine the size of the browser window.
Example
let w = window.innerWidth;
let h = window.innerHeight;
Window object − Top of the hierarchy. It is the outmost element of the object
hierarchy.
Document object − Each HTML document that gets loaded into a window
becomes a document object. The document contains the contents of the page.
Form object − Everything enclosed in the <form>...</form> tags sets the form
object.
Form control elements − The form object contains all the elements defined for
that object such as text fields, buttons, radio buttons, and checkboxes.
There are several DOMs in existence. The following sections explain each of
these DOMs in detail and describe how you can use them to access and modify
document content.
The Legacy DOM − This is the model which was introduced in early versions
of JavaScript language. It is well supported by all browsers, but allows access
only to certain key portions of documents, such as forms, form elements, and
images.
The W3C DOM − This document object model allows access and modification
of all document content and is standardized by the World Wide Web
Consortium (W3C). This model is supported by almost all the modern browsers.
The IE4 DOM − This document object model was introduced in Version 4 of
Microsoft's Internet Explorer browser. IE 5 and later versions include support
for most basic W3C DOM features.
DOM compatibility
If you want to write a script with the flexibility to use either W3C DOM or IE 4
DOM depending on their availability, then you can use a capability-testing
approach that first checks for the existence of a method or property to determine
whether the browser has the capability you desire. For example −
if (document.getElementById) {
// If the W3C method exists, use it
} else if (document.all) {
// If the all[] array exists, use it
} else {
// Otherwise use the legacy DOM
}
JavsScript OOP:
JavaScript Classes
In JavaScript, classes are the special type of functions. We can define the class
just like function declarations and function expressions.
The JavaScript class contains various class members within a body including
methods or constructor. The class is executed in strict mode. So, the code
containing the silent error or mistake throws an error.
Class declarations
Class expressions
Class Declarations
A class can be defined by using a class declaration. A class keyword is used to
declare a class with any particular name. According to JavaScript naming
conventions, the name of the class always starts with an uppercase letter.
Example:
<script>
//Declaring class
class Employee
{
//Initializing an object
constructor(id,name)
{
this.id=id;
this.name=name;
}
//Declaring method
detail()
{
document.writeln(this.id+" "+this.name+"<br>")
}
}
//passing object to a variable
var e1=new Employee(10,"Rahul");
var e2=new Employee(11,"William");
e1.detail(); //calling method
e2.detail();
</script>
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and
method). For example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is template based not class based. Here, we don't create class to get
the object. But, we direct create objects.
// create an object
const person = new Person();
In the above example, function Person() is an object constructor function.
Note:-
Other OOP concepts are similar in other languages like java and C++
JavaScript - Errors & Exceptions Handling:
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime
Errors, and (c) Logical Errors.
Syntax Errors:
Syntax errors, also called parsing errors, occur at compile time in traditional
programming languages and at interpret time in JavaScript.
For example, the following line causes a syntax error because it is missing a
closing parenthesis.
Runtime Errors:
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).
For example, the following line causes a runtime error because here the syntax
is correct, but at runtime, it is trying to call a method that does not exist.
Logical Errors:
Logic errors can be the most difficult type of errors to track down. These errors
are not the result of a syntax or runtime error. Instead, they occur when you
make a mistake in the logic that drives your script and you do not get the result
you expected.
You cannot catch those errors, because it depends on your business requirement
what type of logic you want to put in your program.
You can catch programmer-generated and runtime exceptions, but you cannot
catch JavaScript syntax errors.
catch ( e ) {
// Code to run if an exception occurs
[break;]
}
[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>
The try block must be followed by either exactly one catch block or one finally
block (or one of both). When an exception occurs in the try block, the exception
is placed in e and the catch block is executed. The optional finally block
executes unconditionally after try/catch.
Examples
Here is an example where we are trying to call a non-existing function which in
turn is raising an exception. Let us see how it behaves without try...catch−
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
alert("Value of variable a is : " + a );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Now let us try to catch this exception using try...catch and display a user-
friendly message. we can also suppress this message, if we want to hide this
error from a user.
<html>
<head>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
we can use finally block which will always execute unconditionally after the
try/catch. Here is an example.
<html>
<head>
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
finally {
alert("Finally block will always execute!" );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Example
The following example demonstrates how to use a throw statement.
<html>
<head>
try {
if ( b == 0 ) {
throw( "Divide by zero error." );
} else {
var c = a / b;
}
}
catch ( e ) {
alert("Error: " + e );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
<html>
<head>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Output
The onerror event handler provides three pieces of information to identify the
exact nature of the error −
Error message − The same message that the browser would display for the
given error
Line number− The line number in the given URL that caused the error
Here is the example to show how to extract this information.
Example
<html>
<head>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Output
we can display extracted information in whatever way we think it is better.
React Js
ReactJS is a simple, feature rich, component based JavaScript UI library. It can
be used to develop small applications as well as big, complex applications.
ReactJS provides minimal and solid feature set to kick-start a web application.
Applications of React
Few popular websites powered by React library are listed below −
React elements
JavaScript representation of HTML DOM. React provides an API,
React.createElement to create React Element.
JSX
A JavaScript extension to design user interface. JSX is an XML based,
extensible language supporting HTML syntax with little modification. JSX can
be compiled to React Elements and used to create user interface.
React component
React component is the primary building block of the React application. It uses
React elements and JSX to design its user interface. React component is
basically a JavaScript class (extends the React.component class) or pure
JavaScript function. React component has properties, state management, life
cycle and event handler. React component can be able to do simple as well as
advanced logic.
ReactJS Web Application Page:
ReactJS applications come as a JavaScript blob that will use the DOM interface
to write the view into the div as shown bellow.
<!doctype html>
<html>
<head>
<title>CS142 Example</title>
</head>
<body>
<div id="reactapp"></div>
<script src="./webpackOutput/reactApp.bundle.js"></script>
</body>
</html>
};
export default ReactAppView;
Stateless Components
● React Component can be function (not a class) if it only depends on props
function MyComponent(props) {
return <div>My name is {props.name}</div>;
}
Or using destructuring...
function MyComponent({name}) {
return <div>My name is {name}</div>;
}