# Creating and finding posts using Parse.com

The following code calls Parse. And uses its API to create two functions: post.create and post.find. As the names imply, one is for creating posts and the other for fetching them.

Example:

import Parse from 'parse'

Parse.initialize('APP_ID', 'CLIENT_KEY')

const post = {}

post.create = json => {
const Post = Parse.Object.extend('Post')
const post = new Post()
post.save(json).then(object => {
console.log('yay! it worked', object)
})
}

post.find = () => {
const query = new Parse.Query(Post)
let arr = []
query.find({
success: function (results) {
results.forEach(function (result) {
arr.push(result.toJSON())
})
},
error: function (error) {
alert('Error: ' + error.code + ' ' + error.message)
}
})
return arr
}

export default post


As you can see, const Post = Parse.Object.extend('Post') is being written twice. I could just declare it once at the top of the file, on the other hand, they would be farther from the place they are used.

What's the conventional option here?

• Looks like you want an ES6 class. – Dan Jan 12 '16 at 15:35

This depends on the scope in which you want the variable to have.

Is the variable the same between the two function calls? if so, you would tend to only define it once, as calling it twice may be expensive.

Interestingly however, you've defined an ES6 const which will complain if you redefine the same value (which is why I presume you've named the variable differently).

If you intended the variable to be different between the two calls, you would normally not use const.

Looking at your example, I would define this variable once, and use the const keyword in order to explicitly avoid is being redefined by accident elsewhere.

You also ask about conventions. Looking at the MDN page for const, they advise naming constants with uppercase characters. So I would probably go down that route unless it contravenes your coding style: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

• I would disagree with the MDN recommendation for const. Nearly every variable you write will be declared const in JavaScript, and SHOUT_CAST is very jarring when there's a lot of them (and it dilutes the meaningfulness behind the convention). The SHOUT_CASE is useful when you're in a language that doesn't support constants natively, but you have runtime support with const. If anything needs to have attention drawn to, it's let - mutability is special. – Dan Jan 12 '16 at 15:39
• Yeah I'm not advocating that style personally, but there is certainly a convention to put consts as upper case. Coming from a Java/C# background this would often be the case, my thoughts were 'an' convention (albeit contentious) would be better than none! – dougajmcdonald Jan 12 '16 at 15:43