-1

I would like to set a variable that will store the return value of functions. The return value can either be a string, number or boolean but I don't have any guarantee which one of them will be returned.

Is it possible to use the variable to store either a number, string or boolean depending on the type that the functions will return without applying any conversions?

For example, first I declare var returnValue = 0. Then a function functionAmay return the string 'passed' and I want to store it in returnValue by writing returnValue = functionA(). Then another function functionBmay return 10 or false and I would like to use returnValue by writing returnValue = functionB(). Can it be done?

Bernard Mizzi
  • 49
  • 1
  • 1
  • 8

1 Answers1

0

Yes you can.

In Javascript, a variable can store any type of data as JS is untyped as referred in the comments in the main question.

function fn(type) {
  if(type == 'string') return 'passed';
  if(type == 'number') return 1;
  if(type == 'boolean') return true;
}

let returnedValue;
returnedValue = fn('string');
console.log(returnedValue, typeof returnedValue);

returnedValue = fn('number');
console.log(returnedValue, typeof returnedValue);

returnedValue = fn('boolean');
console.log(returnedValue, typeof returnedValue);
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
Ishwar Patil
  • 1,671
  • 3
  • 11
  • 19