JavaScript 101: Data Types

JavaScript 101: Data Types

· 6 min read

Prerequisites for this series

Before going any further with JavaScript 101 you’ll want to make sure you have:

  • A computer (revolutionary, I know)
  • A text editor. VS Code, Vim, Notepad, a typewriter, whatever
  • Node.js installed. Or not. You can use the browser console like a rebel
  • A cup of tea. Coffee is also acceptable. Hot chocolate if you’re feeling fancy
  • At least one existential crisis about why you chose software development
  • A llama. Not strictly required but it helps with morale

Every programming language needs to know what kind of data its working with. By knowing and learning about how a computer language uses data we can write better programs. Or at the very least, fewer bugs. Hopefully.

When we define a variable in Javascript, assigning it gives that variable a “type” as an attribute. Think of it like labelling boxes when you move house. Except you never actually move house, you just keep accumulating boxes. Forever.

As we write bigger, more complex applications it becomes essential that we know how to use these different “types” of data a variable can be.

What’s a “type”?

A “type” or “data type” is defined as “an attribute of data which tells the compiler or interpreter how the programmer intends to use the data”. Put simply its a way of telling a compiler what type of data we want to use. Its like ordering at a restaurant. You dont just say “food please”, you specify what you want. Unless you’re at a buffet, in which case, go wild.

Primitive Types

A “primitive data type” just means the data types a language can recognise out of the box, without any extra steps. Most languages will come with their own primitives, and Javascript uses the following 7 primitive data types:

string; // words and sentences eg. "foo"
number; // a floating point representation of a numeric value eg. 123
bigint; // numbers too large to be represented by a number e.g 9007199254740991
boolean; // true or false (don't confuse this with the "Boolean object" type)
undefined; // a value automatically assigned to variables that have just been declared e.g 'const x;' will resolve to 'undefined'
symbol; // a Symbol is created by invoking the Symbol function and produces an anonymous, unique value, can be used as an object property. e.g let Sym1 = Symbol("Sym")
null; // a null value is supposed to represent nonexistent or invalid values, in javascript all Objects are derived from null meaning js will return 'object' for any 'typeof(null)' comparisons.

To check what a javascript variable is, we can use the typeof operator. Try logging the ‘change me’ string below with some of the different values above in a react component and see what gets logged out:

const string = "change me";
render(typeof string);

Primitive types are also immutable which means they cannot be changed. When a string is manipulated, for example, what is returned is a new type. They’re basically the introverts of the data type world. They dont change for anyone.

Non-primitive types

A “Non-primitive” data type is a data type derived from primitive data types. I like to think of non primitive data types as a data type that can contain primitive data types, though of course this is an over simplification. Think of it like a lunchbox. The lunchbox itself isnt food, but it contains food. And sometimes a rogue biscuit you forgot about from three weeks ago.

The three main non-primitive types to remember in Javascript are arrays, objects and functions. In Javascript it’s said that everything is an object, though it’s probably more accurate to say everything that isn’t a primitive, is an object.

If everything is an object then, what about Arrays and Functions? (and undefined?)

Well, what exactly is an object?

An object is defined by Mozilla as a standalone entity, with properties and type. An object can contain literally anything, including other objects, arrays and functions. Objects are given a type and is made up of properties.

Lets define an object in Javascript using a very cliche example:

const car = {};

car.colour = "red"; // a "string" property set to "red"

car.wheels = [
  {
    colour: "black",
    size: 21,
  },
  {
    colour: "black",
    size: 21,
  },
  {
    colour: "black",
    size: 21,
  },
  {
    colour: "black",
    size: 21,
  },
]; // an Array property, containing object properties, which contain string and number properties

car.start = () => {
  console.log("I'm a function");
}; // A function property

console.log(typeof car);
console.log(car);

//Should render something similar to: // [object Object] { colour: "red" start: () => { console.log("I'm a function"); } wheels: (4) [{…}, {…}, {…}, {…}] }

In the terminal, functions will be rendered either as empty objects or as a literal string unless the function is invoked (called) i.e car.start() instead of car.start.

Arrays and Functions then, are just special objects in Javascript. Beware though, you do get some unexpected behaviours when using the typeof operator:

typeof car; // object
typeof car.colours; // string
typeof car.wheels; // object
typeof car.start; // function

Javascript seems to catch some flack for its seemingly unpredictable nature of how it defines its types. I think as long as the developer is aware of certain gotchas it doesnt really pose a problem, and if you throw Typescript into the mix then most confusion around types can all but disappear.

Using the example above lets throw some other primitive and Non-primitive types into the mix, namely null and undefined, oh, and NaN (Not A Number):

typeof null; // object
typeof undefined; // undefined
typeof NaN; // number

..wait, wat?

Confused math lady

Null and undefined types

So, null can easily be explained, it is just a special primitive type Javascript uses to represent a missing object. Yes, it’s misleading, but just bear it in mind. Like that one friend who says they’re “fine” but clearly isnt.

FYI, it’s fairly bad practice to use variable === null comparisons everywhere, nevertheless it happens. null is best thought of when you know something should be empty.

undefined though is its own gnarliness. undefined is what Javascript throws when it’s not been told about a property. I see this most often when either a property has been misspelt or there is an order of execution issue.

const obj = {}

obj.property = "a property"

console.log(obj.propery) // undefined (doh) console.log(obj.property) // a property

When is a number, Not A Number?

typeof(NaN) // number

The NaN type returns “number”, why is this?

In Javascript, NaN is still a numeric type. When NaN is thrown it simply means the value cannot be represented within the limitations of the language. It means it’s still probably a number, just not one Javascript can deal with right now. Like trying to count how many tabs you have open in Chrome. Its technically a number, but nobody really wants to know.

Make note that you cannot compare two NaN values accurately, as they both are still likely numeric values. To check if a value is a number it’s best to use isNaN(NaN).

Related Posts

Comments