What's the most readable way to write nested functions in javascript?

The example of this code I wrote doesn't look as readable as it gets:

function getShortMessages(messages) {
    return messages.filter((messages) => {
        return messages.message.length < 50
    }).map((object) => {
        return object.message
    })
}

      

+3


source to share


3 answers


Seems honest to me. What you can do is replace "50" with a variable in your js file.

var MESSAGE_MAX_LENGTH= 50;

      

And re-place the bit the way you are addressing the function



function getShortMessages(messages) {
    return messages
        .filter( (messageObject) => { 
            return messageObject.message.length < MESSAGE_MAX_LENGTH 
        })
        .map( (messageObject) => {
            return messageObject.message 
        });
}

      

Also I found that when accessing an array messages

and running a function, filter

it is better not to call the object messages

, but item

ormessageObject

Also, object

in a function map

is a little sinister, call it messageObject

again, for example, so you know what exactly you are using

+1


source


in ES 6 you can use shortcuts like:

function getShortMessages(messages) {
    return messages.filter( messages => messages.message.length < 50).map( object => object.message )
}

      



Its up to you who we read. On one line, you don't need to use {}

and return

, and if you are using an array function, with 1 parameter you also don't need to (messages) =>

, you can only usemessages =>

+1


source


function getShortMessages(messages) {
  return messages.filter(message => message.message.length < 50)
    .map(message => message.message)
}
      

Run code


0


source







All Articles