KEMBAR78
Javascript | PDF | Java Script | Document Object Model
0% found this document useful (0 votes)
10 views91 pages

Javascript

JavaScript, created by Brendan Eich in 1995 and standardized as ECMA-262 in 1997, is a dynamic, interpreted language that adds interactivity to web pages. It supports various data types, including strings, numbers, booleans, undefined, null, and NaN, and allows for the creation of functions, objects, and arrays. JavaScript also features concepts like hoisting, variable scope, and event handling, making it essential for modern web development.

Uploaded by

Manish0090
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views91 pages

Javascript

JavaScript, created by Brendan Eich in 1995 and standardized as ECMA-262 in 1997, is a dynamic, interpreted language that adds interactivity to web pages. It supports various data types, including strings, numbers, booleans, undefined, null, and NaN, and allows for the creation of functions, objects, and arrays. JavaScript also features concepts like hoisting, variable scope, and event handling, making it essential for modern web development.

Uploaded by

Manish0090
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 91

Javascript

JavaScript was invented by Brendan Eich in 1995, and became an


ECMA standard in 1997.
Javascript is scripting or interpreted language .i.e the code executes
line by line when the browser load the javascript into the memory.
ECMA-262 is the official name of the standard. ECMAScript is the
official name of the language.
When JavaScript was created, it initially had another name:
“LiveScript”. But Java language was very popular at that time, so it
was decided that positioning a new language as a “younger brother”
of Java
Why Javascript

★ If we want to execute any code on click of a button or text box value is changed we
use Javascript.
★ JavaScript adds behavior to the web page where the web page is capable of
responding to actions by your visitors without needing to load a new web page in
order to process their request.
★ We need JavaScript to add interaction to websites. Otherwise all sites would be
mostly read only static text and images or we'd need third party plug-ins like Adobe
Flash or Sun Java.
Javascript

➔ alert - prints to external window


➔ The Window.alert() method displays an alert dialog with the optional specified
content and an OK button.
➔ console - prints to the browser console window
➔ In a browser you will not see anything on the screen. It logs a message to a
debugging console.
● Here you can see the example for alert and console inside the same <script> tag.
● The alert will show the output in the form of dialog box.
● The console will print the output in the console window.
Javascript
❖ Inline JavaScript:
❖ Are loaded in the same page so is not necessary to trigger another request.
❖ They are executed immediately.

❖ External JS File:
❖ Instead of writing the same script numerous times, an external file can be called and
executed anywhere in the code.
❖ Much easier to analyse so you can debug more efficiently and read it.
DataTypes
Data Types
❖ In programming, data types is an important concept.
❖ To be able to operate on variables, it is important to know something about the type.
● String
● Number
● Boolean
● Undefined
● Null
● NAN
My first javascript program
Print the text with simple write function.

<!DOCTYPE html>
<html>
<body>
<h2>My first javascript program...</h2>
<script>
document.write('JavaScript is awesone...');
</script>
</body>
</html>
String
❏ Strings are used for storing text. Strings must be inside of either double or single
quotes.
❏ We can use single quotes or double quotes

Example:
var name = "john";
var city = ‘los vegas’;
Number
❏ There is only one type of Number in JavaScript. Numbers can be written with or
without a decimal point.
❏ Unlike many other programming languages, JavaScript does not define different
types of numbers, like integers, short, long, floating-point etc.
Example:
var salary = 2000; // 2000
Var number = 560e4 // 5600000
Boolean

❏ Boolean represents a logical entity and can have two values: true, and false.
❏ Think of a boolean as an on/off or a yes/no switch.

Example:
var married = true;
Undefined and Null

Undefined:
❏ A variable that has not been assigned a value has the value undefined.
❏ This is one of the JavaScript’s primitive types.

Null:
❏ The value null represents the intentional absence of any object value.
❏ Null is not an identifier for a property of the global object, like undefined.
Difference between Undefined and null
var x;
alert(x); //undefined

var x = null;
alert(x); //null
NAN
❏ Any operation which we perform on a number and does not result a number is
considered as NAN
❏ The global NaN property is a value representing Not-A-Number.
❏ NaN always compares unequal to any number, including NaN.

Example:
var p = 10 + undefined;
console.log(p);
var q = 10/"john";
console.log(q);
Every thing is var. JS is
dynamically typed languges
Dynamically typed:
➢ Dynamically-typed languages are those (like JavaScript) where the interpreter
assigns variables to a type at runtime based on the variable's value at the time.
➢ For instance, The idea of dynamic types is that makes code flexible, i.e. if you’ve got
a function which returns a number,
➢ you don’t actually have to return a number, you can return anything you like.
== vs === in JS
● == only compares values.
● === compares values and its type.
Example:
var x = "20";
var y = 20;

