Unit 3_Functions and Objects
Unit 3_Functions and Objects
A JavaScript object is an entity having state and behavior (properties and method).
For example car, pen, bike, chair, glass, keyboard, monitor, etc.
◦ Everything in JavaScript is an object thus it is called an object-based language.
◦ JavaScript is template-based and not class-based. It does not require the class to create an object. We directly create an
object.
◦ There are 3 ways to create objects.
1. By object literal
Syntax: object={property1:value1,property2:value2.....propertyN:valueN}
Example:
<script>
emp={id:10, name: “Sudhir",salary:25000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
By creating instance of Object
Syntax:
var objectname=new Object();
Here, new keyword is used to create object.
<script>
var emp=new Object();
emp.id=10;
emp.name="R Shastri";
emp.salary=30000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
By using an Object constructor
Here, you need to create a function with arguments. This keyword can assign Each argument value in the current object.
This keyword refers to the current object.
The example of creating an object by object constructor is given below.
<script>
function emp(id,name,salary)
{
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(10,“R. Shastri",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
Defining method in JavaScript Object
We can define method in JavaScript object. But before defining method, we need to add property in the function
with same name as method.
The example of defining method in object is given below.
<script>
function emp(id,name,salary){ e=new emp(103,"Sonoo Jaiswal",30000);
this.id=id; document.write(e.id+" "+e.name+" "+e.salary);
this.name=name; e.changeSalary(45000);
this.salary=salary; document.write("<br>"+e.id+" "+e.name+" "+e.salary);
this.changesalary = changeSalary; </script>
function changeSalary(otherSalary)
{
this.salary=otherSalary;
}
}
JavaScript object properties
JavaScript objects have two types of properties:
❖ Data properties
❖Accessor properties
JavaScript specifies the characteristics of properties of objects via internal attributes surrounded by the two pairs of
square brackets
A data property contains a single location for a data value. A data property has four attributes:
[[Configurarable]] – determines whether a property can be redefined or removed via delete operator.
[[Enumerable]] – indicates if a property can be returned in the for...in loop.
[[Writable]] – specifies that the value of a property can be changed.
[[Value]] – contains the actual value of a property.
By default, the [[Configurable]] , [[Enumerable]]And [[Writable]] attributes set to true for all properties defined
directly on an object. The default value of the[[Value]] attribute is undefined.
const student = { The following example creates a student object with two
name : “Danesh”, properties name and surname with the configurable,
Surname : “Morya” enumerable, and writable attributes set to true. And their values are set
Enumerable Properties in JS
Enumerable properties are iterated using the for...in loop or Objects.keys() method.
An object is an unordered list of key-value pairs.
The key is usually a string or a symbol.
The value can be a value of any primitive type (string, boolean, number, undefined, or null), an object, or a function.
Ex:
const student = { The student object has two properties: name and surname
name = “Danesh”,
Surname = “Morya”
};
Passing Objects to Functions
Using the Literal Object Notation:
Just place your key-value pairs separated by ':' inside a set of curly braces(), and your object will be ready to serve (or
consumed).
We can pass an object to a JavaScript function, but the arguments must have the same names as the Object property
names.
function area_Rectangle({ l,b })
Ex: {
return l * b;
}
let rectangle = {
l: 22,
b: 10
};
area_Rectangle(rectangle);
String object in JavaScript
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
1. By string literal
2. By string object (using new keyword)
By string literal
Syntax: var stringname="string value";
Ex:
<script>
var str="This is string literal";
document.write(str);
</script>
By string object (using new keyword)
Syntax:
var stringname=new String("string literal");
Ex:
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
Methods
JavaScript String Methods
Description
concat() Combines the text of two strings and returns a new string.
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string by searching a character from the last position.
search() It searches a specified regular expression in a given string and returns its position if a match occurs.
match() It searches a specified regular expression in a given string and returns that regular expression if a match occurs.
replace() It replaces a given string with the specified replacement.
substr() It is used to fetch the part of the given string on the basis of the specified starting position and length.
substring() It is used to fetch the part of the given string on the basis of the specified index.
slice() It is used to fetch the part of the given string. It allows us to assign positive as well negative index.
toLowerCase() It converts the given string into lowercase letter.
toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s current locale.
toUpperCase() It converts the given string into uppercase letter.
toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s current locale.
toString() It provides a string representing the particular object.
valueOf() It provides the primitive value of string object.
split() It splits a string into substring array, then returns that newly created array.
trim() It trims the white space from the left and right side of the string.
charAt()
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The charAt() Method</h2>
<p id="demo"></p>
<script>
let text = “I am a student";
let character = text.charAt(text.length-1);
document.getElementById("demo").innerHTML = character;
</script>
</body>
</html>
concat()
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The concat() Method</h2>
<p id="demo"></p>
<script>
let text1 = "Hello";
let text2 = “mcoe!";
let result = text1.concat(" ", text2);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
<script>
let text = "Hello world!";
let result = text.slice(3);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
O/p: lo world!
Slice() : negative index
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The slice() Method</h2>
<p>slice() extracts a part of a string and returns the extracted part:</p>
<p id="demo"></p>
<script>
let text = "Hello world!";
let result = text.slice(-3);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
O/p: ld!
Array object in JavaScript
The Array object lets you store multiple values in a single variable.
Array is a collection of variables of the same type.
Syntax to create an array:
var fruits = new Array( "apple", "orange", "mango" );
Or
var fruits = [ "apple", "orange", "mango" ];
Array methods
1 concat(): Returns a new array comprised of this array joined with other array(s) and/or value(s).
2 every(): Returns true if every element in this array satisfies the provided testing function.
3 filter(): Creates a new array with all of the elements of this array for which the provided filtering function returns true.
4 forEach(): Calls a function for each element in the array.
5 indexOf(): Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
6 join(): Joins all elements of an array into a string.
7 lastIndexOf(): Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is
found.
8 map(): Creates a new array with the results of calling a provided function on every element in this array.
9 pop(): Removes the last element from an array and returns that element.
10 push(): Adds one or more elements to the end of an array and returns the new length of the array.
Array methods cont..
11 reverse(): Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
12 shift(): Removes the first element from an array and returns that element.
13 slice(): Extracts a section of an array and returns a new array.
14 some(): Returns true if at least one element in this array satisfies the provided testing function.
15 sort(): Sorts the elements of an array
16 splice(): Adds and/or removes elements from an array.
17 toString():Returns a string representing the array and its elements.
18 unshift(): Adds one or more elements to the front of an array and returns the new length of the array.
Every()
Syntax: array.every(function(currentValue, index, arr), thisValue)
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The every() Method</h2>
<p>every() returns true if all elements in an array pass a test (provided as a function).</p>
<p id="demo"></p>
<script>
const ages = [32, 33, 16, 40];
document.getElementById("demo").innerHTML = ages.every(checkAge);
function checkAge(age)
{
return age > 18;
}
</script>
</body>
</html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The every() Method</h2>
<p>every() returns true if all elements in an array pass a test (provided as a function).</p>
<p id="demo"></p>
<script>
var passed = [12, 5, 8, 130, 44].every(isBigEnough); document.write("First Test Value : " + passed);
<h1>JavaScript Arrays</h1>
<h2>The filter() Method</h2>
function checkAdult(age) {
return age >= 18;
}
</script>
</body>
</html>
fill()
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The fill() Method</h2>
<p id="demo"></p>
<script>
const num =[1,2,3,5]
document.getElementById("demo").innerHTML = num.fill(4)
</script>
</body>
</html>
fill()
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The fill() Method</h2>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango","watermelon","pear"];
document.getElementById("demo").innerHTML = fruits.fill("Kiwi",2,5);
</script>
</body>
</html>
Date object in JavaScript
Date objects are created with the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most methods simply
allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the
object.
Syntax:
One can use any of the following syntaxes to create a Date object using Date() constructor.
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year, month, date [, hour, minute, second, millisecond ])
Date methods
• getDate(): Returns the day of the month (from 1-31)
• getDay(): Returns the day of the week (from 0-6)
• getFullYear(): Returns the year
• getHours(): Returns the hour (from 0-23)
• getMilliseconds(): Returns the milliseconds (from 0-999)
• getMinutes(): Returns the minutes (from 0-59)
• getMonth(): Returns the month (from 0-11)
• getSeconds(): Returns the seconds (from 0-59)
• getTime(): Returns the number of milliseconds since midnight Jan 1 1970, and a specified date
• getTimezoneOffset(): Returns the time difference between UTC time and local time, in minutes
• getUTCDate(): Returns the day of the month, according to universal time (from 1-31)
• now(): Returns the number of milliseconds since midnight Jan 1, 1970
• parse(): Parses a date string and returns the number of milliseconds since January 1, 1970
• setDate(); Sets the day of the month of a date object
• setTime(): Sets a date to a specified number of milliseconds after/before January 1, 1970
• setUTCDate(): Sets the day of the month of a date object, according to universal time
• toDateString(): Converts the date portion of a Date object into a readable string
Numbers
The Number object represents numerical data, either integers or floating-point numbers
Syntax
The syntax for creating a number object is as follows −
var val = new Number(number);
In the place of number, if you provide any non-number argument, then the argument cannot be
converted into a number, it returns NaN (Not-a-Number).
Number methods
1 toExponential() :Forces a number to display in exponential notation, even if the number is in the range in which
JavaScript normally uses standard notation.
2 toFixed(): Formats a number with a specific number of digits to the right of the decimal.
3 toPrecision(): Defines how many total digits (including digits to the left and right of the decimal) to display a number.