# JS data types

Tram Ho

## A. Number

### 1. Overview

Numbers in JavaScript are used for both integers and floats, and always support signed numbers. The data type is defined on the value assigned to it (value) and does not need to be explicitly specified.

Because there is no difference between an integer and a real number, it is possible to write the whole number with or without dots.

Real numbers can be written in decimal or scientific format, and numbers in the form of `0.abc` be abbreviated to `.abc` .

It is possible to write hexadecimal numbers (hexadecimal) with the prefix `0x` at the beginning, or some JS versions allow octal (octal) numbers by writing the first digit as 0. Therefore, numbers should not be written with leading zeros, unless you know what you’re doing.

### 2. Operators

The operators in JS are similar in other languages. From ES6 onwards there is an additional ** operator to calculate power.

Addition in JS has a special feature, when adding a number to a string will result in a string (string concatenation).

For other calculations like multiplication and division, … between two strings with numeric content, JS will try to convert it into numbers and perform calculations. For example.

### 3. Special value

Two special value numbers in JS are NaN (not a number) and Infinity. These two special values ​​are of type number, when using typeof gives the number result.

NaN value

The NaN value returned when performing an invalid calculation, such as dividing a string by a number (the string without the contents is a number). Then the calculation result is NaN.

Use the `isNaN()` function to check if a number has NaN value.

In expressions containing NaN, the end result is NaN. If the result is string, JS will convert NaN into string “NaN” and concatenate accordingly.

Infinity value

The positive infinity (Infinity) and the negative infinity (-Infinity) are returned when the expression result is too large for the JS limit. Infinity is also returned by dividing a number by 0.

Use `isFinite()` to check if the number is finite or not, if it is infinite (Infinity and -Infinity) will return false. NaN also returns false.

### 4. Number methods

Although number is primitive, JS does some tricks to make number work similar to object, that is, it has properties and methods.

The properties and methods below do not necessarily call from the variable number, can call from value, const or expression to count. For example.

### 5. Number properties

The properties below are only accessible via Number, not variables, constants or expressions like the above method. If intentionally violated, the result returned is undefined.

Below is a list of attributes. Maybe not need to say much more, just reading through the name alone you can understand it.

## B. Boolean

### 1. Overview

Boolean stores two values ​​true (true) and false (false). Boolean variables can be used instead of conditions in other statements.

Comparison and comparison expressions return a boolean value.

### 2. Everything is boolean

In JS, everything can be compared as a boolean, and is determined by the following rule:

• False: contains null values, such as 0, false, “”, null, undefined and NaN
• True: opposite of the above, and more Infinity and -Infinity.

### 3. Properties & methods

Boolean doesn’t have many properties and methods, mainly two methods `toString()` (convert to string) and `valueOf()` (get primitive values ​​- in this case, it doesn’t make much sense).

## C. String

### 1. Overview

String (string) used to store data as text. The content of the string is enclosed in double quotes or single quotes, as appropriate. If the content contains double quotes, use single quotes, and vice versa. In some cases of JS code in HTML events, it is required to use single quotes because double quotes are already taken by the HTML attribute.

Unlike other languages, access outside the array or string does not cause an error.

The string is basically an array of characters, with an index that counts from 0.

Escape character

The string cannot directly contain some characters, since it cannot be typed on the keyboard or is confusing (as above). Therefore it needs to be escaped by inserting the backslash symbol (backslash) before the above special character. For example.

The `"` character in the string must be written as `"` called the escape character (escape sequense)

In addition, other characters such as tab ( `t` ), new line ( `n` ), … are written as above, similar to other languages.

Line breaking

When writing code should not be longer than 80 characters per line, then should break down the new line right at the operator, not breaking between strings as follows is wrong.

In case if you want to break the middle of the string, that is, divide the string into 2 lines, then write as follows with the at the end of the line.

ES6 has a template string but temporarily not mentioned here.

### 2. Properties & methods

Because the property of the string only has the length, so I included it here.

Length property

The length attribute returns string length, note length is an attribute, so there are no brackets () parameters.

Access character

Use two methods `charAt()` and `charCodeAt()` to get characters and code at a certain position (index).

Note the UTF-16 encoding string, should contain Vietnamese and have the code in the range 0 – 65535.

ES5 introduces how to use [] to access characters in the string, similar to arrays. When no character is found, [] returns undefined while `charAt()` returns null.

Also can not change the content of the string, because JS string is immutable (immutable). Any changes made to the string must create a new string, so subsequent methods will return the new string instead of changing it directly onto the old string.

If deliberately change the string, then there is no error but nothing happens.

String concat

