How to Check Data Types in JavaScript

Dealing with data types is a common task in basically any programming language, be it dynamic or static, weakly typed or strongly typed. JavaScript is no exception. Have you ever needed to check the type of a variable in JavaScript? If so, you probably found out that some checks can be trickier than what you expect. In this article, we are going to see how to check for several data types in JS. Just keep reading!

The typeof keyword is used to differentiate primitive types in JavaScript. It will return one of nine strings: undefined, object (meaning null), boolean, number, bigint, string, symbol, function, or object (meaning any object, including arrays).

Data types and JavaScript

First, let’s briefly discuss the concept of data type, or at least what we mean by data type in this article, in the context of JavaScript. While this concept is historically one of the most debated topics in computer science, our interpretation of data type here is extremely practical and non-academic. In this article, things like objects, arrays (which are objects), functions (also objects), numbers, NaN (which are numbers) and others will be treated as distinct types. So, if you have an academic background or are really strict when it comes to typing systems, relax and don’t take this concept too seriously for now.

Strings

Strings are primitive values and testing them is really straightforward. You just need to use the typeof operator:

function printMessage(message) {
  if (typeof message !== 'string') {
    return;
  }

  // ...
}

Really simple, isn’t it? However, there is a special case where this expression would evaluate to false: if the string is initialized using the String constructor directly.

const message = new String('This will not work');
console.log(typeof message); //=> "object"

Dealing with string objects is definitely uncommon and creating them is not recommended. If you need to create a string, always favor the literal syntax. The String constructor is used under the hood by the engine to create wrapper objects. You don’t need to use them directly. However, if for some reason, you need to ensure that a given value is a string, be it primitive or an object, you can combine the instanceof and typeof operators:

const isString = value => typeof value === 'string' || value instanceof String;

const message1 = 'This is a string primitive'; 
const message2 = new String('This is a string object'); 

console.log(isString(message1)); //=> true
console.log(isString(message2)); //=> true

As one might hoped checking for a string in JavaScript is pretty straight-forward — typeof works exactly as expected, returning "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 like they should when programming!

Null and undefined

In JavaScript, null and _undefined _are often mistaken for each other. In simple words, undefined is the default value for uninitialized variables and null is always explicitly set to a variable.

If you use the typeof operator against both, this is what you get:

console.log(typeof undefined); //=> "undefined"
console.log(typeof null); //=> "object"

Well, we got “undefined” for undefined. That makes sense. However, JavaScript gave us “object” as the type for null. This is not by design. It’s an old bug, dating back to the original language implementation. This bug was never fixed, since a considerable part of current JS codebase (which is huge) would break if typeof null suddenly started evaluating to “null”.

To test for null or undefined, you can just use the strict equality operator (===):

if(a === undefined) {}
if(a === null) {}

If you want to check whether a variable is either null or undefined, you could, of course, combine the two tests above (a === undefined || a === null). However, there’s a more succinct way of doing so, by using the abstract equality operator (==):

if (a == null) {}

The above expression evaluates to true only if a is null or _undefined. _Some people try to find the logic behind this behavior, arguing that since null and _undefined are falsy values, both would be equal if compared with the abstract equality operator. _This does not make sense, since other falsy values like 0 (zero), “” (empty string) or NaN, when compared to null or undefined, will not result in an equality.

console.log(null == ''); //=> false
console.log(null == NaN); //=> false
console.log(null == 0); //=> false
console.log(undefined == ''); //=> false
console.log(undefined == NaN); //=> false
console.log(undefined == 0); //=> false

The fact is that there is no real logic behind this. It only happens because ECMAScript specification states so (just check the second and third points of section 11.9.3).

An undefined value in JavaScript is pretty common — it means a variable name has been reserved, but no value has been assigned to that reference yet. It is not defined yet, so we call it undefined.

The value [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) is a primitive type in JavaScript, and undeclared variables are also considered to be undefined.

Referencing undeclared variables usually results in a ReferenceError, except when using the typeof keyword.

The typeof undefined is the string "undefined" — and undefined is a falsy value that is loosely equal to null but not to other falsy 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

Thus, if typeof says a value is "undefined", then it is a safe bet to assume that value is actually undefined — meaning it was not declared, declared but never assigned a value, or declared and assigned the value of undefined.

Arrays

