Sunteți pe pagina 1din 86

CDE TEAM EVENTS

JAVASCRIPT
CDE TEAM EVENTS

GETTING STARTED WITH THE WEB

What’s happening in background ?


CDE TEAM EVENTS

CLIENTS AND SERVERS

▸ Clients : Devices connected to internet & Web-accessing


softwares

▸ Servers: Computers that store webpages, websites or apps.


CDE TEAM EVENTS

INTRODUCTION TO JAVASCRIPT

Getting Started !
CDE TEAM EVENTS

INTRODUCTION TO JAVASCRIPT
▸ Invented by Brendan Eich at NetScape

▸ Originally named as Mocha

▸ Then LiveScript

▸ Then JavaScript

▸ First shipped in NetScape Navigator 2.0 in 1995

▸ Submitted to ECMA International in November 1996

▸ First ECMAScript appeared in June 1997


CDE TEAM EVENTS

JAVASCRIPT MISCONCEPTION
▸ JavaScript is not Java

▸ It’s not simplified ‘Script’

▸ It’s for Browser only.

▸ It’s not like other Languages

▸ It’s Inconsistent and Buggy


CDE TEAM EVENTS

WHAT IS JAVASCRIPT ?
▸ JavaScript is a Programming Language

▸ Add’s interactivity/behaviour to HTML pages.

▸ It can react to User Input

▸ It can process and store data

▸ It can make changes to HTML Page


CDE TEAM EVENTS

WHERE CAN I WRITE MY


JAVASCRIPT CODE ?

JavaScript in HTML
CDE TEAM EVENTS

WHAT IS JAVASCRIPT ?
<!DOCTYPE html>

<html>

<head>

<script> // Valid </script>

</head>

<body>

<script> // Valid </script>

</body>

</html>
CDE TEAM EVENTS

HELLO JAVASCRIPT !

JavaScript Basics
CDE TEAM EVENTS

JAVASCRIPT LANGUAGE BASICS


▸ Syntax: JavaScript Syntax heavily borrows from C &
C-Like Languages such as Java and Perl.

▸ Case-Sensitivity: The first concept to understand is


that everything is case-sensitive; variables, function
names and operators.

▸ The variable name is different from Name.


CDE TEAM EVENTS

IDENTIFIERS
▸ An Identifier is the name given to a variable,
function, property or function argument.

▸ The first character must be a letter (or) _ (or) $

▸ All other characters may be letters, _, $ and numbers.

▸ Ex: myCar, number1, number2, _temp


CDE TEAM EVENTS

STATEMENTS
▸ Statements in JavaScript are terminated by a semicolon.
But not must.

▸ var sum = a + b // valid - not recommended

▸ var diff = a - b ; // valid - recommended

▸ Multiple statements can be combined into a code of block


by using C-like syntax. 

if(a == 2){

sum = a + 3;

}
CDE TEAM EVENTS

COMMENTS
▸ JavaScript uses C-style comments for both single-line
and multi-line comments.

▸ // single line comment

▸ /*

* This is multi line

* comments

*/
CDE TEAM EVENTS

VARIABLES
▸ JS variables are loosely typed, meaning that a variable
can hold any type of data.

▸ To define a variable, use the var keyword followed by


variable name.

▸ var message; // declaration

▸ var sayHello = “Hello World” // initialisation


CDE TEAM EVENTS

OPERATORS
▸ Identically Equal (===) and Not Identically (!==) Equal
operators do the same things as equal and not equal,
except that they do not convert operands before testing
the equality.

▸ Ex:


var result1 = ( “55” == 55 ); // returns true


var result2 = ( “66” === 66 ); // returns false
CDE TEAM EVENTS

DATA TYPES
▸ There are 5 simple(Primitive) data types :

1. Undefined

2. Null

3. Boolean

4. Number

5. String

▸ One complex data type :



Object (un-ordered list of name-value pairs)
CDE TEAM EVENTS

UNDEFINED
▸ The Undefined type has only one value, which the
special value of undefined.

▸ When a variable is defined using var operator but not


initialised, it is assigned the value of undefined.

▸ Ex: var message;

▸ typeof(message) // prints undefined


CDE TEAM EVENTS

NULL
▸ The Null type has only one value, which the special value
of null.

