Spread operators

A spread operator looks exactly like a rest operator but performs the exact opposite function. Spread operators are used while providing arguments while calling a function or defining an array. The spread operator takes an array and splits its element into individual variables. The following example illustrates how the spread operator provides a much clearer syntax while calling functions that take an array as an argument:

    function sumAll(a,b,c){ 
      return a+b+c 
    } 
    var numbers = [6,7,8] 
    //ES5 way of passing array as an argument of a function 
    console.log(sumAll.apply(null,numbers)); //21 
    //ES6 Spread operator 
    console.log(sumAll(...numbers))//21 

In ES5, it is common to use the apply() function when passing an array as an argument to a function. In the preceding example, we have an array we need to pass to a function where the function accepts three variables. The ES5 method of passing an array to this function uses the apply() function, where the second argument allows an array to be passed to the function being called. ES6 spread operators give a much cleaner and precise way to deal with this situation. While calling sumAll(), we use the spread operator(...) and pass the numbers array to the function call. The array is then split into individual variables-a, b, and c.

Spread operators improve the capabilities of arrays in JavaScript. If you want to create an array that is made up of another array, the existing array syntax does not support this. You have to use push, splice, and concat to achieve this. However, using spread operators, this becomes trivial:

    var midweek = ['Wed', 'Thu']; 
    var weekend = ['Sat', 'Sun']; 
    var week = ['Mon','Tue', ...midweek, 'Fri', ...weekend]; 
     //["Mon","Tue","Wed","Thu","Fri","Sat","Sun"] 
    console.log(week); 

In the preceding example, we are constructing a week array using two arrays, midweek and weekend, using the spread operator.

Predefined functions

There are a number of functions that are built into the JavaScript engine and are available for you to use. Let's take a look at them. While doing so, you'll have a chance to experiment with functions, their arguments and return values, and become comfortable working with functions. The following is a list of the built-in functions:

  • parseInt()
  • parseFloat()
  • isNaN()
  • isFinite()
  • encodeURI()
  • decodeURI()
  • encodeURIComponent()
  • decodeURIComponent()
  • eval()

Note

The black box function

Often, when you invoke functions, your program doesn't need to know how these functions work internally. You can think of a function as a black box, give it some values (as input arguments), and then take the output result it returns. This is true for any function-one that's built into the JavaScript engine, one that you create, or one that a co-worker or someone else created.

parseInt()

The parseInt() function takes any type of input (most often a string) and tries to make an integer out of it. If it fails, it returns NaN, as shown in the following code:

    > parseInt('123'), 
    123 
    > parseInt('abc123'), 
    NaN 
    > parseInt('1abc23'), 
    1 
    > parseInt('123abc'), 
    123 

The function accepts an optional second parameter, which is the radix, telling the function what type of number to expect-decimal, hexadecimal, binary, and so on. For example, trying to extract a decimal number out of the FF string makes no sense, so the result is NaN, but if you try FF as a hexadecimal, then you get 255, as shown in the following piece of code:

    > parseInt('FF', 10); 
    NaN 
    > parseInt('FF', 16); 
    255 

Another example would be parsing a string with a base 10 (decimal) and base 8 (octal):

    > parseInt('0377', 10); 
    377 
    > parseInt('0377', 8); 
    255 

If you omit the second argument when calling parseInt(), the function will assume 10 (a decimal), with the following exceptions:

  • If you pass a string beginning with 0x, then the radix is assumed to be 16 (a hexadecimal number is assumed).
  • If the string you pass starts with 0, the function assumes radix 8 (an octal number is assumed). Consider the following examples:
            > parseInt('377'), 
            377 
            > console.log(0o377); 
            255 
            > parseInt('0x377'), 
            887 
    

The safest thing to do is to always specify the radix. If you omit the radix, your code will probably still work in 99 percent of cases (because most often you parse decimals); however, every once in a while, it might cause you a bit of hair loss while debugging some edge cases. For example, imagine you have a form field that accepts calendar days or months and the user types 06 or 08.

Note

ECMAScript 5 removes the octal literal values and avoids the confusion with parseInt() and unspecified radix.

parseFloat()

