Hacking in JavaScript 1

Tram Ho

JavaScript series

This chapter talks about trivial and miscellaneous issues in JavaScript that I don’t know where to put them

If you are looking forward to the support and suggestions of everyone to complete the series.

A. Math object

Math is an object available in JS, containing a number of constants and mathematical functions. You can use the Math object directly without creating it.

1. Math constants

Inside Math there are mathematical constants as attributes.

The names of constants are all capitalized, and they cannot be changed.

2. Math methods

Some important methods of Math are as follows.

Functions to round numbers

The function random a real number from 0 to 1.

The function finds max, min of any number of numbers.

For max, min a sequence of numbers, use the apply() method to pass the array as follows.

Learn more about apply() in the JavaScript function chapter.

B. Error handling

When the code runs, there may be unexpected errors occur. Some errors can be found and fixed, such as the case of wrong code, users do not enter data, divide by 0, … it can be quickly fixed. However, there are some unexpected errors such as network errors, hardware errors, server rejection, … it is impossible to check them all.

Such errors are growing more and more unpredictable, so the way to catch errors by anticipating cases and fixing them as before is no longer effective. Therefore, the concepts of exception (exception) and exception handling (exception handling) are introduced.

In JS, the exception is called error, this concept is equivalent to the exception in other languages.

1. Try catch finally

The try catch finally error structure is introduced to catch all kinds of errors that arise when running certain code. The structure consists of 3 parts as above, of which the finally part can be omitted:

  • The try block: contains pieces of code that can cause errors.
  • catch block: when an error occurs, the current code is stopped and this block is executed to handle the received error (for example, informing the user for example). catch usually takes a parameter named e or err , representing the error thrown (it’s okay if not).
  • The finally : block is always executed, with or without errors.

Flow of try catch finally from top to bottom. If the code in try has an error, then jump right into the catch to process. If the try has no error then the catch block will be ignored. Finally, if the finally block exists, the code will be executed in this block.

2. Throw an error

Used to throw a custom error, this error can be anything, such as a number (error code), a string (error message) or an error object (discussed later).

Throw is often used in functions, to throw an error. And if this function is called in the above try block, if an error is thrown by the function then the catch will catch it.

Add an example.

The above code uses the user’s age, and uses checkAge() to check. Instead of the previous test the function will return a boolean, true is ok and false is not, but here we will use the error instead.

If age less than 18, checkAge() will throw an error, You must be... The try block when detecting an error will stop immediately, and jump over the catch . This unit takes an error into the parameter e , and prints it to the console screen.

In contrast, age greater than 18 has no error thrown, the commands in try are carried forward and finally notified Oh, welcome to X

3. Nested try catch

The try catch finally block can be nested as follows. And should refrain from writing such nested.

This makes another issue arise, when the error checkAge() which catch block will catch that error. As above code, only the catch(e1) block catch(e1) will receive and handle the error. So, only the user can access những trò XYZ bình thường but can continue with những trò ABC, XYZ khác .

So, if you want both blocks to receive errors, then how. That is, if the internal try fails, the external try also receives the error and stops at the same time. That is to ensure safety.

At this point, the throw command will take advantage of its second effect, which is to forward the error to the next error capture block. Modify the code as follows.

Errors when handled in catch(e1) completed will be thrown (forward) upwards for the large outside try catch block to know, and from there catch(e2) will be received and processed.

4. Error object

JS has a number of error objects available, each containing two name and message attributes of string type to describe an error. The functions available in JS will throw an error object whenever an error occurs.

The above code shows an “abc does not exist” error, and the error thrown by JS is named ReferenceError and the message is abc is not defined .

Some commonly available error objects:

  • RangeError : exceeds allowed range
  • TypeError : wrong type, or access to null (similar to NullPointerException in Java)
  • SyntaxError : wrong syntax
  • ReferenceError : undefined, ReferenceError variable

There are also some other types of error objects. The above errors are standard errors in JS, in addition to non-standard errors (non-standard) depending on the browser type.


1. JSON introduction

JSON (JavaScript Object Notation) is a set of data format syntax, commonly used in storing and exchanging data between clients and servers similar to XML.

JSON has the following characteristics:

  • Light-weight (light-weight)
  • Self describle: speaking itself of its content, understanding simply reading and understanding immediately ?
  • Highly compatible, regardless of language


