DEV Community

Cover image for JavaScript Object Method and String Method
Ramkrishna
Ramkrishna

Posted on

JavaScript Object Method and String Method

Here we will discuss about different types of JavaScript Object Method and String Method with explanation and suitable example.

First we will discuss about Object Methods.

  • How to create an Object In JavaScript object is created in key: "value" pair each key have their own value it can string, number, array, function, other object and any data-type.
const obj = new Object();//empty object
//storing data in object
obj.name = "Dev";
obj.section = "B";
console.log(obj);//{ name: 'Dev', section: 'B' }
console.log(obj.name);//Dev

//Here name is key and Dev is value

//Another way to create a object
const language ={
    name: "JavaScript",
    description: "A Programming Language"
}
console.log(language);//{ name: 'JavaScript', description: 'A Programming Language' }
//We can change the value also
language.name = "Python";
console.log(language);//{ name: 'Python', description: 'A Programming Language' }
Enter fullscreen mode Exit fullscreen mode

Object.keys()

When we pass any object in this method it returns the all keys of that object as an array .

Example: In this example Returns myObject keys in array format in myObjectKeys

let myObject = {
    name: "John",
    age: 30,
    city: "New York",
    profession: "Software Engineer",
    hobbies: ["reading", "coding", "traveling"],
    isMarried: true
};
const myObjectKeys = Object.keys(myObject);

console.log(myObjectKeys);
//[ 'name', 'age', 'city', 'profession', 'hobbies', 'isMarried' ]
Enter fullscreen mode Exit fullscreen mode

Object.values()

When we pass any object in this method it returns the all values of that object as an array .

Example:

let myObject = {
    name: "John",
    age: 30,
    city: "New York",
    profession: "Software Engineer",
    hobbies: ["reading", "coding", "traveling"],
    isMarried: true
};
const myObjectValues = Object.values(myObject);

console.log(myObjectValues);
/*['John', 30, 'New York', 'Software Engineer',
    ['reading', 'coding', 'traveling'], true]*/
Enter fullscreen mode Exit fullscreen mode

Object.entries()

It allows you to extract the enumerable property [key, value] pairs from an object and return them as an array.

Example:

let myObject = {
    name: "Alice",
    age: 25,
    city: "Goa",
    occupation: "Designer"
};

const myObjectPair = Object.entries(myObject);

console.log(myObjectPair);
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
[[ 'name', 'Alice' ], [ 'age', 25 ], [ 'city', 'Goa' ], [ 'occupation', 'Designer' ]]

Object.fromEntries()

It transforms a list of key-value pairs into an object. It takes an iterable (like an array) whose elements are arrays or iterable objects with two elements (key and value) and returns a new object initialized with those key-value pairs.

Example:

const arrayLitral = [
    [ 'name', 'Steve' ],
    [ 'age', 27 ],
    [ 'city', 'New York' ],
    [ 'occupation', 'Developer' ]
  ];

  const myObj = Object.fromEntries(arrayLitral);

  console.log(myObj);
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
{ name: 'Steve', age: 27, city: 'New York', occupation: 'Developer' }

Object.assign()

It used to copy the values of all enumerable own properties from one or more source objects to a target object. It returns the target object after merging the properties of the source objects into it.
Syntax: Object.assign(target, ...sources objects)

Example:

const target = { a: 1, b: 2 };
const source1 = { b: 3, c: 4 };
const source2 = { c: 5, d: 6 };

const mergedObject = Object.assign(target, source1, source2);
// The properties of source1 and source2 are copied into target.
//If a property exists in both target and a source object, the value from the source object overwrites the value in target.
//The mergedObject is the modified target object with properties from all source objects.

console.log(mergedObject);

const randomObject = {
    key1: "value1",
    key2: 42,
    key3: ["a", "b", "c"],
    key4: { nestedKey: "nestedValue" }
};

const cloneRandomObject = Object.assign({}, randomObject);
//it copies the randomObject into a empty object and returns the value

//if we change or add something in original obj it does not changes in cloned object

randomObject.key1 = "randomValue1";
randomObject.key5 = true;

console.log(cloneRandomObject);
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
{ a: 1, b: 3, c: 5, d: 6 }
{key1: 'value1', key2: 42, key3: [ 'a', 'b', 'c' ], key4:{nestedKey: 'nestedValue' }}

Object.freeze() & Object.isFrozen()

frozen prevents to add, remove the new properties in object it's also prevent to modify the current objects elements.
where as isFrozen check the object is freeze or not if that object is frozen it returns true else it will returns false.

Example:

const myObj = {name: "Alex", age: 25};
Object.freeze(myObj);// freeze the myObj

myObj.email = "alex@gmail.com";//adding the value but the object is freeze so value will not added
myObj.name = "Steve";//value not modified it's shows an error in strict mode

