Like this:
function show (message)
{
alert(message.head);
// or
alert(message['head']); // Note the quotes
}
Your call to it is fine.
To supply defaults, as David points out, you can use the curiously powerful ||
operator:
function show (message)
{
var head = message.head || 'error',
body = message.body || 'msg';
alert(head);
}
(The above is slightly different from David's approach in that it avoids changing the message
object that was passed in, which is usually not a good idea as the function doesn't own the object, the caller does.)
That works because if head
(for example) isn't on the message
object at all, it's falsey, and so head = message.head || 'error'
ends up assigning 'error'
to head
. This is a handy trick, but there's a gotcha: If head
could have a falsey value already, and that's valid, you don't want to use the ||
trick. Instead, you can use in
to check:
function show (message)
{
var head = 'head' in message ? message.head : 'error',
body = 'body' in message ? message.body : 'msg';
alert(head);
}
That will use the value from message
if it's present, regardless of whether it's falsey.