JSON has the same syntax as the JS object, but JSON is essentially just a text, so in addition to JS, there are other languages ​​that can use JSON (directly or through libraries).

Because the structure is similar to the JS object, handling JSON in JS is much easier.


Cross domain policy & JSONP

2. JSON syntax

JSON obeys certain rules of writing, just the right rules can be completely processed and error free.

Data pair

Data stored in JSON is paired with key and value similar to property and value in JS. Between key and value are two dots, between pairs are commas.

JSON does not allow comma trailing, meaning that the comma is the last one, while JS still works.

The difference with object syntax in JS is that the JSON key name must always enclose the "" pair (must be double quotes, do not accept single quotes or anything else).

Data types

JSON accepts values ​​of types:

  • Null
  • Number
  • Boolean
  • String: use enclosed double quotes
  • Object: put in pair {}, which contains many similar key: value pairs
  • Array: enclose in [], each element is separated by commas

Unlike object, JSON is pure data, so it does not allow types:

  • Function
  • Date
  • Undefined

The sample JSON above is an array of 2 child objects, each object has two name and value properties.


Data pairs can be nested inside an array or object. Note that when inserted into the object, it must belong to a certain new key, as the following example.

JSON minify

JSON sometimes you will see it is not written on many lines as above, only one line, no tabs or spaces at all, that is JSON minified to reduce the size down.

Either way, it is valid because it is true to the JSON structure, but the minified segment is smaller and helps to consume bandwidth when transmitted, so it is often used.

The opposite of minify is pretty print, which makes the reduced JSON segment more beautiful.

3. JSON handling

JSON processing in JS is extremely easy, only consists of two operations:

  • Parse: from string JSON to an object in JS
  • Stringify: from object to JSON string

The above two operations correspond to the two methods of the JSON object.

JSON.parse method

Parse the JSON string into an object. Minify JSON string or not is okay, just the syntax is successful parse.

JSON.stringify method

Generate JSON string from object.

Note that if objects contain Date, undefined, or method properties, they will not be added to the JSON string.

By default, the generated JSON string has been minified, modified as follows to make the JSON string more beautiful and readable.

The third parameter above is the number of spaces used for indents. The second parameter is a replacer, but is rarely used, so it is set to null.

D. Regex

1. Regex introduction

Regex (regular expression – regexp) is a short text used to describe a pattern to search in text. Instead of searching for a exact string, a search with regex will return results that match the rules that the regex defines.

For example, finding all phone numbers in a long document. Obviously a normal search cannot be done because there is no exact number, only the structure of a 10-digit phone number. Therefore, we use regex /d{10}/g to find.

Of course, to find exactly, you need to know how to write the symbols of regex properly as required. This section will be discussed more in another post, you can find out more.

2. Regex in JS

String regex

Regex is just a text string with certain rules, so in JS it is also a string. And this regex string is written slightly different from the normal string.

The regex string in JS consists of 2 parts:

  • The pattern part (in the // pair): defines the regex structure
  • The flags section (behind the // pair): additional options for regex.

When the search with the regex is complete, the result usually returns an array of substrings matching the regex, each matching string called a match.

Check the match

Use the .test() method to check if a string matches a regex.

It only takes a portion of the regex match. If you want the whole string to match, without any redundancy, use the first anchor directive ^ and the end $ for the regex.

This method is often used to check if the user input is valid or not. For example, check if a string is an email, exactly when it matches the regex string describing the email (search on google ? ).

Get the match list

Use the .match() method to get a list of match .match() in a string.

Regex /d/g finds all (flag g ) numbers d in the given string s. The result is an array of 2 elements as above.

Regex in functions

Some functions and methods in JS support regex, for example, the split() method of string is used to cut strings into multiple substrings, separated by separators.

For example, separating words in a string is as follows.

Using the old method will only cut in a single space, so the result is not as expected. Now is the time for regex to take effect, because split() function supports regex as separator. We correct the code as follows.

The result is exactly what you want, no matter how much distance the word has.

Explain regex /s+/ above a bit:

  • Token s is for space only.
  • The + sign indicates that the preceding character can repeat 1 or more times.

In addition to the split() function as above, JS has many other functions and methods that support regex as parameters like .search() , replace() , … can learn more.

Share the news now

Source : Viblo