Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views14 pages

JavaScript

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 14

 JavaScript is an interpreted language and requires no compilation.

 JavaScript is case sensitive and constitutes statements.

 The semicolon is the best way to separate the statements.

 JavaScript is insensitive to whitespace.

 Script tags holding JavaScript code are best placed at the end of the code.

 Comments start with // or /* and */

You can create HTML elements using Javascript. Consider the following HTML
code

<body>
<p>Some text</p>
</body>

Now you need to create a <p> tag inside <body> using Javascript. How can
you do that? Take a look at the following code snippet.

var myParagraph = document.createElement("p"); // Create a <p> element


var myText = document.createTextNode("text added using JS");
// Create a text node that has the text for <p>
myParagraph.appendChild(myText); // Append the text to <p>
document.body.appendChild(myParagraph); // Append <p> to <body>

You can see that Javascript makes use of three methods i.e. createElement(),
createTextNode(), and appendChild() to create a HTML element and append
them in your HTML.

Primitive JavaScript data types:

String [ "Howdy"]
Number [ 23, 482.038]
Boolean [ true, false ]
Null [ null value ]
Undefined [ value not defined ]
Objects
Symbol

 Numbers are only double precision 64-bit values. There are no integers in JS. For example – 42 or
42.39794
 Strings are to store characters.
 Booleans are true and false.
 Undefined is unique to JavaScript. It is a data type assigned to variables that are declared as
variables but not assigned any values.
 Null is a type to denote null value.
 Variables are the identifiers to store data values in our code.
 var is the keyword to declare a variable.
 ‘=’ is the operator to assign a value to a variable.
 A variable must start with _ or $ or letter. 99temp is invalid whereas _99temp is valid.
 In ES2015(known as ECMAscript), two other ways to declare variables were introduced- let and
const. We can use these 2 keywords to define variables(now recommended)

the following operators available in JavaScript:


 Assignment operators
 Arithmetic operators
 Comparison operators
 Logical operators
 String operators
 Conditional operators
== compares the operands and returns true without considering their data type. Ex: var a = 10, b= “10”;
if(a==b) results in true due to the same value they carry, but ignores data types differentiation.
However, if(a===b) results in false as they are of different data types.

While concatenating, JavaScript treats all data types as strings even if values are of different data types.

Conditions - If, Else, Else If


Syntax:
if (condition 1)
{ Execute code if condition 1 is true
}
else if (condition 2)
{ Execute code if condition 2 is true
}
else
{ Execute code if both conditions are false
}

Conditions - Switch
Syntax:
switch(expression)
{
case 1:
code to execute
break;
case 2:
code to execute
break;
case 3:
code to execute
break;
default:
code to execute }

Loops

for ([initialization]; [condition]; [final-expression])


{ statement }
Initialization - An expression to initialize counter variable
condition - An expression to evaluate every loop iteration
final-expression - An expression to update the counter variable
Ex:
for (var i = 0; i < 9; i++)
{
console.log(i);
// more statements
}

Syntax
while (condition)
{ statement}
Ex:
var n = 0;
var x = 0;
while (n < 3) {
n++;
x += n;
}

Syntax
do statement while condition

var i = 0;
do {
i += 1;
console.log(i);
} while (i<5);
Objects in Javascript

 An object in JavaScript is an entity with property and type.


 A property is a variable attached to the object.
 These properties define the characteristics of the object.
 For example, car can be an object with properties color, model, etc.
 You can access the object's property using dot operator.
 In this example, car is an object with model as property
Example
var car = new Object();
car.model = 'Ford';
console.log(car.model);

Ways to create objects in JS

 Create an empty object and then add properties to the object:


Example:
var obj={};
obj.prop1="Hello";
obj.prop2="World";
console.log(obj.prop1 + ' ' + obj.prop2);

 By using Object Literal ie. Name value pair:


Example:
var student = {Name:"Ben", age:20};
console.log(student);

 By using keyword new


Example:
var obj= new Object();
obj.prop1="Hello";
obj.prop2="World";
console.log(obj.prop1 + ' ' + obj.prop2);

Nested Objects
 We can also have an object nested inside another object, i.e., an object will have another object
as its property, which in turn has separate properties of its own.
 Just like the normal objects, these inner objects can also be accessed using dot operator.
Example:
var student = { Name:"Ben", age:20 , degree: {class:"B.Tech",section:"A"}};
We can access the inner object, class by
console.log(student.degree.class);

Remove property from class using delete: eg. Delete object.property


Arrays

