Needing Help with Accessing Object Properties with Variables

When I changed ‘prop’ (the value stored in the local variable) to something such as ‘things’ or anything I want name it causes the output ‘undefined’. What is this ‘prop’ and why I cannot change it to something different?

var result = myFunc(“Name”); used to call my function and if I changed the “Name” to “name” it causes the output to be ‘undefined’. Please tell me the reason why I cannot change “Name” to “name”?

The codes below outputs “David” but if you changed the parameter or the value of that local variable “prop” to something it will output “undefined”.

var someObj ={
    propName: "David"
function myFunc(str){
    var s = "prop";    
    return s + str;
var result = myFunc("Name");

As you can see 'prop' is a string inside the variable s inside the function.

the function will return s + str, which is prop + str(the parameter of the function)
this will return 'propName' because at the bottom the parameter "Name" is passed.
and then if you see the top of the code

the object inside the variable is called propName so if you changed the variable s into something else like things it will return thingsName which is not inside the variable someObj

1 Like

Thank you for helping me understand JavaScript better with your clear explanation.

1 Like

Nice to know I helped :slight_smile:

1 Like