Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Object-Oriented JavaScript

You're reading from   Object-Oriented JavaScript Learn everything you need to know about object-oriented JavaScript (OOJS)

Arrow left icon
Product type Paperback
Published in Jan 2017
Publisher Packt
ISBN-13 9781785880568
Length 550 pages
Edition 3rd Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Ved Antani Ved Antani
Author Profile Icon Ved Antani
Ved Antani
Stoyan STEFANOV Stoyan STEFANOV
Author Profile Icon Stoyan STEFANOV
Stoyan STEFANOV
Arrow right icon
View More author details
Toc

Table of Contents (25) Chapters Close

Object-Oriented JavaScript - Third Edition
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface
1. Object-Oriented JavaScript FREE CHAPTER 2. Primitive Data Types, Arrays, Loops, and Conditions 3. Functions 4. Objects 5. ES6 Iterators and Generators 6. Prototype 7. Inheritance 8. Classes and Modules 9. Promises and Proxies 10. The Browser Environment 11. Coding and Design Patterns 12. Testing and Debugging 13. Reactive Programming and React Reserved Words Built-in Functions
Built-in Objects Regular Expressions
Answers to Exercise Questions

Chapter 3, Functions


Lets do the following exercises:

Exercises

  1. To convert Hex colors to RGB, perform the following:

            function getRGB(hex) { 
              return "rgb(" + 
                parseInt(hex[1] + hex[2], 16) + ", " + 
                parseInt(hex[3] + hex[4], 16) + ", " + 
                parseInt(hex[5] + hex[6], 16) + ")"; 
            } 
            Testing: 
            > getRGB("#00ff00"); 
                   "rgb(0, 255, 0)" 
            > getRGB("#badfad"); 
                   "rgb(186, 223, 173)" 
    

    One problem with this solution is that array access to strings like hex[0] is not in ECMAScript 3, although many browsers have supported it for a long time and is now described in ES5.

    However, But at this point in the book, there was as yet no discussion of objects and methods. Otherwise an ES3-compatible solution would be to use one of the string methods, such as charAt(), substring(), or slice(). You can also use an array to avoid too much string concatenation:

        function getRGB2(hex) { 
          var result = []; 
          result.push(parseInt(hex.slice(1, 3), 16)); 
          result.push(parseInt(hex.slice(3, 5), 16)); 
          result.push(parseInt(hex.slice(5), 16)); 
          return "rgb(" + result.join(", ") + ")"; 
        } 
    

    Bonus exercise: Rewrite the preceding function using a loop so you don't have to type parseInt() three times, but just once.

  2. The result is as follows:

            > parseInt(1e1); 
            10 
            Here, you're parsing something that is already an integer: 
            > parseInt(10); 
            10 
            > 1e1; 
            10 
    

    Here, the parsing of a string gives up on the first non-integer value. parseInt() doesn't understand exponential literals, it expects integer notation:

            > parseInt('1e1'); 
            1 
    

    This is parsing the string '1e1' while expecting it to be in decimal notation, including exponential:

            > parseFloat('1e1'); 
            10 
    

    The following is the code line and its output:

            > isFinite(0 / 10); 
            true 
    

    Because 0/10 is 0 and 0 is finite.

    The following is the code line and its output:

            > isFinite(20 / 0); 
            false 
    

    Because division by 0 is Infinity:

            > 20 / 0; 
            Infinity 
    

    The following is the code line and its output:

            > isNaN(parseInt(NaN)); 
            true 
    

    Parsing the special NaN value is NaN.

  3. What is the result of:

            var a = 1; 
            function f() { 
              function n() { 
                alert(a); 
              } 
              var a = 2; 
              n(); 
            } 
            f(); 
    

    This snippet alerts 2 even though n() was defined before the assignment, a = 2. Inside the function n() you see the variable a that is in the same scope, and you access its most recent value at the time invocation of f() (and hence n()). Due to hoisting f() acts as if it was:

            function f() { 
              var a; 
              function n() { 
                alert(a); 
              } 
              a = 2; 
              n(); 
            } 
    

    More interestingly, consider this code:

            var a = 1; 
            function f() { 
              function n() { 
                alert(a); 
              } 
              n(); 
              var a = 2; 
              n(); 
            } 
            f(); 
    

    It alerts undefined and then 2. You might expect the first alert to say 1, but again due to variable hoisting, the declaration (not initialization) of a is moved to the top of the function. As if f() was:

            var a = 1; 
            function f() { 
              var a; // a is now undefined 
              function n() { 
                alert(a); 
              } 
              n(); // alert undefined 
              a = 2; 
              n(); // alert 2 
            } 
            f(); 
    

    The local a "shadows" the global a, even if it's at the bottom.

  4. Why all these alert "Boo!"

    The following is the result of Example 1:

            var f = alert; 
            eval('f("Boo!")'); 
    

    The following is the result of Example 2. You can assign a function to a different variable. So f() points to alert(). Evaluating this string is like doing:

            > f("Boo"); 
    

    The following is the output after we execute eval():

            var e; 
            var f = alert; 
            eval('e=f')('Boo!'); 
    

    The following is the output of Example 3. eval() returns the result on the evaluation. In this case it's an assignment e = f that also returns the new value of e. Like the following:

            > var a = 1; 
            > var b; 
            > var c = (b = a); 
            > c; 
            1 
    

    So eval('e=f') gives you a pointer to alert() that is executed immediately with "Boo!".

    The immediate (self-invoking) anonymous function returns a pointer to the function alert(), which is also immediately invoked with a parameter "Boo!":

            (function(){ 
              return alert; 
            })()('Boo!'); 
    
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime
Visually different images