Javascript
Javascript
Javascript
JAVASCRIPT
• NO!
• Java and JavaScript are two completely different
languages in both concept and design
• Java (developed by Sun Microsystems) is a powerful
and much more complex programming language - in
the same category as C and C++.
<script> tags
• Place the <script> tags, containing JavaScript,
anywhere within your web page, but it is normally
recommended that you should keep it within the
<head> tags.
• The <script> tag alerts the browser program to
start interpreting all the text between these tags as
a script.
• A simple syntax of your JavaScript will appear as
follows.
<script ...> JavaScript code </script>
Flexibility given to include JavaScript code anywhere
in an HTML document.
However the most preferred ways to include
JavaScript in an HTML file are as follows −
<html>
<body>
<script language=“javascript” type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
JavaScript Identifiers
All JavaScript variables must be identified with unique
names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more
descriptive names (age, sum, totalVolume).
Var
• var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
Let , const
let x = 0;
• With var you can:
Redeclaring the variable
<!DOCTYPE html>
<html>
<body>
<h2>Redeclaring a Variable Using let</h2>
<p id="demo"></p>
<script>
let x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
document.getElementById("demo").innerHTML = x;
</script></body></html>
Redeclaring a variable with let, in another block, IS allowed:
<script>
let x = 2; // Allowed
{
let x = 3; // Allowed
}
{
let x = 4; // Allowed
}
document.getElementById("demo").innerHTML = x; 2
</script>
const
• The const keyword was introduced in
ES6 (2015).
• Variables defined with const cannot be
Redeclared.
• Variables defined with const cannot be
Reassigned.
• Variables defined with const have Block Scope.
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
• JavaScript const variables must be assigned a
value when they are declared:
• const PI = 3.14159265359;………… correct
• const PI;
PI = 3.14159265359; Incorrect
When to use JavaScript const?
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
Comparison Operators
if (expression)
{
Statement(s) to be executed if
expression is true
}
if statement
var num = 5 ;
if (num>0)
{
console.log("number is positive")
}
if...else statement
if (expression)
{
Statement(s) to be executed if expression
is true
}
else
{ var num = 12;
Statement(s) to be executed if expression
is false
if (num % 2 == 0) {
}
console.log("Even");
} else {
console.log("Odd");
}
if...else if... statement
if (expression 1)
{ else
Statement(s) to be executed if {
expression 1 is true
Statement(s) to be executed if
}
no expression is true
else if (expression 2)
}
{
Statement(s) to be executed if
expression 2 is true
}
else if (expression 3)
{
Statement(s) to be executed if
expression 3 is true
}
var num=2
if(num > 0) {
console.log(num+" is positive")
} else if(num < 0) {
console.log(num+" is negative")
} else {
console.log(num+" is neither positive nor
negative")
}
Switch Case
Rules apply to a switch
Definite Loop
A loop whose number of iterations are
definite/fixed is termed as a definite loop.
The ‘for loop’ is an implementation of a definite
loop.
For Loop
var num = 5
var factorial=1;
for( let i = num ; i >= 1; i-- ) {
factorial *= i ;
}
console.log(factorial);
• Multiple assignments and final expressions can
be combined in a for loop, by using the comma
operator (,).
• For example, the following for loop prints the
first eight Fibonacci numbers −
Eg:
• An indefinite loop is
used when the • While loop
number of iterations
• Do… while loop
in a loop is
indeterminate or
unknown.
While loop
while (expression)
{
Statement(s) to be executed
if expression is true
}
var num = 5;
var factorial = 1;
while(num >=1) {
factorial = factorial * num;
num--;
}
console.log("The factorial is "+factorial);
do…while loop
• The do…while loop is
similar to the while
loop except that
the do...while loop
doesn’t evaluate the
condition for the first
time the loop
executes.
do {
Statement(s) to be executed;
} while (expression);
var n = 10;
do {
console.log(n);
n--;
} while(n> = 0);
Break
var i = 1
while(i< = 10) {
if (i % 5 == 0) {
console.log("The first multiple of 5 between 1
and 10 is : "+i)
break //exit the loop if the first multiple is found
}
i++
}
Continue
var num = 0
var count = 0;
for(num = 0;num< = 20;num++) {
if (num % 2 == 0) {
continue
}
count++
}
console.log(" The count of odd values between 0 and
20 is: "+count)
Functions
function name(parameter1, parameter2,
parameter3) {
// code to be executed
}
//define a function
function test() {
console.log("function called")
}
//call the function
test()
• Function names can contain letters, digits,
underscores, and dollar signs (same rules as
variables).
• The parentheses may include parameter
names separated by commas:
(parameter1, parameter2, ...)
• The code to be executed, by the function, is
placed inside curly brackets: {}
function factorial(num) {
if(num <= 0) {
return 1;
} else {
return (num * factorial(num-1) )
}
}
console.log(factorial(6))
Arrow Function
• ES6 introduces the concept of arrow function to
simplify the usage of anonymous function.
• There are 3 parts to an arrow function which are
as follows −
• Parameters − An arrow function may optionally
have parameters
• The fat arrow notation (=>) − It is also called as
the goes to operator
• Statements − Represents the function’s
instruction set
Syntax
//constructor function
function Student(rollno,firstName,lastName) {
this.rollno = rollno;
this.firstName = firstName;
this.lastName = lastName;
this.fullNameUsingAnonymous = function(){
setTimeout(function(){
//creates a new instance of this ,hides outer scope of this
console.log(this.firstName+ " "+this.lastName)
},2000)
}
this.fullNameUsingArrow = function(){
setTimeout(()=>{
//uses this instance of outer scope
console.log(this.firstName+ " "+this.lastName)
},3000)
}
}
const s1 = new
Student(101,'Mohammad','Mohtashim')
s1.fullNameUsingAnonymous();
s1.fullNameUsingArrow();
• When an anonymous function is used with setTimeout(), the function
gets invoked after 2000 milliseconds.
• A new instance of “this” is created and it shadows the instance of the
Student function.
• So, the value of this.firstName and this.lastName will be undefined.
• The function doesn't use the lexical scope or the context of current
execution.
• This problem can be solved by using an arrow function.
JavaScript Events
<body>
<p> Click the following button and see result</p>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>
onmousemove
<html>
<head>
<script type = "text/javascript">
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div> </body> </html>
Note
• An arrow function doesn’t have its own this
value and the arguments object.
• Therefore, you should not use it as an event
handler, a method of an object literal, a
prototype method, or when you have a
function that uses the arguments object.
JavaScript Classes
//creating an instance
var polyObj = new Polygon(10,20);
polyObj.test();
Setters and Getters
Setters
• A setter function is invoked when there is an attempt to set the
value of a property.
• The set keyword is used to define a setter function.
• The syntax for defining a setter function is given below −
{set prop(val) { . . . }}
{set [expression](val) { . . . }}
• prop is the name of the property to bind to the given function.
• val is an alias for the variable that holds the value attempted to be
assigned to property.
• expression with ES6, can be used as a property name to bind to
the given function.
class Student {
constructor(rno,fname,lname){
this.rno = rno
this.fname = fname
this.lname = lname
console.log('inside constructor')
}
set rollno(newRollno){
console.log("inside setter")
this.rno = newRollno
} } let s1 = new Student(101,'Sachin','Tendulkar')
console.log(s1)
//setter is called
s1.rollno = 201
console.log(s1)
The following example shows how to use
an expression as a property name with a setter
function.
let expr = 'name';
let obj = {
fname: 'Sachin',
set [expr](v) { this.fname = v; }
};
console.log(obj.fname);
obj.name = 'John';
console.log(obj.fname);
Getters
• Certain types in JavaScript are iterable (E.g. Array, Map etc.) while
others are not (E.g. Class).
• JavaScript types which are not iterable by default can be iterated by
using the iterable protocol.
• The following example defines a class named CustomerList which
stores multiple customer objects as an array.
• Each customer object has firstName and lastName properties.
• To make this class iterable, the class must
implement [Symbol.iterator]() function.
• This function returns an iterator object.
• The iterator object has a function next which returns an
object {value:'customer',done:true/false}.
//user defined iterable
//create customer objects
class CustomerList {
constructor(customers){
let c1={
//adding customer objects to an array firstName:'Sachin',
this.customers = [].concat(customers) lastName:'Tendulkar'
} }
//implement iterator function let c2={
[Symbol.iterator](){ firstName:'Rahul',
let count=0; lastName:'Dravid'
let customers = this.customers }
return {
//define a customer array and initialize it let
next:function(){
customers=[c1,c2]
//retrieving a customer object from the array
let customerVal = customers[count];
//pass customers to the class' constructor
count+=1; let customersObj = new
if(count<=customers.length){ CustomerList(customers);
return { //iterating using for..of
value:customerVal, for(let c of customersObj){
done:false console.log(c)
} }
} //iterating using the next() method
//return true if all customer objects are iterated
let iter = customersObj[Symbol.iterator]();
return {done:true}
}
console.log(iter.next())
} console.log(iter.next())
} console.log(iter.next())
Generator
Now, you see that the promise starts with the pending state with the value is
undefined.
The promise value will be returned later once the promise is completed.
•Once the promise reaches either fulfilled state or rejected state, it
stays in that state and can’t switch.
•In other words, a promise cannot go from the fulfilled state to the
rejected state and vice versa. It also cannot go back from the
fulfilled state or rejected state to the pending state.
•If the promise reaches fulfilled state or rejected state, the promise is
resolved.
Promise Methods
function errorHandler(err) {
console.log('Handling error', err)
}
function successHandler(result) {
console.log('Handling success', result)
}
console.log('end')
Promises Chaining
console.log('end')
• Promises are a clean way to implement async
programming in JavaScript (ES6 new feature).
• Prior to promises, Callbacks were used to
implement async programming.
JavaScript Callbacks
fetchRes.then(res =>
res.json()).then(d => {
console.log(d)