The parseFloat() function is similar to the parseInt() function, but it also looks for decimals when trying to figure out a number from your input. This function takes only one parameter, which is as follows:

    > parseFloat('123'), 
    123 
    > parseFloat('1.23'), 
    1.23 
    > parseFloat('1.23abc.00'), 
    1.23 
    > parseFloat('a.bc1.23'), 
    NaN 

As with parseInt(), parseFloat() gives up at the first occurrence of an unexpected character, even though the rest of the string might have usable numbers in it:

    > parseFloat('a123.34'), 
    NaN 
    > parseFloat('12a3.34'), 
    12 

The parseFloat() function understands exponents in the input (unlike parseInt()):

    > parseFloat('123e-2'), 
    1.23 
    > parseFloat('1e10'), 
    10000000000 
    > parseInt('1e10'), 
    1 

isNaN()

Using isNaN(), you can check if an input value is a valid number that can safely be used in arithmetic operations. This function is also a convenient way to check whether parseInt(), parseFloat(), or any arithmetic operation succeeded:

    > isNaN(NaN); 
    true 
    > isNaN(123); 
    false 
    > isNaN(1.23); 
    false 
    > isNaN(parseInt('abc123')); 
    true 

The function will also try to convert the input to a number:

    > isNaN('1.23'), 
    false 
    > isNaN('a1.23'), 
    true 

The isNaN() function is useful because the special value NaN is not equal to anything, including itself. In other words, NaN === NaN is false. So, NaN cannot be used to check if a value is a valid number.

isFinite()

The isFinite() function checks whether the input is a number that is neither Infinity nor NaN:

    > isFinite(Infinity); 
    false 
    > isFinite(-Infinity); 
    false 
    > isFinite(12); 
    true 
    > isFinite(1e308); 
    true 
    > isFinite(1e309); 
    false 

If you are wondering about the results returned by the last two calls, remember from the previous chapter that the biggest number in JavaScript is 1.7976931348623157e+308, so 1e309 is effectively infinity.

Encode/decode URIs

In a Uniform Resource Locator (URL) or a Uniform Resource Identifier (URI), some characters have special meanings. If you want to escape those characters, you can use the encodeURI() or encodeURIComponent()functions. The first one will return a usable URL, while the second one assumes you're only passing a part of the URL, such as a query string for example, and will encode all applicable characters, as follows:

    > var url = 'http://www.packtpub.com/script.php?q=this and that'; 
    > encodeURI(url); 
    "http://www.packtpub.com/script.php?q=this%20and%20that" 
    > encodeURIComponent(url); 
    "http%3A%2F%2Fwww.packtpub.com%2Fscript.php%3Fq%3Dthis%20and%20that" 

The opposites of encodeURI() and encodeURIComponent() are decodeURI() and decodeURIComponent(), respectively.

Sometimes, in legacy code, you might see the functions escape() and unescape() used to encode and decode URLs, but these functions have been deprecated; they encode differently and should not be used.

eval()

The eval() function takes a string input and executes it as a JavaScript code, as follows:

    > eval('var ii = 2;'), 
    > ii; 
    2 

So, eval('var ii = 2;') is the same as var ii = 2;

The eval() function can be useful sometimes, but it should be avoided if there are other options. Most of the time, there are alternatives, and in most cases, the alternatives are more elegant and easier to write and maintain. Eval is evil is a mantra you can often hear from seasoned JavaScript programmers. The drawbacks of using eval() are as follows:

  • Security: JavaScript is powerful, which also means it can cause damage. If you don't trust the source of the input you pass to eval(), just don't use it.
  • Performance: It's slower to evaluate live code than to have the code directly in the script.

A bonus - the alert() function

Let's take a look at another common function-alert(). It's not part of the core JavaScript (it's nowhere to be found in the ECMA specification), but it's provided by the host environment-the browser. It shows a string of text in a message box. It can also be used as a primitive debugging tool, although the debuggers in modern browsers are much better suited for this purpose.

Here's a screenshot showing the result of executing the alert("Hi There") code:

A bonus - the alert() function

Before using this function, bear in mind that it blocks the browser thread, meaning that no other code will be executed until the user closes the alert. If you have a busy Ajax-type application, it's generally not a good idea to use alert().

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.236.62