What You Need to Know about JavaScript Delve into the fundamentals of JavaScript Gabriel Cánepa BIRMINGHAM - MUMBAI What you need to know about JavaScript Copyright © 2016 Packt Publishing All rights reserved No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews Every effort has been made in the preparation of this book to ensure the accuracy of the information presented However, the information contained in this book is sold without warranty, either express or implied Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals However, Packt Publishing cannot guarantee the accuracy of this information First Published: May 2016 Production reference: 1300516 Published by Packt Publishing Ltd Livery Place 35 Livery Street Birmingham B3 2PB, UK www.packtpub.com About the Author Gabriel Cánepa is a Linux foundation certified system administrator (LFCS-1500-0576-0100) and web developer from Villa Mercedes, San Luis, Argentina He works for a multinational consumer goods company and takes great pleasure in using FOSS tools to increase productivity in all areas of his daily work When he's not typing commands or writing code or articles, he enjoys telling bedtime stories with his wife to his two little daughters and playing with them, which is a great pleasure of his life About the Reviewer Walter Molina is a web developer from Villa Mercedes, San Luis, Argentina His skills include, but they are not limited to, HTML5, CSS3, and JavaScript He uses these technologies at a Jedi/ninja level (along with a plethora of JavaScript libraries) in his daily work as frontend developer for a prestigious software firm He holds a bachelor's degree in computer science and is co-founder of Tachuso (www.tachuso.com), a social media and design agency He is also a member of the CS department at a local college, where he teaches programming skills to second and third year students www.PacktPub.com Support files, eBooks, discount offers, and more At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books, eBooks, and videos TM https://www.packtpub.com/books/subscription/packtlib Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library Here, you can access, read and search across Packt's entire library of books Why subscribe? • Fully searchable across every book published by Packt • Copy and paste, print and bookmark content • On demand and accessible via web browser Free access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books Simply use your login credentials for immediate access Table of Contents What is JavaScript? Variables, mathematical operations, and string concatenation Arrays and objects Conditionals and loops Functions Libraries 1 Getting Started with ECMAScript 12 Bringing It All Together with Visual Studio Code 24 Template strings Tagged templates Arrow functions Classes The let keyword Choosing an integrated development environment Creating directories and files for our web application with Visual Studio Code Writing JavaScript code for our application Testing our application 13 15 16 19 22 24 25 32 37 To the Future and Beyond 40 JavaScript Cheat Sheet 44 What's in the near future of JavaScript? Reviewing the number object Working with strings Boolean object fundamentals Grouping statements into functions Getting started with arrays Fundamentals of date objects [i] 40 44 45 46 47 48 49 Table of Contents Introducing assignment and arithmetic operators Using comparison operators Several possible courses of action – Using the switch-case control structure Summary What to next? Broaden your horizons with Packt 50 51 52 53 54 54 [ ii ] Preface What you need to know about JavaScript This eGuide is designed to act as a brief, practical introduction to JavaScript It is full of practical examples which will get you up and running quickly with the core tasks of JavaScript We assume that you know a bit about what JavaScript is, what it does, and why you want to use it, so this eGuide won't give you a history lesson in the background of JavaScript What this eGuide will give you, however, is a greater understanding of the key basics of JavaScript so that you have a good idea of how to advance after you've read the guide We can then point you in the right direction for what to learn next after giving you the basic knowledge to so What You Need to Know about JavaScript will the following: • Cover the fundamentals and the things you really need to know, rather than niche or specialized areas • Assume that you come from a fairly technical background and so understand what the technology is and what it broadly does • Focus on what things are and how they work • Include practical examples to get you up, running, and productive quickly [ iii ] What you need to know about JavaScript The following code snippet will help us illustrate this: var famousWriters = []; famousWriters.push("C S Lewis"); famousWriters.push("J K Rowling"); famousWriters.push("J R R Tolkien"); famousWriters.push("Richard Bach"); Given the preceding array, the following statements will evaluate to true: famousWriters.includes("C S Lewis"); famousWriters.includes("Richard Bach"); Whereas the next statements will return false: famousWriters.includes("C S Lewis", 1); famousWriters.includes("John Doe"); Even when "C S Lewis" belongs to the array, famousWriters includes("C S Lewis", 1) begins the search at the second element of the zero-based index array The next three features are not compatible with the current versions of modern browsers as of May 2016: • Object.values/Object.entries: This feature is already in Stage of ECMAScript (2017) This feature allows you to retrieve value or key-value pairs from objects for the purposes of iteration and serialization, as the documentation states Let's take the following example: var person = { name: "Gabriel", age: 33, profession: "developer" }; For this example, consider the following statement console.log(Object.values(person)); This should return the following: ['Gabriel', 33, 'developer'] Likewise, also consider the following statement: console.log(Object.entries(person)); This statement should return the following: [ ['name', 'Gabriel'], ['age', 33], ['profession', 'developer'] ] Even when these features are part of ECMAScript 8, they are expected to be compatible with the next versions of major modern browsers [ 41 ] What you need to know about JavaScript • String padding: This feature is also in Stage as of May 2016 Until ECMAScript 6, there were no native methods to pad a string, whereas most modern popular languages implement similar functions Today, when the need for padding arises, developers have to resort to a wide variety of inefficient methods and workarounds Making string padding an official part of the specification will provide a standardized solution that will improve performance of applications The padStart() and padEnd() method pads the current string with a specific string (eventually repeated) so that the resulting string reaches a desired length Depending on the case, the pad is applied from the beginning (left) or from the end (right) of the current string, respectively If the pad string is not specified, a space is used by default For example, consider the following statement: console.log(1.padStart(10)); This will print the following: " 1" Similarly, consider the following statement: console.log('1'.padStart(10, "0")); This will return the following: "0000000001" On the other hand, let's take a different example: console.log('1'.padEnd(10)); This statement will output the following: "1 " Similarly, consider the following example statement: console.log('1'.padEnd(10, "0")); This will result in the following: "1000000000" When the specified padding is less than or equal to the length of the original string, no padding characters are added Let's take the following two statements as an example This is the first statement: console.log('2016'.padStart(4, "0")); [ 42 ] What you need to know about JavaScript The second statement is as follows: console.log('2016'.padEnd(3, "0")); Both these statements will return the following: "2016" These are only three of the new features that will soon become a part of the ECMAScript standard You can refer to the full list, along with a detailed browser compatibility, at http://kangax.github.io/compat-table/esnext/ The examples in this section are illustrated in https://jsfiddle.net/gacanepa/ sr6oyk0u/ As we approach the date when the ECMAScript specification goes from draft to published, we can say without fear of being wrong that JavaScript will remain the main and the most widely-used programming language for the web in the foreseeable future New features will continue to be added to make it a cleaner language with which both beginners and experts get along just fine [ 43 ] What you need to know about JavaScript JavaScript Cheat Sheet In this last section of the eGuide, we will share a brief JavaScript cheat sheet that we hope you will find useful, both as a reminder and as a reference You can refer to this section of the eGuide when you need to find quick help and usage examples for each JavaScript object type In the following lists, the output of a statement or expression is given as a comment (following the two forward slashes) Reviewing the number object The number JavaScript base object allows us to work with numerical values Rather than performing actual mathematical operations, number lets us query an argument to see whether it matches certain conditions (that is, is it an integer?) or modify its format (for example, define the number of decimal digits in the output): • Number.isNaN(value): This returns true if the value is of the Number type and evaluates to NaN; otherwise, this is false This should not be confused with the isNaN global, which attempts to convert the value and then tests it: Number.isNaN(3); //false Number.isNaN("hi there"); //false Number.isNaN(Math.sqrt(-1)); //true Number.isNaN(0/0); //true • Number.isInteger(): This returns true if the argument is an integer; otherwise, this is false: Number.isInteger(2); //true Number.isInteger(3.5); //false Number.isInteger("a"); //false Number.isInteger(3500); //true [ 44 ] What you need to know about JavaScript • Number.prototype.toFixed(n): This returns the number given by Number prototype in fixed-point notation with n number of decimal places This rounds up when the digit in the (n + 1) position is greater than or equal to 5: var a = 2.6742252; a.toFixed(1); //"2.7" a.toFixed(2); //"2.67" a.toFixed(3); //"2.674" a.toFixed(5); //"2.67423" Working with strings The string object allows you to manipulate text strings or sequences of characters that are composed of one or more characters The string variables are often used to store data in text form: • String.prototype.length: This returns the length of the string that is specified by String.prototype • String.prototype.charAt(value): This returns the character at the index given by value • String.prototype.charCodeAt(value): This returns the Unicode equivalent of the character found at the index given by value • String.prototype.includes(value): This returns true if the value is found inside another String.prototype; otherwise, this is false • String.prototype.indexOf(value): This returns the index where the first occurrence of the value is found (if it exists); otherwise, this is -1 • String.prototype.lastIndexOf(): This returns the index where the last occurrence of the value is found (if it exists); otherwise, this is -1 • String.prototype.startsWith(value): This returns true if a string starts with the value • String.prototype.substring(value1, value2): This returns the substring found between two indexes (value1 and value2 where value2 > value1) • String.prototype.toLowerCase(): This converts the string to lowercase • String.prototype.toUpperCase(): This converts the string to uppercase [ 45 ] What you need to know about JavaScript Here is an example for your reference: var sentence = "We all live in a yellow submarine"; sentence.length; //33 sentence.charAt(17); //"y" sentence.charCodeAt(17); //121 sentence.includes("sub"); //true sentence.includes("Beatles"); //false sentence.indexOf("a"); //3 sentence.lastIndexOf("a"); //28 sentence.startsWith("We"); //true sentence.startsWith("all live in"); //false sentence.endsWith("marine"); //true sentence.endsWith("submarine"); //true sentence.endsWith("Great song!"); //false sentence.substring(7, 23); //"live in a yellow" sentence.toLowerCase(); //"we all live in a yellow submarine" sentence.toUpperCase(); //"WE ALL LIVE IN A YELLOW SUBMARINE" Boolean object fundamentals Boolean variables can store either one of two values: true or false If you are interested in converting the value of a variable to a string in order to use it in an expression, or if you want to assign the same value to another variable, the following methods will help you get the job done: • Boolean.prototype.toString(): This returns true or false (as strings), based on the Boolean value of the variable (true or false, respectively): var x = true; x; //true x.toString(); //"true" • Boolean.prototype.valueOf(): This returns the Boolean value of the variable Typically, this is used to assign the value of the given Boolean.prototype to another variable: var y = x.valueOf(); y; //true [ 46 ] What you need to know about JavaScript Grouping statements into functions Also known as methods in other programming languages, JavaScript functions allow you to group statements in a single block that can be invoked at will in several places of the code Thus, if a change needs to be made to correct an error or implement a feature, the code of the function has to be modified in one place only: // Declare function function name(arg1, arg2, …, argN) { // Javascript expressions here } // Call function var result = name(value_for_arg1, value_for_arg2, …, value_for_argN); Result; An example of this is as follows: function isAdult(age) { if (Number.isInteger(age)) { if (age >= 18) { return "You are an adult"; } else { return "You are a minor"; } } else { return "You have entered an invalid age"; } }; var result = isAdult(15); //"You are a minor" var result = isAdult(99); //"You are an adult" var result = isAdult("AA"); //"You have entered an invalid age" Using arrow functions, the result is the same, which is as follows: var result = (age) => { if (Number.isInteger(age)) { if (age >= 18) { return "You are an adult"; } else { return "You are a minor"; } [ 47 ] What you need to know about JavaScript } else { return "You have entered an invalid age"; } }; result(18); //"You are an adult" result(16); //"You are a minor" result("CC"); //"You have entered an invalid age" Getting started with arrays In simple terms, an array is a list-like object Let's have a look at the most frequently-used methods: • Array.prototype.push: This adds element(s) to the end of the array given by Array.prototype • Array.prototype.unshift: This adds new item(s) to the beginning of an array • Array.prototype.length: This gets the length (number of items) of the array • Array.prototype[n]: This accesses the item in position n of the array This returns undefined if it the given position does not exist within the array • Array.prototype.forEach(callback, [, thisArg]): This executes a function on each element in the array The callback is a function that takes three mandatory arguments (this is the current element in the iteration, its index, and array, which is a placeholder for the array being examined) Additionally, thisArg is an optional argument that can be used to define the this value when the callback function is executed • Array.prototype.pop(): This removes the last item of an array • Array.prototype.shift(): This removes the first item of an array • Array.prototype.splice(pos, n): This removes n number of elements starting at the position specified by pos • Array.prototype.slice(): This copies an array into another variable An example of this is as follows: var fairyTales = []; fairyTales.push("Cinderella"); fairyTales.unshift("Beauty and the Beast"); fairyTales.unshift("The little mermaid"); [ 48 ] What you need to know about JavaScript fairyTales; //Array [ "The little mermaid", "Beauty and the Beast", "Cinderella" ] fairyTales[1]; //"Beauty and the Beast" fairyTales.length; //3 fairyTales.forEach(function (item, index, array) { console.log(item, index); }); //The little mermaid //Beauty and the Beast //Cinderella var fairyTalesOrig = fairyTales.slice(); fairyTalesOrig; //Array [ "The little mermaid", "Beauty and the Beast", "Cinderella" ] fairyTales.pop(); fairyTales; //Array [ "The little mermaid", "Beauty and the Beast" ] fairyTales.shift(); //"The little mermaid" fairyTales; //Array [ "Beauty and the Beast" ] Fundamentals of date objects Date objects are used to represent a fixed date and time: • Date.prototype.getDate(): This returns the day of the month (1-31) for the date specified by Date.prototype, which must follow the guidelines outlined in IETF-compliant RFC 2822 for timestamps • Date.prototype.getDay(): This returns the day of the week (0-6) • Date.prototype.getFullYear(): This returns the year • Date.prototype.getHours(): This returns the hour (0-23) • Date.prototype.getMinutes(): This returns the minutes (0-59) • Date.prototype.getMonth(): This returns the month (0-11) • Date.prototype.getSeconds(): This returns the seconds (0-59) • Date.prototype.getTime(): This returns the number of milliseconds since January 1, 1970, 00:00:00 UTC For prior dates, the result is a negative number • Date.prototype.toString(): This returns the string representation of Date.prototype [ 49 ] What you need to know about JavaScript Here is an example: var myBirthDate = new Date(Date.UTC(1983,0,15,13,09,05)); myBirthDate; //Date 1983-01-15T13:09:05.000Z myBirthDate.getDate(); //15 myBirthDate.getDay(); //6 myBirthDate.getFullYear(); //1983 myBirthDate.getHours(); //10 myBirthDate.getMinutes(); //9 myBirthDate.getMonth(); //0 myBirthDate.getSeconds(); //5 myBirthDate.getTime(); //411484145000 myBirthDate.toString(); //"Sat Jan 15 1983 10:09:05 GMT-0300 (ART)" Introducing assignment and arithmetic operators In order to perform assignments of values to variables or an arithmetic operation, JavaScript uses the following guidelines: • =: This assigns a value to a variable • +=: This adds a value to the current value of a variable • -=: This subtracts a value from the current value of a variable • *=: This multiples the current value of a variable • /=: This divides the current value of a variable • %=: This returns the remainder of a division to a variable • + and +=: These operators are also used to concatenate strings • +, -, *, and /: These operators are used for the usual arithmetic operations when used with numbers • ++ and : These operators are used to increment or decrement the value of a variable, respectively An example of this is the following: var x = x; //10 x += 2; x -= 7; x *= 9; x /= 9; 10; //12 //5 //45 //5 [ 50 ] What you need to know about JavaScript x %= 3; //2 x = x++; x = x; Using comparison operators When we need to determine a course of action based on the comparison between two variables, JavaScript provides the following operators: • a < b: This is true if b is greater than a; otherwise, this is false • a b: This is true if a is greater than b; otherwise, this is false • a >= b: This is true if a is greater than or equal to b; otherwise, this is false • a == b: This is true if a is equal to b; otherwise, this is false • a === b: This is true if a is equal to b and both variables are of the same type; otherwise, this is false • a != b: This is true if a and b are not equal; otherwise, this is false • a !== b: This is true if a and b are not equal or if they are of different types; otherwise, this is false An examples of this is as follows: var a = 15; var b = 18; a > b; //false a !== b; //true var x = 15; var y = 15; x == y; //true x === y; //true var z = "15"; x == z; //true x === z; //false [ 51 ] What you need to know about JavaScript Several possible courses of action – Using the switch-case control structure When there are several "forks in the road" (that is, courses of action depending on the values of variables), a switch-case control structure can be our best friend This will allow us to perform different actions that are based on the value of the control variable: Refer to Section for other control structures and loops switch (variable) { case value1: //Actions to perform if variable=value1 break; case value2: //Actions to perform if variable=value2 break; default: //Actions to perform if variable is not equal to value1 or value2 break; } Let's consider the following example: var currentTime = new Date(); currentTime.getHours(); //20 var currentHour = currentTime.getHours(); switch (true) { case (currentHour < 12): console.log("Good morning!"); break; case (currentHour > 12 && currentHour < 17): console.log("Good afternoon!"); break; default: console.log("Good evening!"); break; }; [ 52 ] What you need to know about JavaScript Given the current hour of day, as indicated by currentHour, the switch-case control structure should return the following: Good evening! The examples in this chapter can be found at http://jsfiddle.net/gacanepa/qu3rzjmq/ Summary In the first section, we reviewed some fundamental programming concepts of JavaScript Moving to the second section, we introduced the most distinguishing features of ECMAScript 6: template strings, tagged templates, arrow functions, classes and inheritance, and the let keyword Particularly, we showed you how these tools can help us write cleaner and more maintainable code when compared to previous specifications of the language In the next section, we put everything together in a basic, yet fully-functional, web application We created a basic web application to add daily activities to a list where we could change their status when complete or remove them if our plans change Through the use of ECMAScript 6, we were able to group tasks into objects of the same type so that they could be more easily accessed for later processing In this last section of the eGuide, we shared a brief JavaScript cheat sheet that you can refer to when you need to find quick help and usage examples for each JavaScript object type [ 53 ] What you need to know about JavaScript What to next? Broaden your horizons with Packt If you're interested in JavaScript, then you've come to the right place We've got a diverse range of products that should appeal to budding as well as proficient specialists in the field of JavaScript [ 54 ] What you need to know about JavaScript To learn more about JavaScript and find out what you want to learn next, visit the JavaScript technology page at https://www.packtpub.com/tech/javascript If you have any feedback on this eBook, or are struggling with something we haven't covered, let us know at customercare@packtpub.com Get a 50% discount on your next eBook or video from www.packtpub.com using the code: [ 55 ] .. .What You Need to Know about JavaScript Delve into the fundamentals of JavaScript Gabriel Cánepa BIRMINGHAM - MUMBAI What you need to know about JavaScript Copyright © 2016... guide We can then point you in the right direction for what to learn next after giving you the basic knowledge to so What You Need to Know about JavaScript will the following: • Cover the fundamentals. .. this: if you need to use one form of quote in the string, you might want to use the other one as the literal [3] What you need to know about JavaScript These concepts are displayed in the following