0

Goal: I'm trying to create a simple function which checks if a property exists in an object, if it doesn't, the property is then created and the value is assigned to it. Problem: the parameter from the function parameters is not being read.

let b = {
  name: 'Chuck Berry',
  job: 'musician',
  bestTune: 'Johnny Be Good',
};

const propertyChecker = (obj, property) => {
  obj.property = obj.property || 'American';
  console.log(obj);
};

propertyChecker(b, 'nationality');

console.log: {name: 'Chuck Berry', job: 'musician', bestTune: 'Johnny Be Good', property: 'American'} bestTune: "Johnny Be Good" job: "musician" name: "Chuck Berry" property: "American" ---- this should be (nationality: "American")

amurra
  • 15,221
  • 4
  • 70
  • 87
REM
  • 3
  • 1

1 Answers1

0

In JavaScript, there are 2 ways to access a property of an object:

  1. dot notaion: obj.property;
  2. brackets notation: obj['property'];

If the property is stored in a variable, you can only use the brackets notaion.

You need to change this line:

obj.property = obj.property || 'American';

to:

obj[property] = obj.[property] || 'American';

because property is a variable.

Idan
  • 202
  • 2
  • 5
  • Thanks Idan for this concise answer. So I patched some holes in my JS foundation and as I understand: the function parameters are variables, therefore my argument from function call becomes a variable, how does that sound? – REM Aug 26 '22 at 19:12
  • @REM yes, and when you pass a variable to a function, a copy of the variable is created. [is-javascript-a-pass-by-reference-or-pass-by-value-language](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Idan Aug 26 '22 at 20:43