ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software

javascript typeof operator

Updated on November 2, 2007

JavaScript typeof operator tells you what type of data you're dealing with:

var BooleanValue = true; 

var NumericalValue = 354;

var StringValue = "This is a String";

alert(typeof BooleanValue) // displays "boolean"

alert(typeof NumericalValue) // displays "number"

alert(typeof StringValue) // displays "string"

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      3 years ago

      ccsdssd

    • profile image

      Johne288 4 years ago

      You are my inspiration, I possess few web logs and rarely run out from to brand. dbebkacdbgea

    • profile image

      Gaksorast 5 years ago

      Прелестный блог, делюсь с Вами, наслаждайтесь, изучайте, зарабатывайте, http://ochupella.ru/

    • profile image

      Wisen Technologies 5 years ago

      The typeof operator returns “object” for a value that is null. This was actually an error in the original JavaScript implementation that was then copied in ECMAScript. Today, it is rationalized that null is considered a placeholder for an object, even though, technically, it is a primitive value.

      Gym.Prathap

      http://wisentechnologies.com/it-courses/html-css-j...

    • profile image

      Dave Stewart 6 years ago

      Just had to join in.

      @Zoroastro There are times when you can say "this is" in coding, but using the typeof operator is not one of them. If you had a point, it got well and truly lost in your incoherent, misleading, opinionated and fairly inaccurate rant.

      I won't bother to knock down each of your arguments as I'm busy, my role here is to highlight to others who may think you know what you're talking about, not to get sucked in.

    • profile image

      David 6 years ago

      @Zoroastro: That's outrageous. What about a javascript model setter that needs to check for associated user-defined hooks (functions) that may or may not be present for a given attribute? You need to determine the type to avoid executing the function in cases where it is absent.

    • profile image

      Tim 7 years ago

      @Zoroastro Or... here's a thought, use the === operator to check value AND type.

    • profile image

      Neo Invoice 7 years ago

      It is very useful when you don't have 100% control of the environment. Done.

    • profile image

      Chris 7 years ago

      Zoroastro has demonstrated fairly well that he doesn't understand much about JavaScript at all. For instance, he says that EVERY object in JavaScript is typeof "object". That is simply not true. What about a function?

      var func = Function();

      "object" == typeof func; // false

      func instanceof Object; // true

      Since I have effectively knocked down the central argument of all that gobbledygook, that every JS object is type "object", I'll stop there.

      typeof should be avoided for other reasons: http://goo.gl/ackpQ

    • profile image

      Alexander 7 years ago

      /* Formatted on 2011/01/03 16:17 (Formatter Plus v4.8.7) */

      SELECT a.matter_ref_number, a.reminder_activity, a.reminder_date,

      a.reminder_to, b.claim_type_id,

      getparamvalue('CLAIM_TYPE_MASTER',

      'CLAIM_NAME',

      'CLAIM_TYPE_ID',

      b.claim_type_id

      ) AS CLAIM_Name

      FROM ACTIVITY_MASTER a, ENQUIRY_MASTER b

      WHERE a.matter_ref_number = b.matter_ref_number

    • profile image

      shortsman 7 years ago

      Just wanted to add my 2 cents:

      THIS SITE IS AN EPIC FAIL.

    • profile image

      pantsman 7 years ago

      well hello..

    • profile image

      nisar 7 years ago

      hi..

    • profile image

      Daniel Earwicker 8 years ago

      @Zoroastro

      "javascript isn't OOP" - true. It's way better than OOP!

      Also you're confusing OOP and static type safety. Smalltalk is a hugely influential OO language, but like JS it is dynamically-typed: a variable may store anything.

      The need to check the type of an object is not automatically a sign of poor design. Yes, often the operation to be performed depends on the type of a single object, and so by calling a method on the object we can avoid an explicit "type-switch": just call the method and let the object decide how to implement it.

      But it is also often true that the operation to be performed depends on the types of two or more objects. Traditional OO (as exemplified by Java and C++) has no answer to this problem. e.g. a "window" receives an "event". The operation to perform depends on both the type of the window and the type of the event. If you make a "handleEvent" method on the window, you need a type-switch to examine the type of event.

      OO is not quite the ultimate solution to all programming problems that you may have been told! :)

    • profile image

      Jim 8 years ago

      Daniel completely agree, surely typeof is essential when relying on parameters passed in by an unknown user.

    • profile image

      Daniel Cotter 8 years ago

      Zoroastro -- What about the case in which you want to know whether a passed-in parameter is of the right type for the code that follows? This especially applies in the case of something like a jQuery plugin, where oftentimes the end-user of the plugin can pass in custom (and quite possibly wrong) settings.

    • profile image

      David 8 years ago

      since this is the #1 google result for javascript typeof, it should probably include a reasonable list of javascript types, such as "object", "undefined", "function"

      men you are honest!! this is because you are rated #1 ;)

    • profile image

      fredmc 8 years ago

      Zoroastro, you said "A variable should NEVER change it's type... if it was a string at the beginning of the program, it should be a string at the end of the program."

      How about when I want to increment a counter on a page? I read the existing value with innerHTML or get the value of a form field. Either gives me a string. If I don't change the type of the variable to a number, I concatenate, rather than add.

    • profile image

      Zoroastro 8 years ago

      typeof is almost never needed in good OOP. The times it is "needed" can usually be avoided by using a simple flag, and the remaining times almost always are a result of poor encapsulation and piss-poor programming ability.

      The thing is, javascript isn't OOP, it's actually not OBP as some people believe. Javascript is a type insensitive language that has few rules on object malleability. That means that you can change almost any aspect of any "new Object()" anywhere in the program. You can do OOP with this, but the type insensitivity upon which it relies means that any object will always be 'type' Object.

      Now, recall that I said that good OOP tries to avoid the need of typeof? Well, I didn't explain that the reason people use typeof is because they want to know what their OBJECT's type is.

      Now wait a min, Javascript's objects are all type Object! So you're saying you don't know the TYPE of a VARIABLE that YOU defined (unlike objects, which are defined by the program).

      Stop using overloaded functions. Javascript does NOT support function overloading, Javascript ONLY supports "argument insensitive" functions (meaning you can leave some arguments off and check if they are undefined (NOT that they are false *:| ("0" == false) && (0 == false) && ([0] == false)

      Three very good reasons to use (0 == undefined) (for arguments sake, null is the value that undefined holds... so either or).

      Javascript has type insensitive functions so you can pass OBJECTS that have the same INTERFACE without hassle, not so you can avoid writing an additional function.

      Stop redefining namespaces (variables)! A variable should NEVER change it's type... if it was a string at the beginning of the program, it should be a string at the end of the program.

      The type insensitivity of variables exists mostly so functions can pass fail flags around (such as returning a -1) instead of returning null.

      Note, however, that even if you pass a fail flag to a variable that should hold a string, you are not changing the variables type (other than from being undefined). By checking if the fail flag is there before using it as a string, you inherently confirm that the object is, indeed, a string.

    • profile image

      Daniel Earwicker 8 years ago

      Google: FAIL.

    • profile image

      talhah 8 years ago

      i agree with cory, such a waste of time

    • profile image

      Robin 8 years ago

      The following site gives more details of the operator of "typeof":

      https://developer.mozilla.org/en/Core_JavaScript_1...

    • profile image

      Wingi 8 years ago

      Please read the 4 articles of Matthias Reuter finding and converting objects in javascript instead the "try and error method"!!!

    • profile image

      Cory Marsh 8 years ago

      since this is the #1 google result for javascript typeof, it should probably include a reasonable list of javascript types, such as "object", "undefined", "function"

      <a href="https://developer.mozilla.org/en/Core_JavaScript_1... Javascript Doc</a>

    • profile image

      mirko 9 years ago

      a fungeje to aj na objekty?

    • profile image

      i9 9 years ago

      o

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)