There are many ways to concatenate strings, including using the + `concat()` , using the `concat()` method, or gathering them into an array and then `join()` . This section `concat()` it about the `concat()` method.

Trim method

Use this method to remove spaces at the beginning and end of the string.

Uppercase, lowercase

Use the two methods `toUpperCase()` and `toLowerCase()` to convert the string to upper / lowercase in its entirety.

Find substring position

To find the position of substring (substring) in a given string, there are 3 methods as follows. These methods return the index (position) found, otherwise returns -1.

Yes, there are 3 methods `indexOf()` , `lastIndexOf()` and `search()` . Differences are as follows:

• `indexOf()` , `lastIndexOf()` find the exact given string. `indexOf()` finds left to right, while `lastIndexOf()` finds the opposite.
• `search()` supports searching for exact strings and regex, as the example above `/anh/i` is a regex in JS.

Also `search()` doesn’t have the second param (parameter) as the starting position, while the other two methods have. This position specifies to search from index onwards, not from the beginning, making it more optimal in some problems.

Extract substring

Use the following 3 methods to extract a part of the string and return a new string.

The `substring()` method does not allow the index to be negative, while the other two methods allow. This method cuts the string from the start index and ends at the end index (the end character is not taken).

The `substr()` method starts searching at the index and retrieves the substring of the required length.

The `slice()` method is quite similar to `substring()` , but accepts a negative index (a negative index counts down from the end of the string to the top, -1, -2, ….).

Replace method

The `replace()` method is used to replace part of a string with a new string.

Parameter 1 is the old string, parameter 2 is the string to be replaced. `replace()` accepts parameter 1 as a regex string.

Split method

Use string splitting as an array of substrings, based on the separator.

When separated by the above separator, there will be cases of multiple delimiters. Split will not work as expected, for example.

To handle the case of multiple contiguous separators, we use regex.

The above regex string represents one or more adjacent space characters, so the regex can make a string delimiter, the result will be exactly what you think.

ES6

ES6 adds some new string handling methods.

Although these methods can be replaced by comparing `indexOf()` , using new methods is more obvious.

## D. Array 1

### 1. Overview

Array (array) allows to store multiple values ​​in a single variable (array variable). The elements in the array are accessed by index from 0.

Unlike many other languages, arrays in JS allow to contain many different data types.

Array declaration

The array declaration consists of the array name and the list of values ​​in [], separated by commas.

Access array element

Use the index to access the element. The index is calculated from 0.

If the array range is exceeded, there is no error that the value received is undefined.

### 2. Array and object?

Array is an object

Array is really an object. If you use typeof for an array, the result is an object.

Arrays in JS use index to access elements, this is the best way. However, like other objects, these elements can be accessed via attribute names.

Creating array as an object

Arrays, instead of being declared by normal values, can also be declared by the new keyword and the Array constructor.

Array constructor takes a list of arguments as initial value for the array. However, this method should not be used because it is confusing and causes errors. For example.

What does it mean, create an array with a value of 10, or an array with 10 initial values ​​??? Therefore, we should declare the array with [] as usual.

Associative array

As mentioned, the array in JS is actually an object, it will have the property name and the value of that property. Instead of accessing the value via index, the object type will use the attribute name to access.

Therefore, this type of array is called associative array, with named index.

When declaring with [], only create value and index. To actually get the attribute name, you need to assign additional values ​​to the array.

Now, we can call `a["John"]` instead of `a[i]` to access the value. Index is the number, in this case has been named “John”.

Note, this time some methods, properties will give incorrect values. And should limit the use of this array type, if you want to have the attribute name, use the object instead.

### 3. Properties & methods 1

Length property

Returns the array length. Note `length` is an attribute, not a method, so write the following as false.

`length` has some strange behavior, specifically the value of length is the highest index value with value + 1. For example, array `[1, 2, 3, 4]` has the highest index of 3, so `length` is calculated. is 3 + 1 = 4.

This leads to a following problem.

How much do you think `a.length` would be worth? If it’s 5 then you’re wrong, now length is 7 (highest index 6 + 1 = 7). Obviously, this is not true of his thinking logic, when the array has only 5 elements and the length is 7.

In fact, the array structure a now looks like this.

There are empty (no value) spaces inside the array, and it makes the `length` attribute wrong.

Therefore, instead of directly assigning the above, it is recommended to use the methods shown below to safely add the element to the array.

Unshift & push method

These two methods add elements to the array and return the new array length. `push()` added at the end and `unshift()` added to the beginning of the array (other elements are pushed back 1 unit).

Shift & pop method

These two methods remove the element from the array, and return the deleted value. `pop()` deletes at the end and `shift()` deletes at the beginning (the other elements are moved forward by 1 unit).

