How to compare a variable by its type? For example, if this number is one, and if it is a string, then another, if the object, then the third?

    1 answer 1

    Use the typeof and instanceof operators (their differences are written here ):

    var data; data = ...; if (typeof data === 'string') { // строка } if (typeof data === 'number') { // число } if (data instanceof Array) { // массив } if (data instanceof Object) { // объект / словарь } 
    • With an array is not so simple. Need to use Array.isArray . - user207618
    • @Other, in most cases, instanceof will do the same? - Qwertiy
    • There is a nuance with null. - Qwertiy
    • In most cases, you can generally score on the nuances . But is it worth it? - user207618