Skip to content

Returning a “typeof” value in a function?

I’m a total beginner, so it would be very helpful if someone posted the full solution in the comments.

I’m trying to solve the following challenge on edabit:

Create a function that takes an array and returns the types of values (data types) in a new array.

arrayValuesTypes([1, 2, "null", []])
// expected output ➞ ["number", "number", "string", "object"]

arrayValuesTypes(["214", true, false, 2, 2.15, [], null])
// expected output ➞ ["string", "boolean", "boolean", "number", "number", "object", "object"]

arrayValuesTypes([21.1, "float", "array", ["I am array"], null, true, 214])
// expected output ➞ ["number", "string", "string", "object", "object", "boolean", "number"]

So far I have this:

    arr = [1, 2, "null", []]
    
    function arrayValuesTypes(arr) {
        for (let i = 0; i < arr.length; i++) {
         return typeof arr[i]
      }
    }

// output ➞
// 'number'

But when I change “return” to a console.log, it gives me a result closer to what I am looking for. Why is that?

arr = [1, 2, "null", []]

function arrayValuesTypes(arr) {
    for (let i = 0; i < arr.length; i++) {
     console.log(typeof arr[i])
  }
}
// output ➞
// 'number'
// 'number'
// 'string'
// 'object'

Answer

Why is that?

Because return inside a function will return the value and so stop the function, regardless of the for loop.


So use map() to apply it for each item in the array, and then return that array created by map:

function arrayValuesTypes(arr) {
    return arr.map(tmp => typeof tmp);
}

const tests = [
  [1, 2, "null", []],
  ["214", true, false, 2, 2.15, [], null],
  [21.1, "float", "array", ["I am array"], null, true, 214]
];
for (let testIndex in tests) {
  console.log(arrayValuesTypes(tests[testIndex]));
}
["number", "number", "string", "object"] 
["string", "boolean", "boolean", "number", "number", "object", "object"] 
["number", "string", "string", "object", "object", "boolean", "number"]