▸ Logically, a null value is an empty object pointer, which is


why typeof returns “object” when it’s passed a null value.

▸ Ex: var car = null;

▸ typeof(car) // prints object


CDE TEAM EVENTS

BOOLEAN
▸ The Boolean type has only two literal values, true and
false.

▸ Ex: var found = true;

▸ typeof(found) // prints boolean


CDE TEAM EVENTS

NUMBER
▸ The most interesting data type in JavaScript is Number, which
uses IEEE-754 format to represent both integer and floating-
point values.

▸ var intNumber = 58; // integer

▸ var floatNumber = 5.8; // float

▸ There is a special numeric value called NaN (Not a Number),


which is used to indicate when an operation intended to
return a number has failed.

▸ isNaN(“blue”); // prints true


CDE TEAM EVENTS

STRING
▸ A String data type represents a sequence of zero or more
16-bit unicode characters.

▸ String can be delineated by either double or single


quotes;

▸ Ex: 

var firstName = “Sasidhar”; 

var lastName = ‘Kola’;
CDE TEAM EVENTS

TYPEOF OPERATOR
▸ Because JS is loosely typed, there needs to be a way to
determine the data type of a give variable.

▸ The typeof operator provides that information.

▸ typeof operator on a value returns one of the following as string:



* “undefined”

* “boolean”

* “string”

* “number”

* “object”

* “function”
CDE TEAM EVENTS

SAYHELLO ( “JAVASCRIPT “ );

JavaScript Functions
CDE TEAM EVENTS

FUNCTIONS
▸ Functions are the core of any programming language.

▸ They allow the encapsulation of statements that can be


run anywhere and at any time.

▸ Functions are declared using the function keyword,


followed by set of arguments and then the body of the
function.

▸ Syntax: function functionName (arg0, arg1, …. argN) {



// statements

}
CDE TEAM EVENTS

NO OVERLOADING
▸ JavaScript functions can’t be overloaded in the traditional sense like
in other Programming Languages.

▸ Ex:

function addNumber(num){

return num + 100;

}


function addNumber(num){

return num + 200;

}


addNumber(100); // prints 300
CDE TEAM EVENTS

VAR NUMBERS = [1,2,3,4,5,6];

Introduction to JavaScript Arrays


CDE TEAM EVENTS

ARRAYS
▸ An Array in JS is very different from arrays in other programming languages.

▸ Unlike other languages, arrays in JS holds any type of data in each slot.

▸ ex:

var colours = new Array ( ) ;


var colours = new Array ( 20 ) ;


var colours = new Array ( “red”, “green”, “blue” ) ;


var colours = [ ] ;


var colours = [ “red”, “green”, “blue” ];
CDE TEAM EVENTS

ARRAY STACK & QUEUE METHODS


▸ One of the most interesting thing about JS arrays is that
they provide a method to make an array behave like
other data structures.

▸ An array can acts as STACK (LIFO).

▸ push( ) & pop( )

▸ An array can also acts as Queue (FIFO)

▸ push( ) & shift( )


CDE TEAM EVENTS

VAR OBJ = NEW OBJECT ( );

Introduction to JavaScript Objects


CDE TEAM EVENTS

OBJECTS
▸ Objects in JavaScript start out as nonspecific groups of
data and functionality.

▸ Objects are created by using the new operator followed


by the object name.

▸ Ex: 

var user = new Object ( );

user.name = “Sasidhar”; // assign property


document.write(user.name); // access property
CDE TEAM EVENTS

OBJECT LITERAL NOTATION


▸ Object literal notation follows key-value pairs.

▸ Key must be string.

▸ Value can be any valid JavaScript data type.

▸ Ex: 

var user = { first_name: ‘Sasidhar’ };

user.last_name = “Sasidhar”; // assign property


document.write(user.first_name + user.last_name); 

// access property
CDE TEAM EVENTS

STRING.REVERSE( )

String Methods
CDE TEAM EVENTS

STRING METHODS
▸ var name = “Aditya”;

▸ var length = name.length;

▸ var firstChar = name.charAt ( 0 );

▸ var fullName = name.concat( ‘College’);

▸ var index = name.indexOf ( ‘i’ );

▸ var subStr = name.substr( 0 , 3 );

