JavaScript
JavaScript
JavaScript
Script tags holding JavaScript code are best placed at the end of the code.
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.
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.
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)
While concatenating, JavaScript treats all data types as strings even if values are of different data types.
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
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
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);
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
Functions
Function arguments
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;}
ForEach method
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
<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);
Onload event handler is used to call the execution of js after a page has completely loaded
OnFocus and OnBlur Events
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.
};
</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.