Arrays are objects. If you try to use the typeof operator against an array, you’ll get “object” as result. The right way to check if a variable is an array is by using the Array.isArray() static method (IE9+):

Array.isArray(someVar);
Array.isArray([11, 22, 33]); //=> true
Array.isArray({}); //=> false

As long as the value in question is not null, typeof returning "object" means that the JavaScript value is a JavaScript object.

One type of object that is built-in to JavaScript is the array, and the typeof of an array is "object": typeof [] === object // true.

ECMAScript 5 introduced an [Array.isArray()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray) method to check for an array, since typeof will not be able to tell arrays from other objects.

The JavaScript prototypes [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) and [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) are two other types of built-in objects where typeof returns “object.” Thus, dates and regular expressions need more differentiation than just using the typeof keyword.

I demonstrates how to check the type of objects and arrays in this code:

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

The verbose JavaScript statement Object.prototype.toString.call() can differentiate between generic objects, arrays, and other objects, because it returns a string that specifies the object type in more detail than typeof.

Function

Functions are also objects. However, differently from arrays, it is possible to check for functions by using the typeof operator:

const f = function() {};
console.log(typeof f === 'function'); //=> true

Functions are easily checked for using the typeof keyword, which works entirely 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"

Objects

To check if a variable is an object, you can compare it against its “boxed” equivalent. If both are equal, it means that your variable is already an object. Please have in mind that this will evaluate to true for any kind of object, including arrays and functions:

const a = {};
console.log(a === Object(a)); //=> true

const b = [];
console.log(b === Object(b)); //=> true

const c = function() {};
console.log(c === Object(c)); //=> true

const d = 123;
console.log(d === Object(d)); //=> false

const e = '';
console.log(e === Object(e)); //=> false

Numbers and Booleans

Numbers and Booleans are really similar to Strings in terms of type testing. Most of the time, you just need to use typeof:

if (typeof a === 'string') {}
if (typeof b === 'boolean') {}

But, in case you need to test for wrapper objects as well and not only primitive values, you could combine typeof and instanceof:

const isBoolean = value => typeof value === 'boolean' || value instanceof Boolean;
const isNumber = value => typeof value === 'number' || value instanceof Number;

Number

Checking for a number in JavaScript works as expected, with typeof returning "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:

Note that this means that checking for NaN requires checking for self-equality because [NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN) is the only value in JavaScript that doesn’t equal 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

Boolean

Checking for Boolean values is easy — they are going to be either true or false, and the typeof a boolean returns "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

Note that JavaScript will coerce any value to true or false by using the Boolean() wrapper function, which puts two exclamation points (the logical NOT — [!](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Description)) in front of the expression. Or it’ll put the statement inside of a conditional, such as an if statement, question mark [?](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean) operator, or loop.

The values that evaluate to false are called the falsy values, and everything else in JavaScript evaluates to true (and thus is a truthy value).

The falsy values in JavaScript are false, 0, 0n, null, undefined, NaN, and the empty string “”; everything else is truthy.

NaN, Infinity and -Infinity

If you use _typeof _against NaN (the acronym for Not a Number), Infinity (JavaScript’s positive infinite number) or -Infinity (negative infinite number), you’ll get “number” as result. I know that it looks weird at first glance, but according to ECMAScript specification, the Number type includes these special numeric values. In order to check for these values, you can use specific builtin functions:

if (isNaN(value)) {} // Checks if value is NaN

if (!isFinite(value)) {} // Checks if value is Infinity or -Infinity

Or, if you need to test if a variable is specifically positive or negative infinity:

if (value === Number.POSITIVE_INFINITY) {} // Checks if value is Infinity

if (value === Number.NEGATIVE_INFINITY) {} // Checks if value is -Infinity

BigInt

BigInt is a built-in object that provides a way to represent whole numbers larger than 253 - 1, which is the largest number JavaScript can reliably represent with the [Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) primitive. BigInt can be used for arbitrarily large integers.” — MDN web docs

Checking for the primitive type BigInt works as expected; typeof for supported browsers will return "bigint":

console.log(typeof 37n) // bigint

Note that BigInt is not yet part of ECMAScript, the official JavaScript standard, even though it is already supported by Chrome (and thus by Node.js), Firefox, and Edge.

Symbol

The primitive data type symbol is a unique identifier, useful for creating keys on objects in JavaScript.