Arrays are used to store a set of values in a single variable. Just like any other language, JavaScript arrays
are also represented using square brackets.
Example:
var myArray=["Hello", "World"];
And of course, they are accessed using the index, which always starts with 0.
var myString=myArray[0]
In case you access an index for which no value has been assigned, then the console will return
undefined. In our previous example, on myArray which carries only two values Hello and World, they are
assigned to myArray[0] and myArray[1]. Hence, the console will return undefined, if you look for
myArray[2].

Arrays are predefined objects, and its index is the object properties. Since the index is an integer, we
access the object properties using square bracket instead of a dot operator.

Methods:
a.Pop()
a.Push()
//pop and push to work at the back/end of the array
a.Shift()
a.Unshift()
//shift and unshift to work in the front/start of the array

var numbers = [3,342,23,22,124];


numbers.sort(function(a,b){return b - a});
alert(numbers[0]);
//code returns largest number in the array

// var a="This is"


// var b="JavaScript"
// c=a+b
// console.log(c.length)
// var year = 2016
// var month = "Jan"
// var date = 1
// console.log(date+"-"+month+"-"+year)
// C=window.prompt("Enter temp")
// F = (9 * C/5) + 32
// console.log(F)
// Write a program to draw a chessboard of size 8X8.
// Each line of the chessboard should have a + and a - . + indicates black cell and - indicates a white cell
on the chess board.
// Draw a border with * on all four sides.
// You can try this using different loops.
// for(i=0;i<9;i++)
// for(j=0;j<9;j++)
// console.log('*')

var obj=new Object();


obj.name="nazeeya"
obj.age=22
console.log(obj.age)
console.log("My age is "+ obj.age)
console.log(obj.gender)

Functions

function Hello (string){


return "Hello" + " " + string
}
Hello("Tom")
//Assign function as value to variable
var f = function foo()
{
console.log("Hello");
};
f(); /* prints "Hello" */
//Pass function as argument to another function
var f = function()
{ console.log("Hello");
};
var executor = function(fn)
{ fn();
}
executor(f); /* returns "Hello" */
// Functions can be added as a property to an object.
var myObj = {
"testProp" : true
};
myObj.prop1 = function() {
console.log ("Function in object");
};
myObj.prop1();

Function arguments

var add = function()


{ var i, sum = 0;
for (i=0; i< arguments.length; i++)
{ sum += arguments[i];
}
return sum;
};

console.log(add(1,2,3,4,5)); /* 5 arguments*/
console.log(add(1,2,3,4)); /* 4 arguments*/

function fibonacciSequence(input) {
//Type your code here.
var a=0;
var b=1;
var c=0;
const fib=[];
for(let i=0;i<input;i++){
fib.push(a);
console.log(a);
c=a+b;
a=b;
b=c;

}
return fib;
}
Object Constructor Functions

function Car(make,model,year){
this.make=make;
this.model=model;
this.year=year;}

var car1= new Car(‘a’,’b’,2022);

ForEach method

var a=[10, 20, “Hello”,{} ] ;


var func = function( item ) {
console.log(“For and element” + item);
};

a.forEach(func);

myArray.forEach (function(item,index,array){
console.log(item,index);
});

Scope

 Scope refers to the part of the program in which a variable can be accessed.
 JavaScript has two types of scopes: Local and Global.
 Variables with global scope can be accessed anywhere in the program, and the variables with a local
scope can be accessed within the block or function within which they are declared.
Example
Here name1 is a global variable and name2 is a local variable
var name1 = "ben";
myFunction();
function myFunction() {
var name2 = "bob";
console.log(name1);
console.log(name2);
}
console.log(name2);
Console
ben
bob
Uncaught ReferenceError: name2 is not defined

Closure

 A Closure is nothing but a function inside another function.


 This closure function can access the variables inside its own scope, the outer function's variables and
the global variables.
Example
In this example, whenever we call the myClosure function the value of i will be increased by one. i will be
set to zero only once and only the inner function will be called every time when myClosure is called

var myClosure = (function () {


var i = 0;
return function () {return i += 1;}
}) ();
myClosure();//i=1
myClosure();//i=2
myClosure();//i=3

DOM – Document Object Model

HTML – Gives structure


DOM – Mirrors HTML Structure, depicted as a tree of objects
Document object gives access to all the other elements in the tree.
Eg: n= document.getElementById(“name“)
n.name=”changed”

Core language objects in JS – Array, Math, Date


User language objects in Js – Dog, cat, car…etc
Host language objects in JS- document, window, h1, h2, form

 The HTML DOM is an accepted guideline for how to access,


update, add or remove HTML elements.
 A Structure representation of an HTML document is provided by
