Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

135
Views
custom function check type of javascipt

I see a function check type in javascript but I don't understand how it works

const typeOf = value => Object.prototype.toString.call(value).slice(8,-1)
typeOf(1) //=> number
typeOf("a") //=> string
typeOf([1]) //=> array
typeOf(()=> {}) //=> function

Please help me explain

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Object.prototype.toString is similar to a big switch statement on the value it's called on. What it does is:

1. If the this value is undefined, return "[object Undefined]".
2. If the this value is null, return "[object Null]".
3. Let O be ! ToObject(this value).
4. Let isArray be ? IsArray(O).
5. If isArray is true, let builtinTag be "Array".
6. Else if O has a [[ParameterMap]] internal slot, let builtinTag be "Arguments".
7. Else if O has a [[Call]] internal method, let builtinTag be "Function".
8. Else if O has an [[ErrorData]] internal slot, let builtinTag be "Error".
9. Else if O has a [[BooleanData]] internal slot, let builtinTag be "Boolean".
10. Else if O has a [[NumberData]] internal slot, let builtinTag be "Number".
11. Else if O has a [[StringData]] internal slot, let builtinTag be "String".
12. Else if O has a [[DateValue]] internal slot, let builtinTag be "Date".
13. Else if O has a [[RegExpMatcher]] internal slot, let builtinTag be "RegExp".
14. Else, let builtinTag be "Object".
15. Let tag be ? Get(O, @@toStringTag).
16. If Type(tag) is not String, set tag to builtinTag.
17. Return the string-concatenation of "[object ", tag, and "]".

It essentially iterates through different types of language objects and will create a string corresponding to the one that it matches. For example, if a number is passed, the string generated is "Number".

This string is then concatenated to produce

[object Number]
        ^^^^^^

where the ^^^ section varies depending on what sort of argument was passed.

Doing .slice(8,-1) is like reversing step 17 - it takes the substring starting from index 8 (right after the space) to the next to last character in the string (inclusive) - so the substring that is extracted is "Number" or "Boolean" or something similar.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!