Best Website-BuildersBest Website-Builders
    What's Hot

    5 Best Password Managers (2022): Features, Pricing, and Tips

    March 27, 2023

    Harry's power play: Why has the prince turned up at court?

    March 27, 2023

    Casualties reported in Tennessee school shooting

    March 27, 2023
    Facebook Twitter Instagram
    Facebook Twitter Instagram
    Best Website-BuildersBest Website-Builders
    • Home
    • CSS

      The 2023 Nagaland State Budget presents state matching shares for the CSS for the first time.

      March 27, 2023

      Annual Development Outlay for 2023-24 fixed at Rs 82,000 lakh | MorungExpress

      March 27, 2023

      Web Scraping with Python and Selenium | Daniel Ellis Research | | March 2023

      March 27, 2023

      Gunboat Association, Partners Host Environmental Education Day on April 1 — News News

      March 27, 2023

      6 best e-books about technology and the people behind it

      March 25, 2023
    • Joomla

      An In-Depth Study of the Market Status, Trends and Top Players of the Open Source Content Management Systems Market

      March 27, 2023

      Save Thousands On Web Hosting With iBrave, Now Only $86

      March 23, 2023

      In Vitro Transcription Services Market Analysis, Research Study with Shanghai Zhishuo Biotechnology Co., Yunzhou Biotechnology Co.

      March 23, 2023

      Current state of UK content management systems

      March 23, 2023

      Reseller Hosting Business: Important Q&A

      March 21, 2023
    • PHP

      TikTok’s WAGs want to show what their lives are really like

      March 27, 2023

      Olivia Wilde slammed leaked documents about Jason Sudeikis’ custody battle

      March 27, 2023

      March 27, 2023 — Biggest news story of the day

      March 27, 2023

      Former U.S. Marshal Convicted of ‘Rape Fantasy’ Conspiracy Against Former American

      March 26, 2023

      Explosion at Palmer chocolate factory kills 4

      March 26, 2023
    • UX

      Experience Optimization Product Acronym Translation

      March 27, 2023

      Microsoft rebuilds Teams from the ground up, promising 2x faster performance

      March 27, 2023

      Uptime.com offers synthetic transaction monitoring to track performance, user experience and prevent revenue loss

      March 27, 2023

      AAZZUR Partners with Financial Services Data Platform Sikoia

      March 27, 2023

      y00ts forms a link from Solana to Polygon for easy user experience

      March 27, 2023
    • Web Builders
      1. Web Design
      2. View All

      What Comes First in Website Development — Design or Copy?

      February 2, 2023

      Modern Campus Honors Best Higher Education Websites of 2022

      February 2, 2023

      Premier SEO Consultant in Las Vegas, Nevada with Unparalleled Customer Service

      February 2, 2023

      Can Religious Freedom Be Saved? This group is racing the clock to teach America’s first freedom

      February 2, 2023

      How i Create New Google Account

      February 7, 2023

      CWT powers tools for meeting and event planners

      January 31, 2023

      Best Website Builder – Website Builders

      January 24, 2023

      Is There A Market For Rap-Themed Slot Games? – Rap Review

      January 19, 2023
    • WordPress

      Xbox Series X receives a visual update, but it’s not what we’ve been waiting for

      March 27, 2023

      Procter & Gamble is the latest large-scale GoAnywhere zero-day victim

      March 27, 2023

      China to pass 1 billion 5G connections within 2 years

      March 27, 2023

      Beware — These IRS Tax Returns Could Actually Be Just Malware

      March 27, 2023

      Part of Twitter’s source code appears to have been leaked by a disgruntled programmer

      March 27, 2023
    • Realtoz
      • Our Other Sites
    • More News
    Best Website-BuildersBest Website-Builders
    Home » JavaScript Typeof for data types: arrays, booleans, etc.
    JavaScript

    JavaScript Typeof for data types: arrays, booleans, etc.

    websitebuildersnowBy websitebuildersnowJanuary 20, 2023No Comments11 Mins Read
    Facebook Twitter LinkedIn Telegram Pinterest Tumblr Reddit WhatsApp Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    of typeof statement is helpful JavaScript for data validation and type checking, but there are some strange features to be aware of.

    I have two instances. typeof Return value "object" In an unexpected way, this changes the type checking a bit.

    What is the Typeof Statement in JavaScript?

    Typeof A statement used in JavaScript to check type variables in code. It can return one of JavaScript’s eight data types, and is especially useful for returning most of JavaScript’s primitive types. undefined, string and number.

    both typeof null and typeof of arrangement return "object" in a potentially misleading manner, null is a primitive type (not an object), and an array is a special built-in type of object in JavaScript.

    This article explores all possible outcomes. typeof in JavaScript.

    data type

    There is only 8 data types (7 primitives and objects) In JavaScript, typeof It actually returns one of the following nine options:

    1. undefined
    2. object (meaning null)
    3. boolean
    4. number
    5. bigint
    6. string
    7. symbol
    8. function
    9. object (meaning any object, including arrays)

    These correspond to JavaScript data types. typeof null again "object" Due to longstanding bugs.

    It then describes when to expect each response from. typeof In detail.

    JavaScript details: What are JavaScript design patterns?

    undefined

    Ann undefined JavaScript values ​​are fairly common. This means that the variable name is reserved, but that reference has not yet been assigned a value. We call it undefined because it hasn’t been defined yet.

    value undefined is a primitive type in JavaScript and undeclared variables are also considered undefined.

    Referencing an undeclared variable usually raises a ReferenceError. typeof keyword.

    of typeof undefined is a string "undefined" – and undefined is a false value roughly equal to null But not for other false values.

    // The value undefined is loosely equals to null but not other falsy values:
    console.log(undefined === undefined) // true
    console.log(undefined === null) // false
    console.log(undefined == null) // true
    console.log(Boolean(undefined)) // false
    console.log(undefined == false) // false
    
    // The typeof keyword returns "undefined" for the value undefined:
    console.log(typeof undefined) // undefined
    
    // A declared variable that has not been assigned a value is undefined by default:
    let undefinedVariable
    console.log(undefinedVariable) // undefined
    console.log(typeof undefinedVariable) // undefined
    
    // The typeof an undeclared variable is undefined, making it a safe way to check if a variable has been declared:
    console.log(typeof undeclaredVariable)
    
    // Referencing an undeclared variable without typeof will throw a ReferenceError:
    try { undeclaredVariable } catch(e) { console.log(e) } // ReferenceError: undeclaredVariable is not defined

    If typeof value is "undefined"the value is actually undefinedmeans undeclared, declared but not assigned a value, or declared and not assigned a value undefined.

    null object

    For historical reasons, typeofnull in JavaScript "object"This is a bug that is not expected to be fixed in JavaScript.

    In other words, you can’t do it with a null check. typeof.

    However, the null check uses the strict equality operator (===) value is actually null,like maybeNull===null.

    Useful things to know about Null

    1. value null is false (evaluates to false in the condition).
    2. its worth null and undefined They are only roughly equal to each other.
    3. do not have null or undefined Equal to any other falsy value.

    This means checking for null using a loose equality (==) operator captures both null and undefined values. This is useful.

    console.log(null) // null
    console.log(typeof null) // "object"
    
    console.log(null === null) // true
    console.log(null === undefined) // false
    console.log(null == undefined) // true
    console.log(null == false) // false
    console.log(Boolean(null)) // false
    
    // Alternatively, null is the only falsy object
    console.log(!null && typeof null === "object") // true
    isNull = (value) => !value && typeof value === "object"
    console.log(isNull(null)) // true

    In many cases, undefined value means the same as a null value – absence of value – hence use == It is recommended to check for null.

    Checking for null, on the other hand, is easy to do with strict equality. === operator.

    Or you can check it by knowing empty object is true (evaluates to a boolean true conditional), null The only fake.

    boolean value

    Checking booleans is easy.they will be either true again falseand the typeof a boolean value Return value "boolean":

    console.log(typeof true) // boolean
    console.log(typeof false) // boolean
    
    // The Boolean() wrapper will convert truthy and falsy values:
    console.log(typeof Boolean(37)) // boolean
    console.log(typeof Boolean(0)) // boolean
    
    // Two exclamation points !! (the logical NOT) operator are equivalent to Boolean()
    console.log(typeof !!(37)) === // boolean
    console.log(typeof !!(0)) === // boolean
    
    // Conditionals will coerce values to boolean in the same way:
    37 ? console.log("truthy") : console.log("falsy") // truthy
    0 ? console.log("truthy") : console.log("falsy") // falsy

    JavaScript accepts arbitrary values ​​as true again false using Boolean() wrapper functiontwo exclamation points ( logical negation — !) before the expression. Or put the statement inside a conditional such as an if statement. question mark ? operatoror a loop.

    Evaluated value false These are called falsy values, and all other values ​​in JavaScript are evaluated as follows: true which is the true value.

    Falsy values ​​in JavaScript are: false, 0, 0n, null, undefined, NaN and an empty string “”Everything else is true.

    number

    Checking numbers in JavaScript works as expected. typeof return "number":

    console.log(typeof 37) // "number"
    console.log(typeof 2.71828) // "number"
    console.log(typeof Math.E) // "number"
    console.log(typeof Infinity) // "number"
    
    // The typeof NaN is "number" even though NaN means "Not-A-Number":
    console.log(typeof NaN) // "number"
    
    // Calling Number explicitly is one way to parse a number:
    console.log(typeof Number(`1`)) // "number"
    
    // The parseInt and parseFloat functions are other ways to parse:
    console.log(typeof parseInt(`100`)) // "number"
    console.log(typeof parseFloat(`100.01`)) // "number" 
    
    // Parse failures lead to NaN, and NaN poisons other math:
    console.log(typeof (2 * parseInt(`invalid`))) // "number"

    this is, NaN Because you need to check for self-equality NaN The only value in JavaScript that is not equal to itself.

    const mightBeNaN = NaN // NaN means "Not-a-Number"
    
    // Anything compares false when compared to NaN:
    console.log(37 === NaN) // false
    console.log(mightBeNaN === NaN) // false
    
    // NaN is the only value that does not equal itself:
    console.log(mightBeNaN !== mightBeNaN) // true
    
    // Creating an invalid Date results in the value NaN:
    console.log(new Date(`invalid`) !== new Date(`invalid`)) // true
    
    // For improved code readability, some developers prefer Number.isNan():
    console.log(Number.isNan(mightBeNaN)) // true

    BigInt

    Checking primitive types BigInt works as expected. typeof For supported browsers it will return "bigint":

    console.log(typeof 37n) // bigint

    “BigInt is a built-in object that provides a way to represent integers greater than 253 – 1. This is because JavaScript uses number Primeval. BigInt can be used for arbitrarily large integers. MDN web docs.

    Officially, BigInt Added to modern JavaScript as part of ES11 (ECMAScript 2020). Supported By Chrome, and thus by Node.js, Firefox, and Edge.

    string

    As you can imagine, checking strings in JavaScript is very easy. typeof works as expected and returns "string":

    console.log(typeof '37') // string
    console.log(typeof "37") // string
    console.log(typeof `37`) // string
    
    // Note that typeof always returns a string:
    console.log(typeof (typeof 37)) // string
    
    // The String() wrapper function converts anything into a string:
    console.log(String(37))

    It sure is nice when things work as they should programming.

    symbol

    primitive data types symbol A unique identifier, useful for creating keys for objects in JavaScript.

    “Symbol values ​​can be used as identifiers for object properties. That’s the sole purpose of data types. MDN web docs.

    As I expected, type Symbol() surely "symbol":

    console.log(typeof Symbol()) // symbol
    console.log(typeof Symbol(37)) // symbol
    console.log(typeof Symbol.iterator) // symbol
    
    const symbolUno = Symbol()
    const symbolDos = Symbol(37)
    const symbolTres = Symbol("37")
    
    console.log(typeof symbolUno) // symbol
    console.log(String(symbolTres)) // Symbol(37)
    
    //  Every symbol value returned from Symbol() is unique:
    console.log(Symbol() === Symbol()) // false
    console.log(Symbol(37) === Symbol(37)) // false
    console.log(Symbol("37") === Symbol("37")) // false

    function

    The function is typeof A keyword that works perfectly as expected by returning "function":

    console.log(typeof function myFunction() {}) // function
    console.log(typeof class myClass {}) // function
    console.log(typeof (() => {})) // function
    
    // This includes built-in functions, for example Number.isNaN():
    console.log(typeof Number.isNaN) // "function"
    
    // But not properties, of course:
    console.log(typeof "".length) // "number"
    
    // And calling a function will check the typeof the return value:
    console.log(typeof Number.isNaN()) // "boolean"
    console.log(typeof Number.isNaN(37)) // "boolean"

    object (meaning object or array)

    Unless the value in question is null typeof return "object" means that the JavaScript value is a JavaScript object.

    One type of object built into JavaScript is an array. typeof array of "object": typeof [] === `object` // true.

    Introduced in ECMAScript 5 Array.isArray() how to check arraysince typeof Arrays cannot be distinguished from other objects.

    JavaScript prototype Date and RegExp are two other types of built-in objects. typeof Returns an “object”. So for dates and regular expressions, typeof keyword.

    Here’s how to check the type of objects and arrays:

    const helloWorldObject = { hello: "world" }
    console.log(typeof helloWorldObject) // 'object'
    // use Array.isArray or Object.prototype.toString.call
    // to differentiate regular objects from arrays
    const fibonacciArray = [1, 1, 2, 3, 5, 8]
    console.log(typeof fibonacciArray) // 'object'
    console.log(Array.isArray(helloWorldObject)) // false
    console.log(Array.isArray(fibonacciArray)) // true
    
    // There is another helper function, though it is a bit long:
    console.log(Object.prototype.toString.call(helloWorldObject)) // [object Object]
    console.log(Object.prototype.toString.call(fibonacciArray)) // [object Array]
    
    // Regular expression have their own native object, RegExp
    const myRegExp = /search/
    console.log(typeof myRegExp) // 'object'
    console.log(myRegExp instanceof RegExp) // true
    console.log(Object.prototype.toString.call(myRegExp)) // [object RegExp]
    
    // The Date native object is built-in to JavaScript
    const emptyDate = new Date()
    const invalidDate = new Date("fail")
    console.log(typeof emptyDate) // 'object'
    console.log(typeof invalidDate) // 'object'
    // Checking for a date is a little trickier
    console.log(emptyDate instanceof Date)
    console.log(invalidDate instanceof Date)
    console.log(Object.prototype.toString.call(invalidDate)) // [object Date]
    // Reliable date checking requires a NaN check by checking for NaN:
    console.log(invalidDate instanceof Date && !Number.isNaN(invalidDate.valueOf())) // true

    Detailed JavaScript statements Object.prototype.toString.call() Returns a string that further specifies the object type, so you can distinguish between generic objects, arrays, and other objects. typeof.

    Similarly, the helper method Array.isArray() or keyword instanceof They can be used to check arrays or objects of any type, respectively.

    Explanation of Typeof and Object wrapper

    of object wrapper For booleans it breaks numbers and strings typeof and as a result "object" Excluding that "boolean", "number"again "string".

    // "The following are confusing, dangerous, and wasteful. Avoid them." -MDN Docs
    typeof new Boolean(false) === 'object'; // true
    typeof new Number(37) === 'object'; // true 
    typeof new String(`Hello World!`) === 'object'; // true

    Why do these object wrappers exist if they don’t need to be called explicitly?

    Basically you call a string property like "".length JavaScript creates a wrapper object and interprets your code as follows:

    "".length === String("").length // true

    There is no need to create an explicit wrapper object as this is done automatically. typeofas shown above.

    Why not use a wrapper object

    Similarly, the wrapper object is == and === JavaScript equality operator.

    And what actually changes the behavior is new Keywords are used in object wrapper calls, as shown in the following example.

    const primitiveString = `Hello world!` // primitive type string
    const wrappedString = new String(`Hello world!`) // wrapper object
    
    console.log(typeof primitiveString) // "string"
    console.log(typeof wrappedString) // "object"
    
    console.log(primitiveString == wrappedString)  // true
    console.log(primitiveString === wrappedString) // false
    
    const almostWrappedString = String(`Hello world!`) // wrapper called without new
    console.log(typeof almostWrappedString) // "string"
    console.log(primitiveString === almostWrappedString) // true

    Generally speaking, string, boolean, and number wrappers are called automatically and should not be called by JavaScript developers.

    JavaScript Typeof and Host Objects

    The host object is implementation dependent. That is, host objects are provided by the local runtime environment.

    In other words, host objects are special objects beyond the standard built-in and native objects that JavaScript provides.

    for example, window object The node.js environment provides other host objects, but provided by the browser environment.

    this is, typeof Keywords are also implementation dependent, at least for host objects.

    That said, modern implementations probably refer to “objects” as typeof host object. for example:

    typeof window // "object"

    Are static types the future of JavaScript?

    JavaScript is a dynamically typed language, typeof Some developers prefer automatic or static type checking using languages ​​like TypeScript or static type checkers like Flow.

    Using TypeScript or Flow certainly has some advantages and can prevent bugs, but it comes at the cost of learning and implementing another tool.

    While convenient, using either TypeScript or Flow adds a whole new layer of complexity to JavaScript programming.

    For vanilla JavaScript, mastering typeof That’s all you need to check for data types like champ.

    Introduction to JavaScript’s typeof operator. | | Video: Java Brain

    JavaScript details: Creating an Npm-only build step for JavaScript — the easy way

    Benefits of Typeof in JavaScript

    keyword typeof is useful for type checking in JavaScript, but has some caveats related to historical bugs.

    type checking typeof Especially useful for most primitive types in JavaScript. undefined, string and number.

    on the other hand, Array, Date and Regular Expressions Native objects that are not distinguished from each other by typeofthey will all be back "object" – that’s right nullunexpectedly in a well-known bug.

    in short, typeof An imperfect but powerful tool for checking value types.



    Source link

    Share this:

    • Tweet
    • Email
    • Pocket
    • Mastodon
    • WhatsApp
    • Telegram
    • Share on Tumblr
    • Print
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Telegram Email
    Previous ArticleChris Eubank Jr on why ‘only ever being Eubank’s son scared me’
    Next Article Beth Matthews' raw honesty saved lives, say mental health experts
    websitebuildersnow
    • Website

    Related Posts

    No More JavaScript: How Microsoft Blazor Uses WebAssembly

    March 27, 2023

    What’s New in TypeScript 5.0

    March 27, 2023

    How to Add a Property to Each Object in an Array of Objects Using JavaScript | Jon O’Young | | Mar 2023

    March 25, 2023
    Add A Comment

    Leave a Reply Cancel reply

    Top Posts

    Subscribe to Updates

    Get the latest sports news from SportsSite about soccer, football and tennis.

    Advertisement
    Demo

    This website provides information about CSS and other things. Keep Supporting Us With the Latest News and we Will Provide the Best Of Our To Makes You Updated All Around The World News. Keep Sporting US.

    Facebook Twitter Instagram Pinterest YouTube
    Top Insights

    5 Best Password Managers (2022): Features, Pricing, and Tips

    March 27, 2023

    Harry's power play: Why has the prince turned up at court?

    March 27, 2023

    Casualties reported in Tennessee school shooting

    March 27, 2023
    Get Informed

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    © 2023 bestwebsite-builders. Designed by bestwebsite-builders.
    • Home
    • About us
    • Contact us
    • DMCA
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.