DOM.
 An HTML document is completely built using objects. DOM
represents it in an objected-oriented way which can be
manipulated using scripting languages like javascript.
 All the objects in the HTML document are hierarchically
connected to one another. The document object forms the root
of all objects.
There are three kinds of objects:
 Core object (array,math,etc)
 User defined object(myobject,student,employee,etc)
 Host object(h1,document,p,etc)

var input= document.getELementById(“num”).style.color=”blue”;


var para=document.getElementByTagName(“p”);
var para1=para[0].style.fontStyle=”italic”;
function stringGen()
{
var n=document.getElementById("num").value;
var text = "";
var possible = "ABCDEFGHIKLMNOPQRSTVXYZabcdefghijklmnopqrstuvwxyz01234546789"
for (var i=0;i< n; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}

<html>
<body>
<div>
Enter the length of character:
<input type='text' id="num">
<button onclick="stringGen()">submit</button>
<p id="result"></p>
</div>
<script type="text/javascript" src="index.js"></SCRIPT>
</body>
</html>
function myFunction() {

var n=document.getElementById("myname").value;
var p=document.getElementById("myphone").value;
var m=document.getElementById("mymail").value;
var c=document.getElementById("mycontry").value;
var result=n+","+p+","+c+","+m
alert(result);
}
<HTML>
<HEAD>
<TITLE> Registration Details</TITLE>
<script type="text/javascript" src="index.js"></script>
</HEAD>

<BODY>
<div>
Name<input type="text" id="myname"><br>
Phone<input type="text" id="myphone"><br>
Country <input type="text" id="mycontry"><br>
Email id<input type="text" id="mymail"><br>
<button onclick="myFunction()">Try it</button>
</div>

</BODY>

</HTML>

function runList() {
// write your code here
var newOption = document.createElement("option");
newOption.text = document.getElementById("txtbox").value;
var select = document.getElementById("list");
select.add(newOption);
}

<HEAD>
<TITLE> Country field</TITLE>
</HEAD>
<BODY>
Country:
<SELECT NAME="list" ID="list">
<OPTION>India</OPTION>
<OPTION>China</OPTION>
</SELECT>
<input type="text" id="txtbox">
<INPUT TYPE="button" NAME="button" VALUE="Add New" onClick="runList()" />
<script type="text/javascript" src="index.js"></SCRIPT>
</BODY>
</HTML>

Event Listeners
source.addEvent Listener(eventName, eventHandler, true);

event handle – a function that reacts to the event


event has useful information with it and that can be passed in to the event handler via an argument e

Onload event handler is used to call the execution of js after a page has completely loaded
OnFocus and OnBlur Events

AJAX – Asynchronous Javascript and XML


Asynchronous means no need to refresh page to load more data….send and recsive data without page
refresh.
Ajax is technology not a programming language

XHR Request
 XMLHttpRequest is an object that is used by all modern browsers to communicate with the
server.
 This object is commonly used in AJAX programming.
 You can also update only a part of a web page using this object.
 It helps in making synchronous and asynchronous calls to the server and retrieving data without
a full page reload.
 Let us see how to make synchronous calls and its disadvantages
Example
var request= new XMLHttpRequest();
request.open('GET','Example.txt',false);
request.send();
if(request.readyState == 4 && request.status == 200){
console.log(request);
document.writeln(request.responseText);
}
document.writeln("some text");
In this code, since we passed false as a parameter to open() function the browser treats this as
synchronous calls and wait for the server to respond and then execute the next line.

Updating the DOM


By using the response from the server, you can update the DOM. One way of doing that is by using
getElementById. Consider the same example from the previous card
<body>
<p id="myElement"></p>
<script>
var request= new XMLHttpRequest();
request.open('GET','example.txt',true);
request.send();
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200){
console.log(request);
document.getElementById("myElement").innerHTML =request.responseText;
}
Reading JSON Files
Now let us see how to read from a JSON file using AJAX. JSON consist of text, it can be converted into
javascript object using JSON.parse() method
var request= new XMLHttpRequest();
request.open('GET','example.json',true);
request.send();
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200){
var item= JSON.parse(request.responseText)
}
};
Here the variable item has a array of javascript objects where each object has a key value pair from the
JSON file. Now you can loop through these object to read the data and use it to update DOM.
var list = '<ul>';
for(var i in item)
{
list += '<li>'+item[i].name+'</li>';
}

};
</script>
</body>
Here the javascript will find the element with the required id and replace it with the response from the
server. This can also be done using getElementByTagName which you should be familiar with previous
topics.

You might also like