Object access bracket notation does not accept String object

Asked

Viewed 85 times

3

I am trying to call a function which is a property of an object, passing a parameter to it. For this I use bracket notation plus this: (parâmetro).

Thus:

afraid[day](num.toString())

But returns error:

afraid[day] is not a Function.

I tried with string template too:

afraid[`${day}`](num.toString())

and also:

afraid[`"${day}"`](num.toString())

and makes the same mistake:

Typeerror: afraid[((""" +] is not a Function

It only works if I pass the object property name as a literal string, but it’s not what I need:

afraid["Tuesday"](num.toString())

See the function on the object:

let afraid = {
    Monday: 12,
    Tuesday: function(number){
     if(number>95)return true
     else return false
    },
    Wednesday: 34,
    Thursday: 0,
    Fryday: function(number){
      if(number%2 == 0) return true 
      else return false
    },
    Saturday: 56,
    Sunday: 666
  }

And the attempt to use the function:

 if(afraid[day] == Math.abs(num) || afraid[`${day}`](num.toString()) == true) return true
  else return false
  • 1

    Not all the keys to afraid are functions, the error does not occur only when day it is neither 'Tuesday' nor 'Fryday'? https://ideone.com/Jj09v3

  • 1

    Are you sure the value of day is what is expected?

  • 1

    But your object itself, the keys of the functions are literal strings, if you have a return of the literal keys within this day object, just do this: afraid[(day).toString()](num.toString())

  • What exactly is returning: day? that has in this: const day = "???"

  • @hkotsubo. It makes sense, because not all day properties are functions, but I didn’t think it would give error when testing an if.

  • @Ivanferrer day is a string

Show 1 more comment

1 answer

6


In its object afraid not all values are functions. The key value 'Monday', for example, it is a number. Only keys Tuesday and Fryday have functions as value. So it is only possible to call these functions if the key is Tuesday or Fryday:

let afraid = {
    Monday: 12,
    Tuesday: function(number){
     if(number>95)return true
     else return false
    },
    Wednesday: 34,
    Thursday: 0,
    Fryday: function(number){
      if(number%2 == 0) return true 
      else return false
    },
    Saturday: 56,
    Sunday: 666
};

// afraid['Tuesday'] é uma função, funciona
let day = 'Tuesday';
console.log(afraid[day](100)); // true

// afraid['Monday'] é um número, vai dar erro
day = 'Monday';
console.log(afraid[day](100)); // erro

What you can do is use typeof to check whether afraid[day] in fact it is a function, and only call it if it really is:

function test(day, num) {
    let afraid = {
        Monday: 12,
        Tuesday: function(number) {
           return number > 95;
        },
        Wednesday: 34,
        Thursday: 0,
        Fryday: function(number) {
          return number % 2 == 0;
        },
        Saturday: 56,
        Sunday: 666
    };

    return afraid[day] == Math.abs(num) ||
           (typeof afraid[day] === 'function' && afraid[day](num));
}

console.log(test('Monday', 12)); // true
console.log(test('Tuesday', 100)); // true

console.log(test('Saturday', 12)); // false
console.log(test('Fryday', 11)); // false

So I just call the function afraid[day] if it really is a function.

I also simplified your if's. After all, an expression like:

if (condicao) return true;
else return false;

Can be simplified to:

return condicao;

And I removed the toString() of num, because within the functions you compare the value with numbers, and not with strings, so I didn’t understand why to convert to string when passing to the functions.


Another option is to use the ternary operator in the return:

return typeof afraid[day] === 'function' ?
       afraid[day](num) :
       afraid[day] == Math.abs(num);

Or good old man if/else:

if (typeof afraid[day] === 'function')
    return afraid[day](num);
else return afraid[day] == Math.abs(num);

Finally, I don’t know if it was a typo, but the correct one is "Friday," not "Fryday".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.