You are on page 1of 15

Functions

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)

Function expressions can include names, which is useful for recursion.


var f = function fact(x) { if (x <= 1) return 1; else return x*fact(x-1); };
document.writeln(f(4))

Function expressions are sometimes defined and immediately invoked:


let t = (function(x) {return x*x;}(10));
document.writeln(ts)
Arrow Functions:
The general form of an arrow function is a comma-separated list of parameters in
parentheses, followed by the => arrow, followed by the function body in curly braces.

let sum = (x, y) => { return x + y; };


document.writeln(sum(6,3))

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

Invoking a Function with a Function Constructor:


function person(name,age)
{
this.name=name;
this.age=age;
}

var p1=new person("RAM",15);


var p2=new person("KUMAR",25);
document.writeln(p1.name);
document.writeln(p1.age);

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

Note: The call() method takes arguments separately.


The apply() method takes arguments as an array.
apply() 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

Function Arguments and Parameters

Function parameters are the names listed in the function definition.


Function arguments are the real values passed to (and received by) the function.

Optional Parameters and Defaults:


If a function is called with missing arguments (less than declared), the missing values are set
to undefined.

function demo(x, y) {
if (y === undefined) {
y = 2;
}
return x * y;
}
document.writeln(demo(5));

 ES6 allows function parameters to have default values.

function demo(x, y = 10) {


return x + y;
}
document.writeln(demo(5));
Rest Parameters and Variable-Length Argument Lists:
The rest parameter (...) allows a function to treat an indefinite number of arguments as an
array.
function sum(...args) {
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
let x = sum(4, 9, 16, 25, 29, 60, 77);
document.writeln(x);

The Arguments Object:


JavaScript functions have a built-in object called the arguments object.
The argument object contains an array of the arguments used when the function was called.
If a function is called with too many arguments (more than declared), these arguments can
be reached using the arguments object.

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

The Spread Operator for Function Calls:

let numbers = [1, 3, 5, 7];


function addNumbers(a, b, c, d) {
return a + b + c + d;
}
sum=addNumbers(...numbers)
document.writeln(sum) //output : 16

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.

let numbers = [1, 3, 5, 7, 2, 9, 8, 6];


function addNumbers(a, b, c, d) {
return a + b + c + d;
}
sum=addNumbers(...numbers)
document.writeln(sum) //output : 16

Destructuring Function Arguments into Parameters:


To destructure an object inside a function's parameters we place a set of curly braces inside
the parentheses of the function. Inside the curly braces, we place the properties of the
object which we wish to pick out.
let drinks = {
cola: 2,
lemon: 1,
milk: 3,
tea: 5,
coffee: 10,
wine: 8
};
const hotDrinksPrices = ({ tea, coffee }) => {
return tea + coffee;
}
let price=hotDrinksPrices(drinks);
document.writeln(price)

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.

let plusFive = (number) => {


return number + 5;
};
// f is assigned the value of plusFive
let f = plusFive;

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

The name Property:


The name property returns the name of the function.
function func3(a, b = 10, c) {
}
document.writeln(func3.name); // func3

Anonymous function is a function that is created without a name. We declare anonymous


functions without using an identifier. We can create an anonymous function with new
Function(..) or Function(..) syntax.

document.writeln((new Function).name); // anonymous

const result = function() {


}
document.writeln (result.name); // result

The prototype Property:

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)

The bind() can take two parameters:


thisArg - The value provided as this parameter for func.
arg1, ... argN (optional) - The value of arguments present inside func.

const student1 = {
name: "Jack",
grade: "5",
introduction: function () {
document.writeln(this.name + "studies in grade" + this.grade + ".");
},
};

const student2 = {
name: "Jimmy ",
grade: " 6",
};

// the object student2 is borrowing introduction method from student1


let result= student1.introduction.bind(student2);

// invoking result() function


result(); // Jimmy studies in grade 6.

Using bind() Method with two Parameters:

const student1 = {
name: "Jack",
introduction: function (score) {
document.writeln (this.name + "scored " + score + " in an exam.");
},
};

const student2 = {
name: "Jimmy ",
};

// passing two parameters student2 and '95'


let result = student1.introduction.bind(student2, 95);
result(); // Jimmy scored 95 in an exam.
The Function () Constructor:
The Function() constructor creates Function objects. Calling the constructor directly can
create functions dynamically.

const sum = new Function('a', 'b', 'return a + b');


document.writeln(sum(2, 6));

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

Hoisting: A class should be defined before using it. For example,


const p = new Person(); // ReferenceError

class Person {
constructor(name) {
this.name = name;
}
}

Classes with constructor:


class mobile{
constructor(name,price,ram){
this.name=name;
this.price=price;
this.ram=ram
}
}

let m1=new mobile("realme",15000,"6gb")


document.writeln(m1.name);
document.writeln(m1.price);

Classes with methods:


class mobile{
constructor(name,price,ram){
this.name=name;
this.price=price;
this.ram=ram;
}
updateram(uram){
this.ram=uram;
}
}
let m1=new mobile("realme",15000,"6gb")
document.writeln(m1.ram);
m1.updateram("8gb")
document.writeln(m1.ram);

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

Static variables and methods:


Static variables and methods can be directly accessed using the class name.

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

let t=new test();


document.writeln(t.b)
t.m2()

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

You might also like