Delete element

Delete the array element but do not move the other elements. If you look at the length problem example, you can use this command to delete an element, as if it had no value.

Delete the whole array

There are two ways, assign it an empty array [], or set `length` to 0.

IndexOf, lastIndexOf method

Used to find the position of a value in the array, similar to that of string.

## E. Array 2

### 1. Methods 2

Is array?

There are many ways to check if an object is an array. Below presents some basic ways.

The `Array.isArray()` method, introduced in ES5, helps to check if a variable is an array.

Since array is an object, we have to use the instanceof operator the second way.

There is also a way to find the word “Array” in the code constructor (attribute constructor) of that variable. But we don’t use this method because it’s a bit nonsense and slow.

Array concat

Using the `concat()` method to merge two arrays into 1, the method returns a new array.

Alternatively, use the spread operator (ES6) to make the connection faster, but not discussed here.

Splice method

This method both deletes existing elements and adds new elements.

In addition, `splice()` can be used to delete or add only.

Slice method

Like string, `slice()` method cuts off an array and returns a new array.

`slice()` can have 1 or 2 parameters, if parameter 2 does not have it will cut to the end of the array. If there is a second argument, it is the stop position, the element at the end position is not taken.

Notice the method name is `slice()` , different from `splice()` above.

Join & toString method

These two methods convert an array into a single string.

`toString()` converts to a string, separating the elements by commas and writing next to each other. The last element has no comma (not trailing comma).

Meanwhile `join()` is a little more advanced. This method accepts a string as a custom delimiter, for example if you want to look better, use `join()` .

If `join()` has no parameters, it is the same as `toString()` .

### 2. Sorting

String sort

Array has two methods to sort and reverse an array: `sort()` and `reverse()` .

`sort()` sort ascending, if you want to reduce it then use more `reverse()` to reverse.

But there is a problem, `sort()` default will sort the string (string sort), so the numbers are wrong (for example 11 is less than 2). Therefore, to sort the number array, you need to use numberic sort as below.

Numberic sort

Here we also use the `sort()` method with a parameter called the callback function that customizes the comparison, called the compare function. This function accepts two numbers, and the result returned determines the way to sort.

The above result for ascending sorted array. For descending order, there is no need to use `reverse()` in this case, just fix `return a - b` to `return b - a` in the above code.

### 3. Find max, min

Find max, min in array quickly, use `Math.max()` and `Math.min()` . Note that it is not possible to call in the normal way, since the above methods do not accept arrays, so need to call with `apply()` as follows.

The null parameter doesn’t need to be concerned, since we don’t pass any objects to `apply()` all.

## F. Iteration methods

### 1. Overview

ES5 has a number of iteration methods, which are used to iterate through all iterable objects, to understand simply that objects are iterable. In this section only consider array.

The iteration method all requires passing a param as a callback function. This function has the following form.

Each time an element is browsed, the information is updated and the above callback function is called once, with new information. Therefore, we put the handlers inside them, and return a value that matches the function of each method.

If you still don’t understand, it’s okay, go to the example below.

It is not necessary that these methods pass through the array, some of which only qualify are stopped immediately, like `some()` or `every()` .

### 2. Iteration methods

Array looping

To loop through the elements of the array, we can use the for loop as usual, loop through the index and access the element via the index.

Or ES5 has more for of loops as follows.

In each iteration, e will take each value of the element in the array respectively. The downside of this way is not knowing the index of the element is how much, want to know a few more cumbersome lines of code.

Therefore, the `forEach()` method was created as a more advanced way to loop arrays.

Pay attention to the anonymous function (without the name) that contains 3 parameter `value, index, array` . You will see it again during this section.

The above callback function has 3 parameters, but can remove the following two parameters if not needed, just keep the value. With the method `forEach()` with up to 3 parameters as above, we can both know the value, both know the index where it is, and can access the array. This is convenient, but in return, the speed will be slower.

Map method

Create a new array with the same length as the original array, but the values ​​are calculated, transformed in a certain way.

The `map()` method `map()` creates a new array, with each element in the old array being applied a number of transformations (in code 2 times) to make the new element. This operation is called map.

Notice the return in the callback is the return of each new value for the newly synthesized array.

Filter method

Returns a new array, including any elements in the old array that match a certain condition.

The `filter()` method browses each element, with each element considering whether it has been added to a new array or not.

The filter’s return is return boolean, if true it is received, false then the element is ignored.

Every, some method

The entire method returns boolean, `every()` checks that the array has all of the matching elements, while `some()` only needs a matching element to be ok.

Both methods browse each element, `every()` all elements must return true for every new to be true, and `some()` only needs a true element to be true immediately.

