100% found this document useful (1 vote)
14K views23 pages

What Is JavaScript

JavaScript was designed to add interactivity to HTML pages. It is a scripting language that allows JavaScript code to be embedded directly into HTML pages. JavaScript code consists of lines of executable computer code and is interpreted at runtime rather than being compiled. JavaScript gives HTML designers a programming tool and allows dynamic text, event handling, reading/writing HTML elements, validating data, detecting browsers, creating cookies, and more to be added to web pages. JavaScript also supports object oriented programming, functions, variables, operators, and more. Code must be within <script> tags and JavaScript engines in browsers compile JavaScript code to native machine code for execution.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
100% found this document useful (1 vote)
14K views23 pages

What Is JavaScript

JavaScript was designed to add interactivity to HTML pages. It is a scripting language that allows JavaScript code to be embedded directly into HTML pages. JavaScript code consists of lines of executable computer code and is interpreted at runtime rather than being compiled. JavaScript gives HTML designers a programming tool and allows dynamic text, event handling, reading/writing HTML elements, validating data, detecting browsers, creating cookies, and more to be added to web pages. JavaScript also supports object oriented programming, functions, variables, operators, and more. Code must be within <script> tags and JavaScript engines in browsers compile JavaScript code to native machine code for execution.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 23

What is JavaScript?

JavaScript was designed to add interactivity to HTML pages

JavaScript is a scripting language

A scripting language is a lightweight programming language

A JavaScript consists of lines of executable computer code

A JavaScript is usually embedded directly into HTML pages

JavaScript is an interpreted language (means that scripts execute without


preliminary compilation)

Everyone can use JavaScript without purchasing a license


What can a JavaScript Do?

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

Using an External JavaScript

<html>

<head>

<script src="xxx.js"></script>

</head>
<body>

</body>

</html>

=== is equal to (checks x=5


for both value and y="5"
type) x==y returns true
x===y returns false

Break up a Code Line

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!")

JavaScript is an Object Oriented Programming (OOP) language.

An OOP language allows you to define your own objects and make your own variable types.

Default value of unassigned variable


let b;

 document.write(b+"<br/>");

If you declare variable but forget to initialised it will print undefined

In Js there no compulsion to declare variable.

Due to which if programmer type wrong variable name then JS consider it as


another variable.

Eg,

Fname=“VITA”

If you print

undeclare and uninitialized variable you will get error

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/>");

This code will give error.

ReferenceError: assignment to undeclared variable a

You must declare variable with var, let or const key word

Order of execution is top to bottom.


Any javascrpt code has to be within <script></script> tag. Html does not
understand script.

In browser there is javas script engine which will compile your code and
generate native code.

In browser you can disable Java script.

Typeof operator revel datatype of any variable.

Eg.

var a=5;

a is number

Any calculation between undefine and data will result into not a number. NaN
(Not a number)

+ operator is overloaded in string class

Beware that numbers can accidentally be converted to strings or NaN (Not a


Number

JavaScript is loosely typed. A variable can contain different data types, and a
variable can change its data type:

Example

var x = "Hello"; // typeof x is a string

x = 5; // changes typeof x to a number

var x = "5" + 7; // x.valueOf() is 57, typeof x is a string

var x = 5 - 7; // x.valueOf() is -2, typeof x is a number

var x = 5 - "7"; // x.valueOf() is -2, typeof x is a number

var x = "5" - 7; // x.valueOf() is -2, typeof x is a number

var x = 5 - “y"; // x.valueOf() is NaN, typeof x is a number


var x = “5” *” 7”; // x.valueOf() is 35, typeof x is a number

Function

Since javascript is dynamically typed programming language function can


return any type of data and it need not mention the type.

<script>

"use strict";

function go()

document.write("hello");

go(); //function call

var r=go(); undefined

console.log(r);//Undefine

document.write(typeof(go)); //function

document.write("<hr/>");

document.write(go); //function defination

</script>

In the above example observe no datatype before function. In the above


example r will get value “Undefined” . By default function will return
undefined.

<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>

Observe we do not have to write any type before a, b in function definition.

function call(a,b){ }

Every function has it’s own copy of variable.

We know function makes code reusable

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);

Observe we do not have to write any type before a, b in function definition.

function call(a,b){ }

Every function has it’s own copy of variable.//undefined next parameter

We know function makes code reusable.

We can avoid NaN by checking undefine before calculation.