▸ name.toUpperCase() | name.toLowerCase();
CDE TEAM EVENTS

DATE.NOW ( )

Date Methods
CDE TEAM EVENTS

DATE
▸ var date = new Date ( );

▸ document.write(date);

▸ document.write(date.getDate());

▸ document.write(date.getMonth());

▸ document.write(date.getFullYear());

▸ document.write(date.getTime());

▸ document.write(date.getHours());

▸ document.write(date.getMinutes());
CDE TEAM EVENTS

MATH.RANDOM( )

Math Methods
CDE TEAM EVENTS

MATH
▸ var random = Math.random( );

▸ var squareResult = Math.sqrt( 5 );

▸ var ceilResult = Math.ceil( 5.7 );

▸ var floorResult = Math.floor( 5.4 );

▸ var powResult = Math.pow(5, 2);

▸ var cosResult = Math.cos(0);

▸ var sinResult = Math.sin(0);


CDE TEAM EVENTS

STRING ( 10 );

Type Conversion
CDE TEAM EVENTS

TYPE CONVERSION
▸ JavaScript variables can be converted to a new variable and
another data type by using


1. A JavaScript function


2. Automatically by JS itself

▸ Eg: 

String ( 20 );


Boolean ( 20 );

CDE TEAM EVENTS

CONVERT TO STRING
▸ String ( 10 ); | 20.toString ( );

▸ 3.14159.toFixed( 2 );

▸ String ( false ); | false.toString ( );

▸ String ( new Date ( ) );

▸ new Date ( ).toString( );


CDE TEAM EVENTS

CONVERT TO NUMBER
▸ Number ( “24.8” );

▸ Number ( “ “ ) ; // prints 0

▸ Number ( “12 24”) // NaN

▸ parseInt ( ); | parseFloat ( );

▸ var a = “10”; 

var b = + a; // b is a number
CDE TEAM EVENTS

CONVERT TO NUMBER
▸ Number ( “24.8” );

▸ Number ( “ “ ) ; // prints 0

▸ Number ( “12 24”) // NaN

▸ parseInt ( ); | parseFloat ( );

▸ var a = “10”; 

var b = + y; // b is a number

▸ Number ( false ) // 0

▸ Number ( null ) // 0
CDE TEAM EVENTS

CONVERT TO BOOLEAN
▸ Boolean ( “Aditya” ); // true

▸ Boolean ( ““ ); // false

▸ Boolean ( 1 ); // true

▸ Boolean ( 0 ); // false

▸ Boolean ( null ); // false

▸ Boolean ( undefined ); // false


CDE TEAM EVENTS

HEY ! I’M VISIBLE

Scope
CDE TEAM EVENTS

SCOPE
▸ In JS there are two types of scopes

1. Local


2. Global

▸ JS has function scope.

▸ JS doesn’t have block level scope.

▸ If you assign a value to a variable that has not been declared, it


becomes a Global
CDE TEAM EVENTS

HELLO DOM !

Document Object Model


CDE TEAM EVENTS

WHAT IS DOM ?
▸ Whenever a web page loads into the browser, it creates
Document Object Modal of that page.

▸ The HTML DOM is constructed as a tree of Nodes.


CDE TEAM EVENTS

HTML
<!DOCTYPE html>

<html>

<head>

<title> My Title </title>

</head>

<body>

<a href=“”> My links </a>

<h1> My header </h1>

</body>

</html>
CDE TEAM EVENTS

DOM REPRESENTATION
CDE TEAM EVENTS

POWER UP JAVASCRIPT
▸ With the object model, JS gets all the power it needs to create
dynamic HTML.

▸ JS can add, modify and remove all HTML elements & attributes.

▸ JS can change all the CSS.

▸ JS can react to all HTML events.

▸ JS can create new HTML events.


CDE TEAM EVENTS

HTML DOM METHODS


▸ In the DOM, all the HTML elements are defined as Objects.

▸ Properties: Values of HTML elements.

▸ Methods: Actions you can perform of HTML elements.

▸ e.g.: 

document.getElementById( “test” ).innerHTML = “Hello

DOM” ;
CDE TEAM EVENTS

DOCUMENT OBJECT
▸ document object is the owner of all other objects in web
page.

