-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?

3
  • 4
    Can it be done? Answer is Yes as JavaScript is untyped/Weakly typed. Commented Mar 16, 2018 at 10:03
  • 1
    … Have you tried it? Commented Mar 16, 2018 at 10:06
  • This was more of a question for my own interest on javascript. Commented Mar 16, 2018 at 10:20

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.