In javascript if you pass only one parameter in function call and have two
parameter in definition. It is not an error. You can set default value for second
parameter.

If user pass second parameter then default value will be overridden.

function call(a,b=1)

{ }

var r=call(x);

We can avoid NaN by checking undefine before calculation.

Default parameter has to be last.

If you set default parameter in between you will get error

arguments
• arguments object contains all arguments passed to the function;

• the arguments object is not a real array

• methods like sort, map, forEach or pop can not be applied on it directly;

• the arguments object has additional functionality specific to itself (like


the callee property).

• You can call findMax() function with different number of parameter

• Call findMax(2,9)

• Call findMax(9,8,2)

Rest parameter

The rest parameter syntax allows us to represent an indefinite number of


arguments as an array. With the help of a rest parameter a function can
be called with any number of arguments, no matter how it was defined.
function functionname(...parameters) //... is the rest parameter
(triple dots)
{
statement;
}
Uncaught SyntaxError: Rest parameter must be last formal parameter
You will get above error if your rest parameter is not last
parameter
function multiply( ...myarg, m) { }
In above line rest parameter is in the beginning it give error

Difference between rest parameters and the arguments object

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;

• the arguments object has additional functionality specific to itself (like


the callee property).

Spread:

Closely related to rest parameters is the spread operator.

While rest parameters allow you to specify that multiple independent


arguments should be combined into an array,

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 args = [0, 1, 2];

var r=myFunction(...args);

console.log(r);

</script>

Spread parameter can be written any where in function call.

Why to use 'use strict'


The "use strict" Directive

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. 

Anonymous Function is a function that does not have any name


associated with it. Normally we use the function keyword before the
function name to define a function in JavaScript, however, in anonymous
functions in JavaScript, we use only the function keyword without the
function name.
An anonymous function is not accessible after its initial creation, it can
only be accessed by a variable it is stored in as a function as a value. An
anonymous function can also have multiple arguments, but only one
expression.

• How to call anonymous function?

Ans: Just put parenthesis “()” after variable pointing to function eg. go();

• Can we assign function pointer variable to another variable?

Ans: yes in our example we have assign go to variable testCopy.

Observe var testCopy =go; in this line no parenthesis “()” after go

Hoisting is JavaScript's default behavior of moving declarations to the


top of the current scope.s

Hoisting applies to variable declarations and to function declarations.

Can we pass name of function in function call?

Yes. This concept is also known as function call back.


A callback is a function passed as an argument to another function.

Self-Invoking Functions
Function expressions can be made "self-invoking".

A self-invoking expression is invoked (started) automatically, without


being called.

Function expressions will execute automatically if the expression is


followed by ().

You cannot self-invoke a function declaration.

You have to add parentheses around the function to indicate that it is a


function expression:
(function () {
  let x = "Hello!!";  // I will invoke myself
})();

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

Anonymous function Arrow function

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.

Arrow function used in array-sort 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);

The map() method creates a new array populated with the results of calling a


provided function on every element in the calling array.

map() creates a new array from calling a function for every array element.

map() calls a function once for each element in an array.

map() does not execute the function for empty elements.

map() does not change the original array.

Array:
let arr=new Array() //do not use this way

//it represent object


arr[0]=1;

arr[1]="ket";

arr[2]='g';

arr[3]=20.5;

alert(arr.length);

Array collection of any type of data

Better way to declare array is []

let a =[1,”ket”, ‘g’,20.5 ];

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>

Difference for..in and for..of :?


Both for..in and for..of are looping constructs which are used to iterate over data
structures.
The only difference between them is the entities they iterate over: 
for..in iterates over all enumerable property keys of an object.
for..of iterates over the values of an iterable object.

Array Methods:

Concat: join two array and return new array


<script>

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.

selects from a given start, up to a (not inclusive) given end.

The slice() method does not change the original 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>

O/P: 200 300 400

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 .

Shift remove s 1st element from array

unshift add element in the beginning of array

Reverse: Reverse the array

Splice to add and remove


array.splice(index, howmany, item1, ....., itemX)

to remove

var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.splice(1, 2);

document.write("</br>"+fruits );

</script>

in the above code it will remove 2 element from index 1 so O/P:banana,Mango

to add:

var fr = ["Banana", "Orange", "Apple", "Mango"];

fr.splice(2, 0, "Lemon", "Kiwi");

document.write("</br>"+fr );

