DEV Community

Himanshupal0001
Himanshupal0001

Posted on

Simple Js hacks for strings and objects 🙌

Tricks

This document contain the simple yet important tricks to remember when dealing with strings or objects.

1. Convert any string to array simply by a single function.

Use split("", limit{any number})

//code

const str = 'abra ka dabra'
console.log(str.split(' ', 2))

output 
[ 'abra', 'ka' ]
Enter fullscreen mode Exit fullscreen mode

2. Add properties to js objects dynamically

Use (.) operator

//code

const dynamicObject = {
    name: 'Himanshu',
    age: 22
};
dynamicObject.sex = 'Male';

console.log(dynamicObject);

//output

{ name: 'Himanshu', age: 22, sex: 12 }
Enter fullscreen mode Exit fullscreen mode

3. Adding properties of a previous object to new object


//code
const object1 = {
    name : 'Himanshu',
    age : 22
}

const newObject  = {};
newObject.name = object1.name;
newObject.age = object1.age;
newObject.sex = 'Male';

console.log(newObject);


//output
{ name: 'Himanshu', age: 22, sex: 'Male' }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)