▸ If you want to access any element in an HTML page, you


always start with accessing the document object.

▸ e.g.: 

document.write ( “Hello DOM” );
CDE TEAM EVENTS

FINDING HTML ELEMENTS


▸ The easiest way to find an HTML element is, by using ID.

▸ document.getElementById(“element_id”);

▸ Other ways are, using Class name & Tag name

▸ document.getElementsByClassName(“red”);

▸ document.getElementsByTagName(“p”);
CDE TEAM EVENTS

MODIFYING HTML CONTENT


▸ document.write ( ) is used to write directly on HTML
output stream.

▸ The easiest way to modify the HTML content is, by using


innerHTML property.

▸ Syntax: 

document.getElementById(id).innerHTML = new HTML;
CDE TEAM EVENTS

MODIFYING HTML ATTRIBUTES


▸ To change the value of an HTML attribute, use this
syntax:


document.getElementById(id).attribute = new Value;

MODIFYING CSS
▸ To change the style of an HTML element, use this syntax:

document.getElementById(id).style.property = new style
CDE TEAM EVENTS

HTML DOM EVENTS


▸ DOM allows JS to react to HTML events.

▸ When an event occurs, JavaScript can be executed.

▸ e.g.: 

1. Mouse Clicked

2. Key Pressed

▸ Syntax:

<element event=“js_function()”>
CDE TEAM EVENTS

HTML DOM EVENTLISTENERS


▸ The addEventListener() method attaches an event handler to the specified
element.

▸ The addEventListener() method attaches an event handler to an element


without overwriting existing event handlers.

▸ You can add many event handlers to one element.

▸ You can add many event handlers of the same type to one element, i.e two
"click" events.

▸ Syntax:

element.addEventListener ( event, function, useCapture );

CDE TEAM EVENTS

FORMS
▸ document.forms returns all the available forms in your
HTML page as a collection.

▸ We can access form input value by using the following


syntax:


document.forms[formName][inputName].value

CDE TEAM EVENTS

CREATING NEW HTML ELEMENTS


▸ To add a new element to the HTML DOM, you must create the
element (element node) first, and then append it to an existing

element.

▸ Steps to be followed:

1. Create element by using document.createElement(element);


2. Create a Node by using document.createTextNode(text);


3. Append to parent by using parent.appendChild(childNode);


CDE TEAM EVENTS

CREATING NEW HTML ELEMENTS


▸ To add a new element to the HTML DOM, you must create the
element (element node) first, and then append it to an existing

element.

▸ Steps to be followed:

1. Create element by using document.createElement(element);


2. Create a Node by using document.createTextNode(text);


3. Append to parent by using parent.appendChild(childNode);

▸ insertBefore ( ) // to insert new HTML before the specific element


CDE TEAM EVENTS

REMOVE & REPLACE HTML ELEMENTS


▸ removeChild ( ) // to remove existing HTML element.

▸ replaceChild ( ) // to remove existing HTML element.


CDE TEAM EVENTS

DOM TRAVERSING
▸ With the HTML DOM, you can navigate the node tree using
node relationships.

▸ Node Relationships:

1. In a node tree, the top node is called the root (or root node).


2. Every node has exactly one parent, except the root (which has

no parent).


3. A node can have a number of children.


4. Siblings (brothers or sisters) are nodes with the same parent.


CDE TEAM EVENTS

TRAVEL BETWEEN NODES


▸ You can use the following node properties to navigate
between nodes with JavaScript:


1. parentNode


2. childNodes [ node index ]


3. firstChild


4. lastChild


5. nextSibling


6. previousSibling
CDE TEAM EVENTS

HELLO BOM !

Browser Object Model


CDE TEAM EVENTS

BROWSER OBJECT MODEL


▸ There are no official standards for the Browser Object
Model (BOM).

▸ The window object is supported by all browsers. It


represents the browser's window.

▸ All global JavaScript objects, functions, and variables


automatically become members of the window object.

▸ Even the document object (of the HTML DOM) is a property


of the window object.
CDE TEAM EVENTS

WINDOW OPERATION
▸ window.open ( ‘url’ ); // opens a new window

▸ window.close ( ); // closes the current window

▸ window.resizeTo ( width, height ); // resize the window

▸ window.move ( x, y ); // move window to x, y positions


