JavaScript – Interesting Objects And Functions Properties

ES6 provides few interesting ways to manipulate objects and functions with minimal code and maximum readability. Here is how we store variables in an object by simple JS function.

let name = 'Harper'
let age = '25'
let address = '123 Street, ABC'

function getPerson(name, age, address){
    return {
        name:name,
        age:age,
        address:address,
    }
}
console.log(getPerson(name, age, address))

But in ES6 we can just simply remove duplication like name:name, age:age etc and write. 

let name = 'Harper'
let age = '25'
let address = '123 Street, ABC'

function getPerson(name, age, address){
    return {name, age, address}
}

console.log(getPerson(name, age, address))

Now if we want to call functions inside getPerson function then we used to do this. 

let name = 'Harper'
let age = '25'
let address = '123 Street, ABC'

function getPerson(name, age, address){
    return {
        name:name, 
        address:address,
        getAge: function(){
            return age
        }
    }
}

console.log(getPerson(name, age, address).getAge())

But with the new syntax we can write this. 

let name = 'Harper'
let age = '25'
let address = '123 Street, ABC'

function getPerson(name, age, address){
    return {
        name, 
        address,
        getAge(){
            return age
        }
    }
}

console.log(getPerson(name, age, address).getAge())

We can compute different properties on the run time in ES6 as well. 

let nameType = 'first'
const person = {
    [nameType+'Name']: 'John' 
}
console.log(person.firstName)

nameType = 'last'
const person1 = {
    [nameType+'Name']: 'Doe' 
}
console.log(person1.lastName)

Or there is a better way to do this too. 

const myVariable = 'first';
function computeNameType( type ) {
  return type + 'Name';
}
const person = {
  [ myVariable + 'Name' ] : 'John',
  [ computeNameType( 'last' ) ]: 'Doe'
};

console.log(person.firstName)
console.log(person.lastName)

Remember that these braces [] are very important. They hold the key to compute values on the runtime. We can also implement a very interesting and magical property of ES6 enhanced object properties. 

const PI = 3.14
const inchesToFeet = 0.083333

const interestingMaths = {
    PI,
    inchesToFeet,
    sum(num1, num2){
        return num1+num2
    },
    subtract(num1, num2){
        return num1-num2
    }
}

console.log(interestingMaths.PI)
console.log(interestingMaths.inchesToFeet)
console.log(interestingMaths.sum(3,5))
console.log(interestingMaths.subtract(9,5))

I hope these updates will help you in your JS learning venture.