JavaScript data types

Data storage types such as variables can store different types of data in JavaScript.

Variables can be different data types. The basic types in JavaScript are:

  • Number
  • String
  • Boolean
  • Undefined
  • Null
  • Object

Numbers

var x = 1;
console.log(x);
x++;
console.log(x);
typeof x;

JavaScript does not differentiate between integers and floating point numbers, such as 1 and 1.5.

NaN means "Not a Number". You will get that if you try to evaluate a string that cannot be parsed to a number. You can test for NaN using the isNaN() function.

 isNaN(NaN);
 isNaN("hello world");
 isNaN("7"); // why doesn't this return false?

Strings

Strings in JavaScript are sequences of characters, using Unicode they are represented by a 16-bit number, for example: "Hello world." or "string". Characters are written as strings with the length of one. Strings provide length, a property that returns the length of the string.

"Hello World".length

Strings also have some built in methods like charAt() and replace() which help us do evaluation and manipulation.

var str = "Hello world";
str[0];
"Hello world".charAt(0);
"Hello world".replace("world", "Jerry");
"Hello world".indexOf("world");

More string methods

Addition vs. concatenation

var x = 1;
var y = "7";
x + y;
typeof x + y;
y + x;
x + +y;
x + Number(y);

Booleans

Booleans default to the values true and false.

In JavaScript many values will become false, such as 0, "" (empty string), NaN, null, and undefined.

Everything else defaults to true, such as "Hello World", 1, 99, or -99. Try evaluating some booleans in the console with this syntax:

Boolean("");
Boolean(null);
Boolean(4);

We'll use booleans when we start working on logic.

Null and undefined

JavaScript uses null and undefined as distinct values. null indicates a purposely unassigned value. undefined indicates a variable that has been instantiated but not assigned with a value. typeof null is object while typeof undefined is "undefined".

console.log(y);
var x;
console.log(x);