Find, findIndex method

Use returns a value in array. `find()` returns the value, while `findIndex()` returns the index of the found value (first element). If not, `find()` returns undefined and `findIndex()` returns -1.

Note that the “find” here is not merely looking for a value in the array, but more precisely it finds the first element that matches a certain condition.

Inside the callback, we return a boolean describing the condition found, such as equal to 5 (find the number 5 in the array), less than 5 (find the first number less than 5), …)

If you are looking midway and find a matching value, then stop always.

Reduce, reduceRight

Reduce is the operation from an array of “reduce” elements to a single value. Often used to sum all elements in the array, we call it “descending array into a total” instead of “summing up the whole array”.

`reduce()` and `reduceRight()` slightly different from other iteration methods, as its callback has an additional `prevValue` parameter.

`prevValue` value is the value “previously” gathered. In the above code, the previous value is added with the value, and return is the new value. This value in the next loop will become `prevValue` .

In a nutshell, after all elements are `prevValue` , `prevValue` from 0 is added up, and finally into the sum of the array. This sum is returned for the `reduce()` method (or `reduceRight()` ).

The above two methods also take param 2 behind the callback function, which initializes the initial value for prevValue.

`reduceRight()` similar to `reduce()` , but is run from the end of the array to the top, that’s all.

### 3. Arrow function

Often people will use the arrow function (ES6) in this case to write shorter code. For example instead.

then write with the arrow function is

or

If you do not know the arrow function, do not worry, the following articles will talk about. In the code above, I wrote the regular callback function for easy understanding.

## G. Date

### 1. Date object

To perform operations with time, we use the Date object. Note the time here includes the date (date) and time (time).

There are 4 ways to create a date object, using various parameters passed to the Date constructor.

Current datetime

`Date()` constructor without param will take the current gain saved to the variable. Note that the save time is fixed, do not automatically change unless you update it.

Custom datetime

Get 7 parameters respectively year (year), month (month), day (day), hour (hour), minute (minute), second (second) and millisecond (milisecond – msec).

There are two notes:

• The year if there are 1 or 2 digits, is the year 19AB.
• The month in JS counts from 0, so the number 7 will be August.

Miliseconds

JS actually stores time as an extra large integer, the number of milliseconds that elapsed from the original time.

The time to be chosen as the landmark of JS is 1/1/1970, 00:00:00.

The number of miliseconds can be negative, so the time will go back to the past.

String datetime

JS also allows receiving date strings and automatically parsing the appropriate time. This datetime string must follow certain standards for JS to recognize it correctly, read the next section.

### 2. Date format

JS allows identifying a date string according to a certain rule, including ISO standard date, long date (long date) or short date (short date) is accepted.

ISO date

Above are some acceptable ISO date string examples.

The above time has a “T” separating the date and time. The “Z” at the end indicates it is UTC time, GMT time zone (0). Or you can omit Z and specify the time zone deviation as follows.

Replace the “Z” with `+hh:mm` or `-hh:mm` .

Long date

Long date in JS has the form `MMM DD yyyy` , which uses space to separate. The year is always at the end and the month and day can be swapped.

Months can be abbreviated or complete, and are not case sensitive.

Short date

The syntax of the short date string in JS accepts as `MM/dd/yyyy` .

### 3. Date get, set methods

The Date object has a number of methods of the form `get_()` and `set_()` , used to read (get) or change (change) the components of time.

Get methods

Note the time-taking methods `s` .

There are also similar `getUTC_()` methods to get the time at GMT.

Set methods

Similar to `get_()` , but taking parameters is a new value to assign, instead of leaving it blank. For example

### 4. Date actions

Display date

The `toString()` method converts the date object into a string describing time, including date, day, year, hour, minute, second, (without milliseconds), time zone, and time zone name.

Besides ocnf has method `toUTCString()` to get time series at GMT.

Get miliseconds

If you want to get the number of milliseconds of a specific date string without creating a date object, you can use the `Date.parse()` method to parse the string and retrieve the number of milliseconds.

Compare

Because date objects store milliseconds, it is possible to determine which time is before which by comparison.

Current time

When you want to update the current date for the date object, use the `Date.now()` method and the `setTime()` method of the object to update as follows.

`Date.now()` returns the current number of milliseconds, so to assign the value of milliseconds, you need to use `setTime()` .

Add and subtract days

Use the combination of `getDate()` and `setDate()` to add or subtract certain dates.

Calculate the number of days between two dates

There are really no functions or methods that support this. One solution is to find the milliseconds, then divide by the number of milliseconds of the day as follows.

Note that this formula is only approximate, but it is acceptable if not required for high accuracy.

Share the news now

Source : Viblo