JAvascript

Data types in Javascript

Data types

Variables in JavaScript can contain any data type at any moment. A variable that was initialised with a string can later hold a number or a boolean variable because JavaScript is a "dynamically typed" language:

let country = "Zimbabwe";
country = 263;
console.log(country); // 263

These are the basic data types in JavaScript:

  • number
  • string
  • boolean
  • null
  • undefined
  • object
  • symbol

number

The number type is subdivided into four types of numeric literal formats: decimal, binary, octal, and hexadecimal.

Numbers are stored using the double-precision 64-bit format which limits the value of a number between -(253 -1) and (253 -1). Unlike in other common programming languages such as Java, there is no specific type for integers. In JavaScript, integers are stored as "doubles".

The number type has three other types of values: +Infinity, -Infinity, and NaN (which ironically stands for "Not a Number").

let dayHours = 24; // 24 is an integer literal but still a double (collectively known as a decimal type)
let  redColor  =  0xff0000; //a hexadecimal type (starts with 0x)
let  dataMask  =  0o0023; // an octal type (starts with 0o)
let maxVelocity =  23.05; //decimal type
const AVOGRADRO = 6.02e23; //exponential type (6.02 x 10 to the power 23)

Whatever literal format you represent your value in (decimal, hexadecimal, exponential, etc.) they are all stored in double format.

Warning about using leading zeroes in numeric literals.

Example 1

console.log(0888); // prints 888
console.log(0777); // prints 511

Octal numbers are numbers in base 8. Mathematically when we are in base 8, 7 is the largest allowed digit. One of the quirks of JavaScript is that if a literal has a leading 0 and the next digits are all smaller than 8, the literal is interpreted as an octal number. This means 0777 is treated as an octal number which is equivalent its decimal value of 511. I say this is a quirk because 0888 should produce an error about digits greater than 7 not being allowed in base 8. Instead, JavaScript assume that your literal in now in decimal (base 10). That’s how 0777 become 511, while 0888 becomes 888.

Now let us see how the script behaves in strict mode:

"use strict"

console.log(0888); 
console.log(0777); // SyntaxError: Octal literals are not allowed in strict mode.

Infinity (∞) represents the greatest possible number that can ever be reached. It is the value you get when you divide any positive number by zero. This means that there are no "division by zero" errors in javascript.

-Infinity (-∞) represents the least possible number that can ever be reached. It is the value you get when you divide any negative number by zero

```js
console.log(1/0); // Infinity
console.log(-1/0); // -Infinity
```

NaN is the value you get from a computational error whereby the result of a numerical action is not a number. It is a result of an incorrect or an undefined mathematical operation, for instance:

```js run
console.log("Harare"/2); //NaN
```

Though NaN is not actually a number, it formally belongs to the "number" type.

string

A string literal in JavaScript must be surrounded with quotes. In Javascript there are 3 types of quotes:

let greeting = "Hello World"; // double quotes
let alienGreeting = 'Hi human'; // single quotes
let parasiteName = `cow ticks`; // back ticks

More on JavaScript Strings

boolean

The boolean type can only assume two values true and false.

For example:

let userLogged = true; // the user is logged in
let userVerified = false; // the user is not verified

Boolean values are also the output of many logic comparisons

let isGreater = 23 > 87;
console.log(isGreater); // false
// because 23 is not greater than 87
console.log(3 < 87); // true

null and undefined

null and undefined are two different data types. In fact, each is its own data type. null has only one possible
value which is null and undefined has only one possible value which is undefined.

The similarity between null and undefined is that they both represent something that doesn’t exist, and that itself has between the source of confusion among novice developers.

undefined is the default value of a variable that is declare but not initialised.

let gender;
var sex;

console.log(gender); // undefined
console.log(sex); // undefined

Using the example above, we can safely say undefined means "value is not assigned". However we can explicitly set the value of a variable as undefined return it to a state of an uninitialised variable:

let gender = "male";

console.log(gender); // male

gender = undefined;

console.log(gender); // undefined

null represents a value that is initialised but holding "nothing", an "empty" value or an "unknown" value.

let gender;

console.log(gender); // undefined

gender = null;

console.log(gender); // null

In the example above, gender is unknown or empty but initialised.

Word of advice Use null instead of undefined to represent an "empty" or an "unknown" value, and use undefined to check if the variable has been previously been initialised or not, if necessary.

Objects

All the data types mentioned above are immutable primitives, which means their values can contain one data type which we can’t manipulate. An object is a custom data container whose contents are custom and can change any time.

The data contents in an object are called properties or members. Properties of an object consist of a name and value.

// create an empty object
let student = {};
console.log(typeof student); // object
console.log(student); // {}

// one way of adding a property to an object
student.race = "African";
console.log(student); // { race: 'African' }

//another way of adding a property to an object
student["name"] = "Sydney";
console.log(student); // { race: 'African', name: 'Sydney' }

Symbols

Symbols were introduced in ES6. They were introduced to create unique identifiers for objects. Once created,
a symbol is unique. Unlike objects, symbols are primitive.

Symbols are created with the Symbol() constructor.

const headmaster = Symbol();
console.log(typeof headmaster); // symbol
const headmaster = Symbol();
const sportsmaster = Symbol();

console.log(headmaster == sportsmaster); // false
// symbols are unique

typeof

We use the typeof operator to check the data type of an argument.

const escapeVelocity = 11;
const planet = "Earth";
const hospitable = true;
const atmosphere = {
    oxygen: 20,
    nitrogen: 79
    }
let love;

console.log(typeof escapeVelocity); // number
console.log(typeof planet); // string
console.log(typeof hospitable); // boolean
console.log(typeof atmosphere); // object
console.log(typeof love); // undefined
console.log(typeof atmosphere.oxygen); // number
const escapeVelocity = 11;
const planet = "Earth";
const hospitable = true;
const atmosphere = {
    oxygen: 20,
    nitrogen: 79
    }
let love;

console.log(typeof(escapeVelocity) ); // number
console.log(typeof(planet) ); // string
console.log(typeof(hospitable) ); // boolean
console.log(typeof atmosphere); // object
console.log(typeof love); // undefined
console.log(typeof atmosphere.oxygen); // number

As you can see from the above examples, it doesn’t matter whether you use it as typeof x or as typeof(x).

In other words, it works both with parentheses or without them. The result is the same.

Warning

console.log(typeof null); // object

Which is actually wrong because null is not an object type but a null type. But that’s OK, it’s one of JavaScript’s quirks.