Client side Java script Server side Java script Data types variables Operators Expressions Functions Objects Array Date and math related objects Document objectmodel Event handling
Key characteristics of JavaScript objects:
Key-Value Pairs:
Objects
store data in properties, where each property consists of a unique string
"key" (or property name) and an associated "value."
Dynamic and
Mutable:
Objects
are dynamic, meaning properties can be added, modified, or deleted at any time
after the object's creation. They are also mutable, allowing changes to
their internal state.
Values of Any Type:
The
value associated with a key can be of any data type, including primitives
(strings, numbers, booleans), other objects, arrays, or even functions.
Methods:
When
a function is assigned as the value of a property within an object, it is
referred to as a method. Methods represent actions or behaviors associated
with the object.
Encapsulation:
Objects
allow for data grouping and encapsulation, bringing together related data and
the functions that operate on that data.
How to Create a
JavaScript Object
An object
literal is a concise way to
create an object.( concise -brief)
An
object literal is a list of key : value pairs inside curly
braces { }:
{firstName:"John",
lastName:"Doe", age:50, eyeColor:"blue"}
In
object terms, the key : value pairs are the object properties.
Examples
All
the examples below, create a JavaScript object with 4 properties.
//
Create an Object
const person = {firstName:"John", lastName:"Doe",
age:50, eyeColor:"blue"};
Creating Objects:
An
object in JavaScript is a collection of key-value pairs, where keys are strings
(properties) and values can be any data type. Objects can be created using
object literals, constructors, or classes. Properties are defined with
key-value pairs, and methods are functions defined within the object, enabling
encapsulation and organization of data and behaviour.
Creating object with a
constructor
One
of the easiest ways to instantiate an object is in JavaScript. Constructor is
nothing but a function and with the help of a new keyword, the constructor
function allows to creation of multiple objects of the same flavour as shown
below:
//
Simple function
function
vehicle(name, maker, engine) {
this.name = name;
this.maker = maker;
this.engine = engine;
}
//
New keyword to create an object
let
car = new vehicle('GT', 'BMW', '1998cc');
//
Property accessors
console.log(car.name);
console.log(car.maker);
console.log(car['engine']);
Output
GT
BMW
1998cc
Explanation:
Class Components: A class in OOP has
parameters and member functions, encapsulating attributes and behaviors.
Constructor Function: In a class method,
parameters (e.g., name, maker, engine) use this to differentiate between class
attributes and argument values.
Object Creation: Create an object
(e.g., obj) from the class, initialize it, and call its methods to use the
class functionality.
Using object literals
Using
object literals to create objects in JavaScript involves defining an object
directly with key-value pairs inside curly braces {}. This method is concise
and straightforward, allowing you to quickly create objects with properties and
methods, enhancing code readability.
//
Creating js objects with object literal
let
car = {
name: 'GT',
maker: 'BMW',
engine: '1998cc'
};
//
Property accessor
console.log(car.name);
//dot notation
console.log(car['maker']);
//bracket notation
Output
GT
BMW
Explanation:
In
the above code example we Created a car object using an object literal with
properties like name, maker, and engine.
Used
dot notation and bracket notation to access properties of the car object.
Now
let's see how we can add more properties to an already defined object:
let
car = {
name: 'GT',
maker: 'BMW',
engine: '1998cc'
};
//
Adding property to the object
car.brakesType
= 'All Disc';
console.log(car);
Output
{
name: 'GT', maker: 'BMW', engine: '1998cc', brakesType: 'All Disc' }
Methods
can also be part of the object while creation or can be added later like
properties as shown below:
//
Adding methods to the car object
let
car = {
name : 'GT',
maker : 'BMW',
engine : '1998cc',
start : function(){
console.log('Starting the engine...');
}
};
car.start();
//
Adding method stop() later to the object
car.stop
= function() {
console.log('Applying Brake...');
}
car.stop();
Output
Starting
the engine...
Applying
Brake...
Explanation: In
the above code start method was added to the car object and later called by
the car.start() and also the stop method was added too after the
object was already declared.
Creating
object with Object.create() Method
The
Object.create() method in JavaScript creates a new object using an existing
object as its prototype. This approach allows the new object to inherit
properties and methods from the prototype object, enabling inheritance-like
behavior. It's useful for creating objects with shared behaviors while
maintaining unique properties.
const
coder = {
isStudying : false,
printIntroduction : function(){
console.log(`My name is ${this.name}.
Am I studying?: ${this.isStudying}`);
}
};
const
me = Object.create(coder);
me.name
= 'Mukul';
me.isStudying
= true;
me.printIntroduction();
Output
My
name is Mukul. Am I studying?: true
Using
ES6 classes
Using
ES6 classes to create objects in JavaScript involves defining a class with a
constructor to initialize properties and methods. Objects are then instantiated
from the class using the new keyword, offering a more structured and OOP-like
approach to object creation.
//
Using es6 classes
class
Vehicle {
constructor(name, maker, engine) {
this.name = name;
this.maker = maker;
this.engine = engine;
}
}
let
car1 = new Vehicle('GT', 'BMW', '1998cc');
console.log(car1.name); //GT
Output
GT
Accessing and Modifying
Properties:
Properties
within an object can be accessed and modified using dot notation or bracket
notation:
JavaScript
console.log(person.firstName);
// Accessing with dot notation
console.log(person["lastName"]); // Accessing with bracket notation
person.age = 31; // Modifying a property
person.email = "john.doe@example.com"; // Adding a new property
Methods:
Methods
are invoked using dot notation followed by parentheses:
JavaScript
person.greet();
// Calling the greet method
2. Array: Represents
an ordered list of values.
Array: A specialized type of object used to
store ordered collections of elements. Elements in an array are accessed
by their numerical index, starting from 0. Arrays can hold elements of
different data types.
Arrays are ordered
collections of values, enclosed in square brackets []. Elements in an
array are accessed by their numerical index, starting from 0.
Syntax:
const array_name =
[item1, item2, ...];
Example
const colors = ["red",
"green", "blue"];
const mixedData = [1,
"hello", true, { key: "value" }];
Example
let a = ["red", "green", "blue"];
No comments:
Post a Comment