“A symbol value may be used as an identifier for object properties; this is the data type’s only purpose.” — MDN web docs

As one would expect, the typeof Symbol() is indeed "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

Object (meaning null)

For historical reasons, the typeof [null](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null) in JavaScript is "object". This is a bug that is expected to never be fixed in JavaScript.

However, null checking is pretty easy using the strict equality operator (===) to check that the value is indeed null, as in maybeNull===null.

Useful things to know about null

  1. The value null is falsy (evaluates to false in a conditional).
  2. The values null and undefined are only loosely equal to each other.
  3. Neither null nor undefined are equal to other falsy values.

This means that checking for null using the loose equality ([==]) operator will capture both null and undefined values, which can be 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

Often, an undefined value means the same thing as a null value — the absence of a value, so using == is recommended to check for null.

On the other hand, checking for null can be performed easily with the strict equality === operator.

Or one can check by knowing that since the empty object is truthy (evaluates to Boolean true in a conditional), null is the only falsy object.

Conclusion

  • In JavaScript, different data types require distinct forms of checking.
  • Strings, numbers, booleans and functions can be easily checked by using the typeof operator.
  • For null and undefined, you can use a simple comparison with the strict equality operator.
  • Arrays can be recognized by using the Array.isArray static method
  • You can check objects of any kind by comparing them with their boxed value
  • We have special functions such as isNaN and isFinite, for us to check numeric values like NaN, Infinity and -Infinity

#javascript #web-development

What is GEEK

Buddha Community

How to Check Data Types in JavaScript
Siphiwe  Nair

Siphiwe Nair

1620466520

Your Data Architecture: Simple Best Practices for Your Data Strategy

If you accumulate data on which you base your decision-making as an organization, you should probably think about your data architecture and possible best practices.

If you accumulate data on which you base your decision-making as an organization, you most probably need to think about your data architecture and consider possible best practices. Gaining a competitive edge, remaining customer-centric to the greatest extent possible, and streamlining processes to get on-the-button outcomes can all be traced back to an organization’s capacity to build a future-ready data architecture.

In what follows, we offer a short overview of the overarching capabilities of data architecture. These include user-centricity, elasticity, robustness, and the capacity to ensure the seamless flow of data at all times. Added to these are automation enablement, plus security and data governance considerations. These points from our checklist for what we perceive to be an anticipatory analytics ecosystem.

#big data #data science #big data analytics #data analysis #data architecture #data transformation #data platform #data strategy #cloud data platform #data acquisition

Gerhard  Brink

Gerhard Brink

1620629020

Getting Started With Data Lakes

Frameworks for Efficient Enterprise Analytics

The opportunities big data offers also come with very real challenges that many organizations are facing today. Often, it’s finding the most cost-effective, scalable way to store and process boundless volumes of data in multiple formats that come from a growing number of sources. Then organizations need the analytical capabilities and flexibility to turn this data into insights that can meet their specific business objectives.

This Refcard dives into how a data lake helps tackle these challenges at both ends — from its enhanced architecture that’s designed for efficient data ingestion, storage, and management to its advanced analytics functionality and performance flexibility. You’ll also explore key benefits and common use cases.

Introduction

As technology continues to evolve with new data sources, such as IoT sensors and social media churning out large volumes of data, there has never been a better time to discuss the possibilities and challenges of managing such data for varying analytical insights. In this Refcard, we dig deep into how data lakes solve the problem of storing and processing enormous amounts of data. While doing so, we also explore the benefits of data lakes, their use cases, and how they differ from data warehouses (DWHs).


This is a preview of the Getting Started With Data Lakes Refcard. To read the entire Refcard, please download the PDF from the link above.

#big data #data analytics #data analysis #business analytics #data warehouse #data storage #data lake #data lake architecture #data lake governance #data lake management

Arvel  Parker

Arvel Parker

1593156510

Basic Data Types in Python | Python Web Development For Beginners

At the end of 2019, Python is one of the fastest-growing programming languages. More than 10% of developers have opted for Python development.

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Table of Contents  hide

I Mutable objects

II Immutable objects

III Built-in data types in Python

Mutable objects

The Size and declared value and its sequence of the object can able to be modified called mutable objects.

Mutable Data Types are list, dict, set, byte array

Immutable objects

The Size and declared value and its sequence of the object can able to be modified.

Immutable data types are int, float, complex, String, tuples, bytes, and frozen sets.

