What Are JavaScript Objects
What Are JavaScript Objects
What Are JavaScript Objects
concept. With javascript being widely adopted due to its ability to provide
dynamic behaviour to web pages, one should be aware of javascript and how to
work with its objects. Objects in javascript are a group of different data types or
objects put together as “key-value” pairs. The “key” part of the object is nothing
For example, let us consider we have an object “Student”, where its properties
The javascript object representation for this student object would be represented
as follows:
Code:
var student = { first_name : ‘Anamika’,
last_name : ‘Rai’,
age : 14,
student_id : 20,
class : ‘VIII D’
Here the properties first_name, last_name, and class contain values of String
data type, whereas age and student_id are of the number data type.
respective values, enclosed within curly braces ({…}). In the example above,e
we have created the object “student” using the object initializer syntax.
Here the properties are either of a primitive data type (string, number, Boolean,
null
Example:Code:
last_name : ‘Rai’,
age : 14,
student_id : 20,
class : ‘VIII D’
Rai’}
following which create its object using the “new” keyword. Then assign the
Example:
Code:
function Student(name, age, gender){
this.name= name;
this.age = age;
this.gender = gender;
Note that the constructor name should start with an upper case as per the
naming convention.
Code:
‘female’);
Also, note that here we are only passing the values to the constructor. The
constructor is assigning these values to the respective properties using the “this”
keyword. The current object is being referred to by using the “this” keyword.
student.age = 14;
student.gender = “female”;
object class. The create method takes in an object prototype as a parameter. Due
Example:
Code:
gender : “female” }
Here “student” is our prototype object. Now, using this, let’s create another
object:
Code:
change any of the values to this newly created object, then that is done as
follows:
Code:
Now, the student_1 object has similar property values as that of the student
access it? Well, javascript provides two ways using which one could access the
object:
Syntax:
object.property
Example:
gender : “female” }
Now to access the object and its properties, let’s print it to console:
Code:
Syntax:
object[‘property’]
Example:
Code:
console.log (“Student” + student[‘name’] + “is” +
if both the objects are equal and return a Boolean value. That is, if both
Code:
console.log(Object.entries(student));