Data types output, incorrect format

Hello,

I am writing a function which returns type and value in the format ‘number=2’ (for example). It works fine for some data types, but when it comes to strings and arrays, the quote marks (for strings) and the square brackets (for arrays) are missing (I need them to be shown).

Does someone know how I might be able to include these in the output please?

function typing(param) {
  let varType = typeof param;

  return(`${varType}=${param}`);
 
}

If it is a type of string, then you can have a condition to check for that and then return a template literal that has quotes around the param

if (varType === "string") {
    return `${varType}="${param}"`;
  }

Arrays are a type of object in JavaScript.

You can have a condition to check for type of object, then you can check if it is an array or object literal.

You can use the isArray method for that

If it is an array, then you can return a template literal with the square brackets around the param

If it is an object literal, then you will need to add JSON.stringify around the param otherwise you will get this result

Screenshot 2024-03-16 at 10.58.34 AM

Lastly, you will need to account for the typof null.

Right now, your code will show this

"object=null"

reason being is because this is a historical bug in javascript

You can add a condition that says if the type is null, then return some other string acknowledging that

if (param === null) {
    return "Null has a type of object because this is a historical bug in JavaScript";
  }

hope that helps

you can specify conditions for your parameters like so,

function typing(param) {
    let varType = typeof param;
    if(varType=="string"){
         param = `"${param}"`;
    }
    else if(varType=="object"){
        // if you want to specify that array parameter shows up as array type, you can
        // use this line written next to the sentence or ignore it
         varType = "array";
        //  console.log(typeof Array); // returns object type
         param = `[${param}]`
    }
    return(`${varType}=${param}`);
  }

great, many thanks for your help

Fantastic. I got the solution using the info in your answer. Many thanks for the help.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.