What Is JavaScript
What Is JavaScript
JavaScript gives HTML designers a programming tool - HTML authors are normally not
programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can
put small "snippets" of code into their HTML pages
JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:
document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
JavaScript can react to events - A JavaScript can be set to execute when something happens, like
when a page has finished loading or when a user clicks on an HTML element
JavaScript can read and write HTML elements - A JavaScript can read and change the content of an
HTML element
• JavaScript can be used to validate data - A JavaScript can be used to validate form data
before it is submitted to a server. This saves the server from extra processing
• JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect
the visitor's browser, and - depending on the browser - load another page specifically
designed for that browser
• JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve
information on the visitor's computer
<html>
<head>
<script src="xxx.js"></script>
</head>
<body>
</body>
</html>
You can break up a code line within a text string with a backslash. The example below will
be displayed properly:
document.write("Hello \
World!")
An OOP language allows you to define your own objects and make your own variable types.
document.write(b+"<br/>");
Eg,
Fname=“VITA”
If you print
But undeclared but intilised variable will not give any error
Ie. a=5;
document.write(a+"<br/>");
For better and safe programming always use ‘use strict’ which indicate you are
running script in a strict mode.
'use strict'
a=5;
document.write(a+"<br/>");
You must declare variable with var, let or const key word
In browser there is javas script engine which will compile your code and
generate native code.
Eg.
var a=5;
a is number
Any calculation between undefine and data will result into not a number. NaN
(Not a number)
JavaScript is loosely typed. A variable can contain different data types, and a
variable can change its data type:
Example
Function
<script>
"use strict";
function go()
document.write("hello");
console.log(r);//Undefine
document.write(typeof(go)); //function
document.write("<hr/>");
document.write(go); //function defination
</script>
<script>
"use strict";
function call(a,b)
{ var p;
p=a*b
return p;
var x , y;
x=5;
y=7;
var r=call(x,y);
document.write(r);
document.write(call(3,3));
</script>
function call(a,b){ }
In javascript if you pass only one parameter in function call and have two
parameter in definition. It is not an error.
function call(a,b)
{ }
var r=call(x);
function call(a,b){ }
function call(a,b=1)
{ }
var r=call(x);
arguments
• arguments object contains all arguments passed to the function;
• methods like sort, map, forEach or pop can not be applied on it directly;
• Call findMax(2,9)
• Call findMax(9,8,2)
Rest parameter
There are three main differences between rest parameters and the
arguments object:
• rest parameters are only the ones that haven't been given a separate
name, while the arguments object contains all arguments passed to the
function;
• the arguments object is not a real array, while rest parameters are Array
instances, meaning methods like sort, map, forEach or pop can be
applied on it directly;
Spread:
the spread operator allows you to specify an array that should be split and
have its items passed in as separate arguments to a function
The main difference between rest and spread is that the rest
operator puts the rest of some specific user-supplied values
into a JavaScript array. But the spread syntax expands
iterables into individual elements.
<script>
"use strict";
function myFunction(x, y, z)
{ return x+y+z;
var r=myFunction(...args);
console.log(r);
</script>
The purpose of "use strict" is to indicate that the code should be executed in
"strict mode".
Using strict mode, don’t allow to use a variable without declaring it.
Duplicating a parameter name is not allowed.
Ans: Just put parenthesis “()” after variable pointing to function eg. go();
Self-Invoking Functions
Function expressions can be made "self-invoking".
There are some situation where you want to initialize the data as soon as
application start in such scenario you can use self invoking function
Eg alert popup
var reflect = function(value) { var reflect1 = value => value;
return value; }; document.write(reflect1(67));
document.write(reflect(22));
var sum = function(num1, num2) { var sum1 = (num1, num2) => num1 + num2;
return num1 + num2; document.write(sum1(5,7));
};
document.write(sum(5,5));
var getName = function() { var getName = () => "TSYS";
return "TSYS"; console.log(getName());
};
console.log(getName());
var getTempItem = function(id) { var getTempItem = id => ({ id:id, name:
return { "Temp" });
id: id, let obj=getTempItem(5)
name: "Temp" document.write(obj.id)
};
};
Arrow Function
Big fat Arrow functions allow us to write shorter function syntax:
This allows the omission of the curly brackets and the return keyword.
The left part denotes the input of a function and the right part the output of that
function.
var result1 = values.sort((a, b) => a - b);
map():
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
map() creates a new array from calling a function for every array element.
Array:
let arr=new Array() //do not use this way
arr[1]="ket";
arr[2]='g';
arr[3]=20.5;
alert(arr.length);
script>
let arr=[];
arr[0]=5;
arr[4]=4;
document.write(arr)
document.write("<hr/>");
for(let e in arr)
document.write(arr[e])
document.write("<hr/>");
for(let e of arr)
document.write(e)
//remove undefined
for(let e of arr)
if(e)
document.write(e)
</script>
Array Methods:
let nar=[10,20,30]
let ar=[5,6,7]
let result=ar.concat(nar)
slice(begin,end):
The slice() method returns selected elements in an array, as a new array.
begin : Zero-based index at which to begin extraction.
end : (Optional) Zero-based index at which to end extraction:
slice extracts up to but not including end
<script>
var cut=[100,200,300,400]
var c=cut.slice(1);
cut.slice(1,3);//200,300
document.write("</br>"+c);
<script>
Join :
convert array to string
The push() method adds one or more elements to the end of an array and retu
rns the new length.
The pop() method remove elements from the end of an array .
to remove
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(1, 2);
document.write("</br>"+fruits );
</script>
to add:
var fr = ["Banana", "Orange", "Apple", "Mango"];
fr.splice(2, 0, "Lemon", "Kiwi");
document.write("</br>"+fr );
The find() method returns the value of the first element in the provided array
that satisfies the provided testing function. If no values satisfy the testing
function, undefined is returned.
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
The filter() method creates a new array with all elements that pass the test
implemented by the provided function.
The at() method takes an integer value and returns the item at that index,
allowing for positive and negative integers. Negative integers count back from
the last item in the array.
Q 1. whats is difference between function as class and class key word?
In java script function it self is class and it act as constructor also to initialize data member.
class Rectangle {}
When you add method using prototype it will not create a copy for every
object. You have to use function name dot prototype
Prototype is a keyword.
person.prototype.toString= function(){
• Instance method can make use of private variable eg if you have declare
var x in function person Instance method can have access to this variable
• Prototype method can not access variable declared in function with var
key word as scope of var will be within the function
3) Creating object with Object.create() method:
const me = Object.create(coder);
4) Using es6 classes:
ES6 supports class concept like any other Statically typed or object
oriented language. So, object can be created out of a class in
javascript
let car1 = new Vehicle('GT', 'BMW', '1998cc');
var objperson = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var objperson1 = {
firstName:"John",
lastName: "Doe"
}
var objperson2 = {
firstName:"Mary",41
lastName: "Doe"
}
objperson.fullName.call(objperson1); // Will return
"John Doe“
objperson.fullName.call(objperson2); // Will return
"Mary Doe"
The call() method is a predefined JavaScript method.
It can be used to invoke (call) a method with an
owner object as an argument (parameter).
With call(), an object can use a method belonging to
another object.
The apply() is same as call bit this method takes
arguments as an array.
Object destructuring?
let {title, width, height} = options;
• We should have an existing object at the right side,
that we want to split into variables. The left side
contains an object-like “pattern” for corresponding
properties. In the simplest case, that’s a list of
variable names in {...}.
Q 9. what is closure?
4) Local variables have short lives. They are created when the function is
invoked, and deleted when the function is finished.
5) 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:
--There is a problem with the solution above: Any code on the page can change
the counter, without calling add().
== We can remove the global counter and access the local counter by letting the
function return it
It did not work because we reset the local counter every time we call the
function.
We need a closure.
The self-invoking function only runs once. It sets the counter to zero (0),
and returns a function expression.
This way add becomes a function. The "wonderful" part is that it can
access the counter in the parent scope.
A closure is a function having access to the parent scope, even after the
parent function has closed.