if(x == y){
alert('x value is equal to y');
}
else
{
alert('x value is not equal to y');
}
=== checks whehter lhs and rhs are
same data type
● The identity operator returns true if the operands are strictly equal (see above) with
no type conversion.
Example:
var x = "20";
var y = 20;
if(x === y){
alert('x value is equal to y');
}
else
{
alert('x value is not equal to y');
}
Comparision with 0 and 1

var x = true;
var y = 1;

if(y == x){
alert('true');
}
else
{
alert('false');
}
1 is true in JS

var x = false;
var y = 0;

if(y == x){
alert('true');
}
else
{
alert('false');
}
var y = 10;

if(y){
alert('true');
}
else
{
alert('false');
}
If variable contains value it is
considered as true

var y = 10;
if(y){
alert('true');
}
else
{
alert('false');
}
Undefined is false in JS
● Undefined most typically means a variable has been declared, but
its value not defined.

var y;
if(y){
alert('true');
}
else
{
alert('false');
}
Null is false in JS

var x = true;
var y=null;

if(y){
alert('true');
}
else
{
alert('false');
}
NAN is false in JS

var x = true;
var y=5/"john"; //nan
if(y){
alert('true');
}
else
{
alert('false');
}
Type Coercion
Type Coercion
● Converting from One Data type another Datatype is called as type coercion

var x = 10 + "10"; output 1010


var l = 100/"10"; output 10

● The number 10 is converted to string 10


● String 10 is converted as number 10
Arrays
Arrays
● Arrays are used to hold multiple values at the same time.
● 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.

Example:

var primenum=[1,3,5,7,"govardhan",true]// simple string array


primenum[0]; // access first element in the array
Loop through Arrays

● JavaScript has powerful semantics for looping through arrays and array-like objects.
● The 'for' loop is the most compact form of looping.
● You have three options in ECMAScript 5 ("ES5"), the version most broadly supported
at the moment, and two more added in ECMAScript 2015,
○ ForEach.
○ ForIn.

}
for

for (var index = 0; index < array.length; index++) {


const element = array[index];
console.log(element);

}
Push and Pop

● If we want to insert an item at the end, use push


● If we want to remove an item at the end, use pop
● Push and pop at the end of the array
● They are used to add or remove elements at the end of
array.
Example
var fruits = ['apple','mango','banana'];

console.log(fruits);

fruits.push('chikko');

console.log(fruits);

fruits.pop();

console.log(fruits);
Unshift and shift

● If we want to insert an item at the first, use unshift


● If we want to remove an item from the start, use shift
● Shift and unshift at the start of the array.
● They are used to add or remove elements at the start of the
array.
Example
var fruits = ['apple','mango','banana'];

console.log(fruits);

fruits.unshift('chikko');

console.log(fruits);

fruits.shift();

console.log(fruits);
Objects
Object
● Object is collection of Properties and methods. In Javascript static objects available.
● A JavaScript object has properties associated with it. A property of an object can be
explained as a variable that is attached to the object.

Example :

var employee = {
name: "david",
age:27,
married : true
}
Accessing properties of Objects

employee.name; //dot notation


employee["age"]; // array notation

● Javascript object properties are mutable mean they can be created on the fly even if
they don’t exists at the time of creation.
Demo - display object in the console
Loop through properties of Object

● you may need to loop through Objects in JavaScript. The only way to do so
before ES6 is with a for...in loop
Example:

for (var prop in employee){


console.log(prop);
console.log(employee[prop]);
}
Debugging javascript

● Programming code might contain syntax errors, or logical errors.


● Searching and fixing errors in programming code is called code debugging.
● We need to use chrome developer tools source window for debugging.
● Use the F10 and F11 keys to start and stop the debugging.
● The debugging is similar to any programming language debugging like c and c++
Array of objects
See notes
Functions
Functions

● Functions are considered as the first class citizens in Javascript.


● A function is a group of reusable code which can be called anywhere in your
program.
● This eliminates the need of writing the same code again and again.

Example:

function add(x,y){
return x + y;
}
var p = add(10,20);
console.log(p);
Function Parameters

● If we call a function with more than defined parameters the extra parameters are
ignored
● If we call a function with less than required parameters than the additional
parameters will be undefined
● Function overloading is not possible in Javascript
○ I.e if we have two functions with same name with different number of
parameters in the memory only the function defined at the end is available
function add(x,y){
return x + y;
}
var p = add(10,20);

var p = add(10,20,30); //30 extra parameters are ignored


