Composite types
The main difference between the primitive and composite types is that, primitive types contain only any one type of values. But in composite types, they contain more than one type of values.
There are three composite data types:
- Objects
- Arrays
- Functions
Objects
An object is a collection of both primitive and composite data types including functions. Object are written as key-value pairs. Key is known as properties. To access an object data, we have to use the properties whereas in array we can access data by accessing index of array.
var person = {
firstName: "Luther",
lastName: "Salt",
age: 35,
height: "196cm",
};
console.log(person);
// expected output: { firstName: "Luther", lastName: "Salt", age: 35, height: "196cm" }
Work out
A user defined objects can be created using new
keyword followed by name of function and parentheses. What here actually happens is we
are nvoking the constructor function so that we are using parentheses. Then a new instance of the constructor function Object
is created.
Var newObject = new Object();
Arrays
An array is an ordered list in which each member of an array is called as element
and each element are assigned to index
. Index
starts from to zero. Elements in following index are accessed by following array name with square brackets ([]) containing index of
desired element.
var arr = [1, 2, 3];
arr[3] = 4;
arr[4] = 5;
arr[5] = "Six";
console.log(arr);
// expected output: [1, 2, 3, 4, 5, "Six"]
Work out
Arrays are actually objects, so we can use object syntax to declare a new array.
var newArray = new Array();
Functions
A function is another JavaScript object. A function is called or invoked by following the function name with parentheses. Inside the
parentheses we can pass arguments
. Arguments are the data which is passed to the function when the function is invoked.
function testFunction(para) {
console.log(para);
}
testFunction("Hello World");
// expected output: "Hello World"
Work out
Function parameters
are values received inside the parantheses of the function definition.
function name(parameter1, parameter2, parameter3) {
// Code to be executed
}
Function arguments
are values listed inside the parentheses when the function invoked.
name(argument1, argument2, argument3);