CDE TEAM EVENTS

SCREEN
▸ The window.screen object contains information about
the user's screen.

▸ The window.screen object can be written without the


window prefix.

▸ screen.width ▸ screen.availHeight

▸ screen.height ▸ screen.colorDepth

▸ screen.availWidth ▸ screen.pixelDepth
CDE TEAM EVENTS

LOCATION
▸ The window.location object can be used to get the
current page address (URL) and to redirect the browser
to a new page.

▸ location.href

▸ location.hostname

▸ location. pathname

▸ location. protocol
CDE TEAM EVENTS

HISTORY
▸ The window.history object contains the browsers history.

▸ history.back( ) // to load previous url

▸ history.forward( ) // to load next url


CDE TEAM EVENTS

POPUPS
▸ JavaScript has three kind of popup boxes: 

1. Alert box 

2.Confirm box

3. Prompt box.
CDE TEAM EVENTS

TIMING FUNCTIONS
▸ setTimeout(function, milliseconds) ;

Executes a function, after waiting a specified number of


milliseconds.

▸ setInterval(function, milliseconds);

Same as setTimeout(), but repeats the execution of the


function continuously.
CDE TEAM EVENTS

THE NEW JAVASCRIPT !!

ES 6
CDE TEAM EVENTS

CONSTANTS
▸ ES6 Support for constants (also known as "immutable
variables”).

▸ Syntax: 

const constant_name = value;

▸ e.g.: 

const PI = 3.141593;
CDE TEAM EVENTS

SCOPING
▸ ES6 Support for block-level scope.

▸ Syntax: 

let variable_name = value;

▸ e.g.: 

let name = “Aditya”;
CDE TEAM EVENTS

ARROW FUNCTIONS
▸ ES6 Support for arrow functions.

▸ Syntax: 

let variable_name = ( arg1, arg2 ) => {

// function definition

};

▸ e.g.: 

let add = ( num1, num2) => {

return num1 + num2;

}
CDE TEAM EVENTS

TEMPLATE LITERALS
▸ ES6 Support for template literals (also known as
Template Strings).

▸ Back quote ( ` , ` ) characters are used to create Template


literals.

▸ $ { variable_name } is used to print the variable.

▸ e.g: 

var message = `Hello, this ${ name} from ${college}`;
CDE TEAM EVENTS

CLASSES

ES 6 CONT.
CDE TEAM EVENTS

CLASSES
▸ ES6 Support for Classes.

▸ class keyword is used to define classes

▸ Syntax: 

class ClassName {

// class definition

}

▸ e.g.:

class Person {

}
CDE TEAM EVENTS

CONSTRUCTOR (CLASSES CONT.)


▸ e.g.:


class Student {

constructor (id, name) { 

this.id = id;

this.name = name;

}

}
CDE TEAM EVENTS

INHERITANCE (CLASSES CONT.)


▸ extends keyword is used to achieve the inheritance in
ES6.

▸ super keyword is used to call the super class from child


class.

▸ Syntax:

class Student extends User {

// class definition

}
CDE TEAM EVENTS

STATIC MEMBERS (CLASSES CONT.)


▸ static keyword is used to define static members of a
class.

▸ Syntax:

class ClassName {

static classMemberName = () => {


}

}
CDE TEAM EVENTS

SETTERS & GETTERS (CLASSES CONT.)


▸ set keyword is used to define setters.

▸ get keyword is used to define getters.

▸ Syntax:

class ClassName {

get getterName() { }

set setterName() {}

}
CDE TEAM EVENTS

SETS & MAPS

ES 6 CONT.
CDE TEAM EVENTS

SETS
▸ SETs are cleaner data structures to hold unique values

▸ Sets are defined by creating a new object to Set class.

▸ add method is used to append new element

▸ delete(value) method is used to remove element

▸ clear method is used remove all the elements

▸ has method is used to check the element existence 



CDE TEAM EVENTS

MAPS
▸ MAPs are cleaner data structures to hold unique values

▸ Maps are defined by creating a new object to Map class.

▸ set method sets a value for key in map object

▸ get (key) method is used to get value for key

▸ clear method is used remove all key & value pairs

▸ delete(key) method is used to remove element from map


S-ar putea să vă placă și