var k = add(10); // nan un supplied parameters will be undefined
console.log(p);
console.log(k);
Function overloading?
function add(x,y,z){
return x+y+z;
}
function add(x,y){
return x + y;
}

var p = add(10,20,30); //?


var k = add(10,20); // ?
var z = add(10); // ?
console.log(p);
console.log(k);
function add(x,y){
return x + y;
}
function add(x,y,z){
return x+y+z;
}
var p = add(10,20,30); //60
var k = add(10,20); // nan un supplied parameters will be undefined
console.log(p);
console.log(k);
hoisting
Hoisting

❏ All functions and variable declarations on a given js file are moved to the top of stack
before actual execution of the JS file starts from line by line.
❏ In JavaScript, a variable can be declared after it has been used.
❏ In other words, a variable can be used before it has been declared.
❏ Hoisting is a JavaScript mechanism where variables and function declarations are
moved to the top of their scope before code execution.
Function hoisting
var p = add(10,20,30); //60
var k = add(10); // nan un supplied parameters will be undefined
console.log(p);
console.log(k);

function add(x,y){
return x + y;
}
function add(x,y,z){
return x+y+z;
}
Variable hoisting

alert(y); // y is not defined


alert(x); // undefined => x value is hoisted
var x = 10;
alert(x); // print 10
Variable Scope - var
function add(x, y)

In Javascript if we define a variable with {


if (x > 9)
key word var then that variable is {
available in complete function even if is var p = 20;
defined in block like if or for. }
console.log(p);
//console.log(p) - ? return x + y;
}
var z = add(10, 20);
console.log(z);
Variable Scope - let
function add(x, y)

In Javascript if we define a variable with {


if (x > 9)
key word Let then that variable is {
available in complete function even if is let p = 20;
defined in block like if or for }
console.log(p);
Let variables are not hoisted.. return x + y;
}
//console.log(p) - ? var z = add(10, 20);
console.log(z);
Anonymous functions
var myAdd = function (x,y){
return x + y;
}

// variable can hold a function

console.log(myAdd );
var p = myAdd(20,30);
console.log(p);
Return function as output from another
function
In Javascript we can return the function a()
function as output from another {
function
alert('A!');
function b() {
alert('B!');

}
return b; // return function reference
}
var s = a(); //s holds refernce to b function
s();
pass function as parameter to another
function
In Javascript we can pass the var z = function()
function as parameter to another {
function console.log('angular');
}
function abc(p,q){
p();
console.log(q);
}
abc(z,20);
DOM and Events
DOM - it is a object
representation of the html
elements present in the
document
DOM
DOM Methods

● document.getElementById(id)

● document.getElementsByTagName(name)

● document.getElementsByClassName(name)

Example :

document.getElementById("abc").innerHTML = "Welcome to Javascript";


Events
click event

● The onclick attribute fires on a mouse click on the element.


● Whenever user clicks on a button we want to validate username and password
whether they are entered or not . we use events there.
● You can put your validation, warning etc.
click event
<div id="displayDiv">
function validateLogin(){
userName : <input type="text" id="userName">
</div> var userValue =
<div> document.getElementById("userName")
password : <input type="password"
id="password"> .value;
</div> if(userValue == ""){
<div>
<button id="loginButton" alert("user name is required");
onclick="validateLogin()">Login</button> }
</div>
}
DOM Events
❖ When a user clicks the mouse
❖ When a web page has loaded
❖ When an image has been loaded
❖ When the mouse moves over an element
❖ When an input field is changed
❖ When an HTML form is submitted
❖ When a user strokes a key
OnChange

