Professional Documents
Culture Documents
Function Declaration:
Function declarations consist of the function keyword, followed by these components:
• An identifier that names the function. The name is a required part of function
declarations: it is used as the name of a variable, and the newly defined function object is
assigned to the variable.
• A pair of parentheses around a comma-separated list of zero or more identifiers. These
identifiers are the parameter names for the function, and they behave like local variables
within the body of the function.
• A pair of curly braces with zero or more JavaScript statements inside. These statements
are the body of the function: they are executed whenever the function is invoked.
Example:
function factorial(x) {
if (x <= 1) return 1;
return x * factorial(x-1);
}
fact=factorial(5)
document.writeln(fact)
Function Expressions:
Function expressions appear within the context of a larger expression or statement, and the
name is optional.
Example:
let square = function(x) { return x*x; };
let result=square(6)
document.writeln(result)
If the body of the function is a single return statement, you can omit the return keyword.
let sum = (x, y) => x + y;
document.writeln(sum(8,3))
if an arrow function has exactly one parameter, you can omit the parentheses around the
parameter list:
let sum = x => x*x + 2*x + 3;
document.writeln(sum(3))
An arrow function with no arguments at all must be written with an empty pair of
parentheses.
const a = () => 36;
document.writeln(a())
Nested Functions:
Example:
function hypotenuse(a, b) {
function square(x) { return x*x; }
return (square(a) + square(b));
}
var a=hypotenuse(2,3);
document.writeln(a)
Invoking Functions
Invoking a Function as a Function:
function mul(a, b) {
return a * b;
}
c=mul(10,5);
document.writeln(c);
Invoking a Function as a Method:
var person={name:"RAM",age:15,
changename: function cn(a)
{
this.name=a; document.write("in method call","<br>");
}
};
document.write("Before Method call","<br>");
document.write(person.name,"<br>");
document.write("After Method call","<br>");
person.changename("KUMAR");
document.write(person.name);
call() Method :
let person = {
details: function(city, country) {
return this.name + "," + this.age + "," + city + "," + country; }
}
let person1 = { name:"kumar", age:35 }
document.writeln(person.details.apply(person1, ["guntur", "india"]));
output: kumar,35,guntur,india,undefined
Output : kumar,35,guntur,india
function demo(x, y) {
if (y === undefined) {
y = 2;
}
return x * y;
}
document.writeln(demo(5));
function sumAll() {
let sum = 0;
for(let i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
result=sumAll(123, 500, 115, 44, 88,1)
document.writeln(result);
If the numbers array had more than four items, then it will only use the first four items as
addNumbers() argument and ignore the rest.
Functions as Values
In JavaScript, functions are a data type just as strings, numbers, and arrays are data types.
Therefore, functions can be assigned as values to variables, but are different from all other
data types because they can be invoked.
document.writeln(plusFive(3)); // 8
// Since f has a function value, it can be invoked.
document.writeln(f(9)); // 14
Function Properties, Methods, and Constructor
The length Property:
The length property returns the number of formal parameters listed inside a function.
function func() {}
document.writeln(func.length); // 0
function func1(a, b) {}
document.writeln(func1.length); // 2
The length property excludes the rest parameters and only counts parameters until the first
one with a default value.
function func3(a, b = 10, c) {
}
document.writeln(func3.length); // 1
function person () {
this.name = 'John',
this.age = 23
}
const p1 = new person();
const p2 = new person();
person.prototype.gender = 'male';
// inheriting the property from prototype
document.writeln(p1.gender); // male
document.writeln(p2.gender); // male
The bind() Method:
The bind() method allows an object to borrow a method from another object without
copying.
Syntax: func.bind(thisArg, arg1, ... argN)
const student1 = {
name: "Jack",
grade: "5",
introduction: function () {
document.writeln(this.name + "studies in grade" + this.grade + ".");
},
};
const student2 = {
name: "Jimmy ",
grade: " 6",
};
const student1 = {
name: "Jack",
introduction: function (score) {
document.writeln (this.name + "scored " + score + " in an exam.");
},
};
const student2 = {
name: "Jimmy ",
};
example:
var func = new Function("x","y", "return x*y;");
function sample(a,b) {
var result=func(a,b);
return result;
}
var val=sample(10,20);
document.writeln(val);
Closures:
Assessing the variables of a function even its execution is completed or out of its scope.
function outer(num1)
{
var x=10;
function inner(num2)
{
document.writeln(num1+num2+x)
}
return inner
}
var res=outer(7)
res(8)
For Example, if we want to know how many times a user clicks a particular button, this
concept will be useful. (Execute this code and examine the output)
<html>
<head>
<body>
<input type="button" onclick="updatecount()" value="click">
<p id="count">clicked:0</p>
<script >
function updatecountsecure()
{
let count=0;
function inner()
{
count=count+1
let p=document.getElementById("count")
p.innerText=`clicked:${count}`
}
return inner
}
let updatecount=updatecountsecure()
let counter2=updatecountsecure()
counter2()
counter2()
let counter3 =updatecountsecure()
counter3()
counter3()
counter3()
</script></body>
</head>
</html>
CLASSES
class emp {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
let emp1 = new emp("kumar", "25 years");
document.write(emp1.name);
document.write(emp1.age);
class Person {
constructor(name) {
this.name = name;
}
}
Setter method:
An object properties can be initialized, modify or updated using setter functions.
class mobile{
constructor(name,ram){
this.name=name;
this.ram=ram;
}
set cost(p)
{
if(p<=0)
alert("price cannot be zero or less");
else
this.price=p;
}
}
let m1=new mobile("realme","6gb")
document.writeln(m1.name);
document.writeln(m1.ram);
//m1.cost(15000) // error
m1.cost= 15000
document.writeln(m1.price);
getter method:
class mobile{
constructor(name,ram){
this.name=name;
this.ram=ram;
}
get print()
{
return "mobile name="+this.name+" ram="+this.ram
}
}
let m1=new mobile("realme","6gb")
document.writeln(m1.name+"<br>");
document.writeln(m1.print);
class test {
static a=10;
b=20;
static m1(){
document.writeln("this is static method")
}
m2(){
document.writeln("this is non-static method")
}
}
document.writeln(test.a)
test.m1()
Encapsulation:
Java Script Encapsulation is a process of binding of binding the data with the
functions acting on that data. (We define the data and to work on the data, we
create the functions (methods). All these are present as a single unit.)
class student{
constructor(){
let name,marks;
}
getname()
{
return this.name;
}
setname(name)
{
this.name=name;
}
getmarks()
{
return this.marks;
}
setmarks(marks)
{
this.marks=marks;
}
}
let stu=new student();
stu.setname("kumar");
stu.setmarks(80);
document.writeln(stu.getname())
document.writeln(stu.getmarks())
Inheritance:
class one
{
a=100;
display()
{
document.writeln(this.a);
}
}
class two extends one
{
b=200;
show()
{
document.writeln(this.b);
}
}
obj=new two();
obj.display() //100
obj.show() //200
Method Overriding:
class one
{
a=100;
display()
{
document.writeln(this.a);
}
}
class two extends one
{
b=200;
display()
{
document.writeln(this.b);
}
}
obj=new two();
obj.display() //200
Super Keyword:
super(arguments); // calls the parent constructor (only inside the constructor)
super.parentMethod(arguments); // calls a parent method
class one
{
a=100;
display()
{
document.writeln(this.a);
}
}
class two extends one
{
b=200;
show()
{
super.display();
}
}
obj=new two();
obj.display() // 100
obj.show() // 100
Prototype: (Adding Methods to Existing Classes)
class employee
{
constructor(id,name)
{
this.id=id;
this.name=name;
}
}
employee.prototype.sal=50000;
employee.prototype.display=function()
{
document.writeln(this.id,this.name,this.sal);
}
emp1=new employee(101,"kumar");
emp2=new employee(102,"ram");
emp1.display();
emp2.display();