In the above code it will insert two data at index 2

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.

In ES6 javascript introduce Class keyword.

An important difference between function declarations and class declarations is that function


declarations are hoisted and class declarations are not. You first need to declare your class and then
access it, otherwise code like the following will throw a ReferenceError:

const p = new Rectangle(); // ReferenceError

class Rectangle {}

Creating objects in JavaScript (4 Different Ways)


1) Creating object with a constructor:
 Constructor is nothing but a function and with help of new keyword,
constructor function allows to create multiple objects of same flavor as
shown below:

let car  = new vehicle('GT','BMW','1998cc');

2) Using object literals:


In literal object we use colon : to assign value to instance member.
var obj={"name":"raj“ }
We can directly add instance member to the class like this
obj.marks=80

which constructor will it call?


It is instance of Object class so it will call constructor of Object
class (function)
alert(obj); // object Object
As we know when you print object it will Call ToString() method.
If instance member variable name is not as per rule of variable then
enclosed it in “” and you can use it with following syntax
obj[“2division”]);

the differences: constructor object and literal object?


 The constructor object has its properties and methods defined with the
keyword 'this' in front of it, whereas the literal version does not.
 In the constructor object the properties/methods have their 'values'
defined after an equal sign '=' whereas in the literal version, they are
defined after a colon ':'.
 The constructor function can have (optional) semi-colons ';' at the
end of each property/method declaration whereas in the literal version
if you have more than one property or method, they MUST be separated
with
a comma ',', and they CANNOT have semi-colons after them, otherwise
JavaScript will return an error.
 You can create multiple object for constructor object
 You create only one object in literal object. Just for display and
temporary use.

How to add method to constructor object?

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(){

return this.name+ " "+this.age }

Difference: add method as instance member and add method through


prototype?

• Instance method is slow in performance as it will allocate memory for


every object

• Prototype method is provide better performance as it will stored in


separate memory block (virtual table) and every object will have same
copy of 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');

Call and apply


With the call() method, you can write a method that can be used on
different objects.
In a function definition, this refers to the "owner"
of the function.
In the example above, this is the objperson object
that "owns" the fullName function.
In other words, this.firstName means the firstName
property of this object.

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.

The Difference Between call() and apply()


The difference is:

The call() method takes arguments separately.

The apply() method takes arguments as an array.

Q 2. How to implement inheritance in Es5?

1)Create Person as function class.


2)Create methods on prototype of the Person class
3)Cpreate child class and call its base class with required
parameters.
4)Create prototype object for child class from Person class.
child.prototype=Object.create(person.prototype);

Here we are creating new object from Person.prototype and


assigning it to prototype object of base class.
Q 3. How to implement inheritance in Es6?
The ES6 JavaScript supports Object-Oriented programming components
such as Object, Class and Methods. Further in Classes we can
implement inheritance to make child inherits all methods of Parent Class.
This can be done using the extends and super keywords.

We use the extends keyword to implement the inheritance in ES6. The


class to be extended is called a base class or parent class. The class that
extends the base class or parent class is called the derived class or child
class. The super() method in the constructor is used to access all
parent’s properties and methods that are used by the derived class.

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?

JavaScript variables can belong to the local or global scope.

Global variables can be made local (private) with closures.

1)A function can access all variables defined inside the function,

2) But a function can also access variables defined outside the function,

3) Global variables live until the page is discarded

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().

-- The counter should be local to the add() function, to prevent other code from


changing it
-- It did not work because we display the global counter instead of the local
counter.

== 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.

 A JavaScript inner function can solve this.

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:

This could have solved the counter dilemma, if we could reach


the plus() function from the outside.

We also need to find a way to execute counter = 0 only once.

We need a closure.

The variable add is assigned to the return value of a self-invoking


function.

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.

This is called a JavaScript closure. It makes it possible for a function to


have "private" variables.
The counter is protected by the scope of the anonymous function, and can
only be changed using the add function.

A closure is a function having access to the parent scope, even after the
parent function has closed.

var add = (function () { //2 add=


function () {return counter += 1;}
    var counter = 0;
    return function () {return counter += 1;}
})(); //1

ES8 #--private variable


ES8 _--protected variable

Window class has many methods


1)open:
window.open('p.html');
Open will open new file in current window by default.
If you add second parameter _blank then it will open
file in a new tab
2)Prompt:
<script>
var no1=window.prompt("enter number",5);
ss

You might also like