console.log(myObj);

console.log(Object.isFrozen(myObj));// it shows true because object is frozen

Enter fullscreen mode Exit fullscreen mode

OUTPUT:
{ name: 'Alex', age: 25 }
true

Object.seal() & Object.isSealed()

This method is used to seal an object. Sealing an object means that it's existing properties cannot be deleted, but their values can be changed it also prevent to add new properties.
isSealed checks the object is sealed or not if the object is sealed it returns the true boolean value if the object is not sealed it returns the false.
Example:

const myObj = {name: "Alex", age: 25};
Object.seal(myObj);// freeze the myObj

myObj.email = "alex@gmail.com";//adding the value but the object is sealed so value will not added
myObj.name = "Steve";//value modified

console.log(myObj);

console.log(Object.isSealed(myObj));// it shows true because object is sealed
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
{ name: 'Steve', age: 25 }
true

Object.isExtensible() & Object.preventExtensions()

This method prevent to add new value in object or isExtensible checked the object is Extensible or not it returns boolean value.

Example:

const myObj = {
    key1: "value1",
    key2: "value2",
    key3: "value3"
}
console.log(Object.isExtensible(myObj));//true
Object.preventExtensions(myObj);

myObj.key4 = "value4";//but property will not added

console.log(Object.isExtensible(myObj));//false
console.log(myObj);
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
true
false
{ key1: 'value1', key2: 'value2', key3: 'value3' }

Object.create()

This method creates a new object with the specified prototype of the new object. The properties of prototype object can be access in new object.
Example:

const protoMethods = {
    square: function(){
       console.log(`Square of ${this.key1} is ${(this.key1)**2}`);
       console.log(`Square of ${this.key2} is ${(this.key2)**2}`);
       console.log(`Square of ${this.key3} is ${(this.key3)**2}`);
    }
}

const numObj = Object.create(protoMethods);//set prototype protoMethods
numObj.key1 = 4;
numObj.key2 = 6;
numObj.key3 = 9;
console.log(numObj.square());//property of prototype (square) is used in numObj
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
Square of 4 is 16
Square of 6 is 36
Square of 9 is 81

Object.hasOwn() & .hasOwnProperty()

Syntax Object.hasOwn(object name, "object key");
objectName.hasOwnproperty("object key");
Both methods returns true if the key present in the object else it will return false.
Example:

let myObject = {
    name: "Alice",
    age: 25,
    city: "Goa",
    occupation: "Designer"
};

console.log(Object.hasOwn(myObject, "name"));//true
console.log(Object.hasOwn(myObject, "address"));//false

console.log(myObject.hasOwnProperty("city"));//true
console.log(myObject.hasOwnProperty("country"));//false
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
true
false
true
false

Object.getOwnPropertyNames()

It returns an array containing the names of all properties that belong to the object itself, not its prototype chain.
Example:

const protoObj = {
    greet() {
      console.log("Hello!");
    }
  };

  // Create a new object with protoObj as its prototype and define properties directly
  const newObj = Object.create(protoObj, {
    name: {value: "John"},
    age: {value: 35}
  });

newObj.greet();//great is the prototype value
const propertyName = Object.getOwnPropertyNames(newObj);
console.log(propertyName);
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
Hello!
[ 'name', 'age' ]

Object.getOwnPropertyDescriptor()

This static method use to get own property descriptor on a given object.
Example:

const obj = {
  name: "John",
  age: 30
};

const descriptor = Object.getOwnPropertyDescriptor(obj, 'name');
console.log(descriptor);

Enter fullscreen mode Exit fullscreen mode

OUTPUT:
{
value: "John",
writable: true,
enumerable: true,
configurable: true
}
Note:
value: The value of the property.
writable: Whether the value of the property can be changed.
enumerable: Whether the property will be returned in certain object iteration methods.
configurable: Whether the property descriptor can be changed and the property can be deleted.

Object.getOwnPropertyDescriptors()

this method returns the object of all object properties descriptors.
Example:

const myObj = {name: "Brohit", class: 11, fav: "cricekt", occupatons: "designer"};

const discriptValue = Object.getOwnPropertyDescriptors(myObj);
console.log(discriptValue);
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
{
name: {
value: 'Brohit',
writable: true,
enumerable: true,
configurable: true
},
class: { value: 11, writable: true, enumerable: true, configurable: true },
fav: {
value: 'cricekt',
writable: true,
enumerable: true,
configurable: true
},
occupatons: {
value: 'designer',
writable: true,
enumerable: true,
configurable: true
}
}

value, writable, enumerable, configurable described in previous example

Object.defineProperty()

Syntax: Object.defineProperty(obj, "prop", {descriptor})
In this method we define the own property for the object element.