id() and type() is used to know the Identity and data type of the object

a**=25+**85j

type**(a)**

output**:<class’complex’>**

b**={1:10,2:“Pinky”****}**

id**(b)**

output**:**238989244168

Built-in data types in Python

a**=str(“Hello python world”)****#str**

b**=int(18)****#int**

c**=float(20482.5)****#float**

d**=complex(5+85j)****#complex**

e**=list((“python”,“fast”,“growing”,“in”,2018))****#list**

f**=tuple((“python”,“easy”,“learning”))****#tuple**

g**=range(10)****#range**

h**=dict(name=“Vidu”,age=36)****#dict**

i**=set((“python”,“fast”,“growing”,“in”,2018))****#set**

j**=frozenset((“python”,“fast”,“growing”,“in”,2018))****#frozenset**

k**=bool(18)****#bool**

l**=bytes(8)****#bytes**

m**=bytearray(8)****#bytearray**

n**=memoryview(bytes(18))****#memoryview**

Numbers (int,Float,Complex)

Numbers are stored in numeric Types. when a number is assigned to a variable, Python creates Number objects.

#signed interger

age**=**18

print**(age)**

Output**:**18

Python supports 3 types of numeric data.

int (signed integers like 20, 2, 225, etc.)

float (float is used to store floating-point numbers like 9.8, 3.1444, 89.52, etc.)

complex (complex numbers like 8.94j, 4.0 + 7.3j, etc.)

A complex number contains an ordered pair, i.e., a + ib where a and b denote the real and imaginary parts respectively).

String

The string can be represented as the sequence of characters in the quotation marks. In python, to define strings we can use single, double, or triple quotes.

# String Handling

‘Hello Python’

#single (') Quoted String

“Hello Python”

# Double (") Quoted String

“”“Hello Python”“”

‘’‘Hello Python’‘’

# triple (‘’') (“”") Quoted String

In python, string handling is a straightforward task, and python provides various built-in functions and operators for representing strings.

The operator “+” is used to concatenate strings and “*” is used to repeat the string.

“Hello”+“python”

output**:****‘Hello python’**

"python "*****2

'Output : Python python ’

#python web development #data types in python #list of all python data types #python data types #python datatypes #python types #python variable type

Cyrus  Kreiger

Cyrus Kreiger

1618039260

How Has COVID-19 Impacted Data Science?

The COVID-19 pandemic disrupted supply chains and brought economies around the world to a standstill. In turn, businesses need access to accurate, timely data more than ever before. As a result, the demand for data analytics is skyrocketing as businesses try to navigate an uncertain future. However, the sudden surge in demand comes with its own set of challenges.

Here is how the COVID-19 pandemic is affecting the data industry and how enterprises can prepare for the data challenges to come in 2021 and beyond.

#big data #data #data analysis #data security #data integration #etl #data warehouse #data breach #elt

Macey  Kling

Macey Kling

1597579680

Applications Of Data Science On 3D Imagery Data

CVDC 2020, the Computer Vision conference of the year, is scheduled for 13th and 14th of August to bring together the leading experts on Computer Vision from around the world. Organised by the Association of Data Scientists (ADaSCi), the premier global professional body of data science and machine learning professionals, it is a first-of-its-kind virtual conference on Computer Vision.

The second day of the conference started with quite an informative talk on the current pandemic situation. Speaking of talks, the second session “Application of Data Science Algorithms on 3D Imagery Data” was presented by Ramana M, who is the Principal Data Scientist in Analytics at Cyient Ltd.

Ramana talked about one of the most important assets of organisations, data and how the digital world is moving from using 2D data to 3D data for highly accurate information along with realistic user experiences.

The agenda of the talk included an introduction to 3D data, its applications and case studies, 3D data alignment, 3D data for object detection and two general case studies, which are-

  • Industrial metrology for quality assurance.
  • 3d object detection and its volumetric analysis.

This talk discussed the recent advances in 3D data processing, feature extraction methods, object type detection, object segmentation, and object measurements in different body cross-sections. It also covered the 3D imagery concepts, the various algorithms for faster data processing on the GPU environment, and the application of deep learning techniques for object detection and segmentation.

#developers corner #3d data #3d data alignment #applications of data science on 3d imagery data #computer vision #cvdc 2020 #deep learning techniques for 3d data #mesh data #point cloud data #uav data