menu

JavaScript

A community to get help with JavaScript, find jobs, outsource and much more!

Channels
# All channels
view-forward
# General
view-forward
# Jobs
view-forward
# Node.js
view-forward
# React
view-forward
# Snippets
view-forward
# Vanilla
view-forward
# Vue.js
view-forward
Team

Object or just single property as argument to function?

March 17, 2019 at 11:24am

Object or just single property as argument to function?

March 17, 2019 at 11:24am (Edited 1 year ago)
I have person object.
const person = {
name: 'Adam',
surname: 'Smith',
address: {
streetNumber: 1
street: 'Hamilton Street',
state: 'Alabama',
postCode: 00000
}
}
and want to transform person.address.state property.
What is best practice for passing argument to function?
// Passing single property
matchState(person.address.state) // ALABAMA_COUNTY
// Passing whole object
matchState(person) // ALABAMA_COUNTY
const matchState = (param) => {
// what should be param?
if(param.address.state === 'Alabama') return 'ALABAMA_COUNTY'
// or
if(param === 'Alabama') return 'ALABAMA_COUNTY'
...
}

March 18, 2019 at 2:02am
Hi, in my opinion it depends, for me I base the parameters of a function base on its definition. For example your matchState, I've perceived that its definition is to match a state and return something, so the matchState function does not know anything about person object or any object outside its scope, if my perception of the matchState function is correct I would probably go for matchState(person.address.state) because it can be used also if you have matchState(otherObject.state) other object, but I think this is not just the basis for passing arg to function, as I said it depends and it has many factors. I always suggests to make the function pure and has single responsibility.
like-fill
1
  • reply
  • like

March 18, 2019 at 4:31pm
Looking at your function, I'd definitely say to only pass the state here. There are a couple reasons for this, the main two being that A: You only need the state for the function, save memory where you can, and B: If you want to change the name of that object property later, it will be more difficult to track down.
like-fill
1
  • reply
  • like

November 17, 2019 at 1:01pm
Update: I found that second solution matchState(person.address.state) is better when writing tests, because you don't need to create mock objects, cloning existing, reseting it in beforeEach etc... You just pass a single value.
Edited
like-fill
2
  • reply
  • like