Example:

const myObj = {}; 
Object.defineProperty(myObj, 'prop1', { 
    value: 65, 
    writable: false
}); 
myObj.prop1 = 7; //writable value is false so we cannot change the value to 7
console.log(myObj.prop1); 
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
65

Object.defineProperties()

Syntax: Object.defineProperties(object, {key1:{discriptor}, key2:{discriptor}, keyn:{discriptor}})
In this method we define the own properties for the object's one or more then one elements.

Example:

const myObj = {}; 

Object.defineProperties(myObj,{
    key1:{
        value:"value1",
        writable: true,
        enumerable: true,
        configurable: true
    },
    key2:{
        value:"value2",
        writable: true,
        enumerable: false,
        configurable: true
    },
    key3:{
        value:"value3",
        writable: false,
        enumerable: true,
        configurable: true
    }
});
myObj.key1 = "Changed Value1"//value changed
myObj.key3 = "Changed Value3";//discriptor writable is false so cannot changed the value

//applying loop in myObj key2 will not display in loop because enumerable is false
for(let key in myObj){
    console.log(myObj[key]);
}
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
Changed Value1
value3

Importent String Methods

String method -

it includes charAt(), concat(), endsWith(), startswith(), includes(), indexOf(), padEnd(), padStart(), repeat(), replace(), replaceAll(), search(), slice(), split(), subString(), toLowerCase(), toUpperCase(), trim(), trimEnd(), trimStart()

We will understand these methods with the help of certain example

charAt(), concat(), endsWith() and startswith()

Example:

const myString = "Hello World";
const spaceString = " ";
const anotherString = "Welcome";

//charAt returns the char at that index
console.log(myString.charAt(4));//o

//concat merge the strings
console.log(anotherString.concat(spaceString,myString));//"Welcome Hello World"

//endsWith
console.log(myString.endsWith("World"));//true
console.log(myString.endsWith("Hello"));//false

//startsWith
console.log(myString.startsWith("Hello"));//true
console.log(myString.startsWith("Random"));//false
Enter fullscreen mode Exit fullscreen mode

includes(), indexOf(), padEnd() and padStart()

Example:

const myString = "Hello World";
const spaceString = " ";
const anotherString = "Welcome";

//includes
console.log(myString.includes("o"));//true
console.log(myString.includes("z"));//false

//indexOf
console.log(anotherString.indexOf("c"));//3
console.log(myString.indexOf("o"));//4

//padEnd
console.log(myString.padEnd(15, "p"));//after Hello World it added p till 15th index. output:Hello Worldpppp
console.log(anotherString.padEnd(12, "Yes"));//WelcomeYesYe

//padStarts
console.log(myString.padStart(17, "Alex"));//AlexAlHello World
console.log(spaceString.padStart(5, "M"));//MMMM 
Enter fullscreen mode Exit fullscreen mode

repeat(), replace(), replaceAll() and search()

Example:

const anotherString = "Welcome";

//repeat
console.log(anotherString.repeat(3));//WelcomeWelcomeWelcome

//replace
console.log("Hello World World".replace("World", "Earth"));//Hello Earth World

//replaceAll
console.log("Hello World World".replaceAll("World", "Earth"))//Hello Earth Earth

//search(it returns the first index where the value found in string)
console.log("Hello World Welcome to the hell".search("Welcome"));//12
Enter fullscreen mode Exit fullscreen mode

slice(), split() and subString()

Example:

//slice(start Index, value - 1 index )
console.log("Hello World!".slice(6)); // World! (cut the element from index 6 to last index)
console.log("Hello World!".slice(6, 11)); // World (from 6 to 11 - 1 means 10th index)


//split  it returns the array of split element
console.log("hello,world,hello,world".split(","));
// output - [ 'hello', 'world', 'hello', 'world' ]


//substring
console.log("hello".substring(2)); // llo
console.log("hello".substring(1, 3)); // el
Enter fullscreen mode Exit fullscreen mode

toLowerCase(), toUpperCase(), trim(), trimEnd() and trimStart()

Example:

const myString = "Hello World";

//toUpperCase
console.log(myString.toUpperCase());//"HELLO WORLD"

//toLowerCase
console.log(myString.toLowerCase());//"hello world"

//trim it removes spaces from the string
const spaceString = "    Hello    ";
console.log(spaceString.trim());//"Hello"

//trimEnd
console.log(spaceString.trimEnd());//"    Hello"

//trimStart
console.log(spaceString.trimStart());//"Hello    "
Enter fullscreen mode Exit fullscreen mode

So, we understand the object methods and string methods with the help of examples if you have any doubt or suggestion related to this topic please write down in the comment.
Happy Learning😊

Top comments (0)