Akin Zeman
Akin Zeman

Reputation: 507

how to use dynamic variables in object value?

is it possible to use dynamic variables in object value? (not property)

errors = { 'small_age':`${age} is too small`}

age = 17;
if (age < 18) {
   alert(errors.small_age)
} 

Upvotes: 1

Views: 74

Answers (3)

Akin Zeman
Akin Zeman

Reputation: 507

thanks to @Diego_Sanches, I solved like that jsfiddle

const errors = { 
  'too_young': (n) => `${n} is too young`,
  'too_short': (n) => `${n} is too short`,
  'too_heavy': (n) => `${n} is too heavy`,
  //there thousant err msgs, and didnot want to seperate each of them for related functions...  
  }

function check_age(n){
  if (n < 18) alert(errors.too_young(n)) 
}

function check_height(n){
  if (n < 180) alert(errors.too_short(n))
}

function check_weight(n){
  if (n > 90) alert(errors.too_heavy(n))
}

check_age(17);
check_height(150);
check_weight(120);

Upvotes: 0

Diego Sanchez
Diego Sanchez

Reputation: 83

You can use a function as the value in an object and then pass the variable that you want to use as a parameter, that way it's more obvious what value is being used on the error message.

const errors = { 'small_age': (age) => `${age} is too small` }

const age = 17;
if (age < 18) {
   alert(errors.small_age(age))
}

Expected alert message

17 is too small

Upvotes: 1

Rikki
Rikki

Reputation: 3528

JavaScript is a Dynamic Programming Language. (Read more about Dynamic Type Systems)

Your code is correct (even though you haven't included the code to define var age). Here is the fiddle for it. Be vary of what version of JavaScript you use that supports Template Literals.

Upvotes: 1

Related Questions