● The onchange attribute fires the moment when the value of the element is changed.
● Execute a JavaScript when a user changes the selected option of a <select>
element.
● When user changes values in the given input control then onchange event gets
raised.
● We use this event if we want to typically do validations or copy the data of the given
control to another control.
OnChange
<div id="displayDiv"> function copyValueToAnother(){
userName : <input type="text"
id="userName" var userNameValue =
onchange="copyValueToAnother()"> document.getElementById("userName").
</div> value;
<div id="usernamerequired"
class="redBackground"> document.getElementById("duplicateNa
user name is required: me").value = userNameValue;
</div> }
<div>
duplicate name : <input type="text"
id="duplicateName">
</div>
OnKeyPress
● The keypress event is fired when a key that produces a character value is pressed
down.
● Examples of keys that produce a character value are alphabetic, numeric, and
punctuation keys.
● KeyboardEvent objects describe a user interaction with the keyboard. Each event
describes a key.
● We are going to use this event to accept only given characters.

Example :

● Allow only numbers in a text box.


OnKeyPress

<div id="displayDiv"> function allowOnlyNumbers(evt){


userName : <input type="text" if(evt.keyCode <48 || evt.keyCode
id="userName" >57 ){
onkeypress="allowOnlyNumbers(event) evt.preventDefault();
"> }
</div> }
addEventListener
● We use addEventListner if we want to attach the event from the javascript instead
from the html only
● It accepts 2 parameters
★ Event
★ Eventlistener

document.getElementById("userName").addEventListener("change",copyValueToA
nother);
Mouse events
❖ Whenever we hover a mouse an element or mouse out from an element if we want
to execute any code we can use the mouse events.

➢ Mouseover
■ The mouseup event is fired when a pointing device button is released
over an element.
➢ Mouseout
■ The mousedown event is fired when a pointing device button is pressed
on an element.
mouseover ,mouseout

<div function addSomeText(currentElement)


onmouseover="addSomeText(this)" {
onmouseout="changeText(this)"> currentElement.innerText =
some text "Welcome to Hover";
</div> }

function
changeText(currentElement){
currentElement.innerText = "you
have moved from the div element";
window.onload
When we want to execute the some code or function which is defined in the script once
the html document is loaded mean all the dom has been initialized.

● We use to access the elements


○ To fetch the values
○ Set the values
○ Attach the events
○ Set styles
Example

<body bgcolor = "cyan">


<div id="displayDiv">
userMobile : <input type="text" id="userMobile">
</div>
<script>
window.onload = function() {
document.getElementById("userMobile").addEventListener("keypress", allowOnlyNumbers)
}
function allowOnlyNumbers(evt){
if(evt.keyCode <48 || evt.keyCode >57 ){
evt.preventDefault();
}}
</script>
</body>
JSON
● JSON is serialized representation of javascript object.
● The JSON format was originally specified by Douglas Crockford, and is described in
RFC 4627.
● The official Internet media type for JSON is application/json.
● The JSON filename extension is .json.
● It is easy for humans to read and write. It is easy for machines to parse and
generate.
● It is based on a subset of the JavaScript Programming Language.
● These properties make JSON an ideal data-interchange language.
var employee = {name:'john',age:20,salary:4000};
console.log(employee.name);

console.log(employee);

var empJSON = JSON.stringify(employee);


console.log(empJSON.age);
console.log(empJSON);
var employee = { console.log(employee);
name:"john", var x = employee.name;
age:23, var empJSON =
married :true JSON.stringify(employee);
} console.log(empJSON);
var y = empJSON;
● Advantage : Let assume that we are create three BankAccount objects
johnAccount,kevinAccount,DavidAccount how it was memory allocate
background johnAccount object has accountName, accountNumber,balance
and withDraw ,deposit methods same way kevin object also these
accountName, Acconutumber,balance and withDraw ,deposit methods also
same way davidAccount Account Name, Acconutumber,balance and
withDraw ,deposit methods but there is only one method with name
drawcheck its prototype function its not going having own that function its
member function it going having inside object function
javascript closures:
*)javascript variables can belong to the local or global scope.

*)global variable can be made local with closures.


global variables:

->A function can access all variables defined inside the function,like this

example:

function myFunction() {

var a = 4;

return a * a;

}
Local variables:
->But a function can access all variables defined outside the function also,

example:

var a = 4

function myFunction() {

return a * a;

}
variable lifetime:
->Global variables live as long as your application(your window/your webpage) lives.

->local variables have short lives. they are created when the function is invoked, and
deleted when the function is finished.

Global and local variables are with same name but different variables.Modifying one,does
not modify the other.
A Counter Dilemma:
->Suppose you want to use a variable for counting something, and you want this counter
to be available to all functions.

You could use a global variable, and a function to increase the counter:
1.example

var counter = 0; //call add() 3


times

// Function to increment counter add();

function add() { add();

counter += 1; add();
2.Example
var counter = 0; }

// Function to increment counter // call add() 3 times

function add() { add();

var counter = 0; add();

counter += 1; add();
3.Example
// Function to increment counter }

function add() { //call add() 3


times

var counter = 0; add();

counter += 1; add();

return counter; add();


JavaScript Nested Functions:
->All functions have access to the global scope.

->In fact, in JavaScript, all functions have access to the scope "above" them.

->JavaScript supports nested functions. Nested functions have access to the scope
"above" them.

->In this example, the inner function plus() has access to the counter variable in the
parent function:
Example
function add() {

var counter = 0;

function plus() {counter += 1;}

plus();

return counter;

}
JavaScript Closures:
->Remember self-invoking functions? What does this function do?

Example })();

var add = (function () { add();

var counter = 0; add();

return function () {counter += 1; return counter} add();

//
the counter is now 3

You might also like