Search code examples
javascriptvariablestypes

Is it possible to change a variable from String to Number in Javascript?


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?


Solution

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