However, their result can be assigned to variables and used in operations later, as seen in the following figure: Mathematical operations with variables You can also concatenate the valu
Trang 2What You Need to Know about JavaScript
Delve into the fundamentals of JavaScript
Gabriel Cánepa
BIRMINGHAM - MUMBAI
Trang 3What 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
Trang 5About 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
Trang 6About 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
Trang 7Support 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
Trang 8Table of Contents
Bringing It All Together with Visual Studio Code 24
Creating directories and files for our web application with
Trang 9Introducing assignment and arithmetic operators 50
Several possible courses of action – Using the switch-case
Trang 10What 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 do so
What You Need to Know about JavaScript will do 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
Trang 11In this eGuide, we will review the fundamental concepts behind JavaScript, which
is the most used language among frontend developers and web designers It is also highly used among backend and fullstack developers (according to https://www.packtpub.com/skillup/web-dev-salary-report) Besides being easy to learn, JavaScript is used everywhere on the web today This, in itself, I believe is enough reason to either learn the language or polish your existing JavaScript skills
JavaScript is present the moment you launch your web browser to visit your favorite pages and interact with them; this applies to the end users of your applications As a web developer, here are some common uses of JavaScript:
• If you need to create a contact form where some fields are required, you can rely on JavaScript to alert the user if he has missed some of these fields and
to validate or sanitize their contents You don't have to rely on alert windows
anymore as the Document Object Model (DOM) can be accessed through
JavaScript to manipulate its look, content, and attributes
• You can populate search boxes with common terms as you type into them; this is a feature known as autocomplete
• Displaying or hiding information on demand and animating elements on a page is a walk in the park using JavaScript
• Using JavaScript, you can pass requests to a backend server and handle responses without reloading the page
• And many more…
All of this goes to show that the mission of JavaScript is to bring websites to life and
to enrich user experience while making things easier and keeping the design of web pages beautiful
Please join us as we dive into this powerful language in this eGuide
Trang 12What is JavaScript?
JavaScript is a very versatile language because it supports both object-oriented and procedural programming to bring interactivity to a Web page On top of this, due
to its flexibility, it allowed developers to write several wellknown tools (also known
as libraries, which we will discuss near the end of this section) that provide robust solutions with little extra effort Under the hood, these libraries are a combination of variable declarations, arithmetic, and conditional operators, iteration loops, functions, and event responses The purpose of this section is to help you get up to speed with some JavaScript fundamentals, and briefly refresh your mind on these constructing blocks of the language up to ECMAScript version 5 Then, you will be in better shape
to tackle ECMAScript 6 and its new features in the next section
Variables, mathematical operations,
and string concatenation
Like other programming languages, JavaScript enforces some rules on variable
naming For example, a valid variable name cannot start with a number (although numbers are allowed inside a variable name), it cannot contain spaces, arithmetic, Boolean operators, or punctuation signs In addition to this, you can't use reserved keywords and must avoid—to the extent possible—using mixed cases because variable names in JavaScript are case-sensitive; myCar and MyCar represent different variables.Reserved keywords that cannot be used as variable names (which are also known
as identifiers) are listed in section 11.2.6.1 of the ECMAScript 6 specification, which
is available in HTML format at 262/6.0/ and in PDF format at http://www.ecma-international.org/ecma-262/6.0/ECMA-262.pdf
Trang 13http://www.ecma-international.org/ecma-A variable can be declared and given a value in two separate steps, which are
displayed as follows:
var myTeam;
myTeam = 'Chicago Bulls';
They can also be given a value in a single step, as follows:
var myTeam = 'Chicago Bulls';
JavaScript allows us to declare variables without the var keyword (the variable will
be global) Anyway, this practice is not recommended, and most developers will advise against it and think that it should be deprecated
Then, this can be queried by simply calling the variable by name, as follows:
myTeam;
Then, this can be changed by assigning a different value, as follows:
myTeam = 'Indiana Pacers';
The preceding steps are illustrated in the following figure inside a Firefox developer
console (which can be accessed through the Ctrl + Shift + K key combination) If you use Google Chrome, you can access the Chrome developer tools with Ctrl + Shift + J
instead:
Initializing and calling variables
After typing the var myTeam = 'Chicago Bulls'; statement, as shown in the
preceding figure and pressing Enter, undefined is returned because an assignment does not produce a value On the other hand, when the value of myTeam is queried through an expression, its value is returned as a string type
Trang 14Also, mathematical expressions, such as 3*4;, produce a value, which is printed to the
console However, their result can be assigned to variables and used in operations later, as seen in the following figure:
Mathematical operations with variables
You can also concatenate the values of two or more variables of different types to form a new variable or produce new output using the + sign:
var sumResult = 'The sum of ' + firstNumber + ' and ' +
secondNumber + ' equals ' + sum;
sumResult;
When building a string variable as the result of the concatenation of two or more values, it is recommended that you be consistent with the use of single or double quotes Many JavaScript developers prefer to use double quotes to enclose string values as this allows you to use single quotes within the variable without the need
to escape them
While others prefer to use single quotes, the principle that should be followed is this:
if you need to use one form of quote in the string, you might want to use the other one as the literal
Trang 15These concepts are displayed in the following figure:
Using single and double quotes in string variables
In other words, you can perform the following:
var nickName1 = "I'm a programmer and my nickname is 'Geek' for that reason";
This can be used instead of the following:
var nickName2 = 'I\'m a programmer and my nickname is \'Geek\' for that reason';
Or, you can also use this:
var nickName3 = 'I\'m a programmer and my nickname is "Geek" for that reason';
The bottom line is: you pick your poison! Just don't forget to be consistent
Trang 16Arrays and objects
An array is a collection of values (different types are allowed) that can be saved into
a single variable This structure must be enclosed within square brackets and each element is referenced using a zero-based index notation For example, take a look
at the following:
var rockBands= ['The Beatles', 'Rolling Stones', 'Pink Floyd'];
As is the case with other variables, you can query the value of rockBands, as follows:
This example is illustrated in the following figure:
Initializing array variables and retrieving elements
Going one step further, you can easily create an object variable with properties Using this approach, you can think of an object as a thing For example, let's create an object variable named dog with three properties: color, age, and breed, as follows:
var dog= {color: 'Brown', age: 4, breed: 'Boxer'};
Trang 17You can then query the object variable as a whole or each property using the dot notation (the object name followed by a dot and the property name):
dog;
dog.color;
dog.age;
dog.breed;
Properties cannot only be fixed values, but they can also be methods that represent
an action that is associated with the object Using the dog object, let's redefine it and add a method property called bark:
var dog= {color: 'Brown', age: 4, breed: 'Boxer', bark: function() {console.log('Guau guau')}};
A method property can be invoked like a regular property as explained previously, and then followed by a set of parentheses that denote an action:
dog.bark();
This example is shown in the following figure:
Initializing and querying objects with properties and methods
Likewise, you can store HTML elements in object variables, as we will show you in the example near the end of this chapter
Conditionals and loops
In JavaScript, you can build a condition test using the usual if…else block and the identity operator (===) In the following example, we will use the console.log()method to display its parameter to the web console:
var myNumber = 4;
if (myNumber === 5) {
Trang 18console.log('The number is equal to five');
Using conditionals to control flow and loops to repeat actions
Trang 19Another way of displaying the same information is using a do while loop, which executes the indicated action as long as the condition in the while clause evaluates to true:
When we defined the dog object previously, we used a function as a method
property (bark) to indicate an action that is associated with the object Thus, you can think of a JavaScript function as a procedure that performs a task, manipulates variables, and calculates a result
A function declaration consists of the keyword function, followed by the name of the function, a list of optional arguments to be passed to the function (if there are more than one, they should be separated by commas), and a list of one or more JavaScript statements enclosed in curly brackets
For example, we can define a function named sum that takes two numbers
(firstNumber and secondNumber, to use the same variables as before) and returns the sum of these numbers Function naming is another area where effective developers use one pattern or another: some prefer to use all lowercase letters (for example, sum), while others like to use uppercase at the beginning of the name (Sum)
Again, either method works fine, but you are strongly advised to choose one and stick with it to avoid confusion down the road Either way, it would be a good idea
to check out http://www.w3schools.com/js/js_conventions.asp for current naming conventions
function sum(firstNumber,secondNumber) {
var mySum = firstNumber + secondNumber;
return 'The sum of ' + firstNumber + ' and ' + secondNumber + ' equals ' + mySum;
}
Trang 20Thus, we don't need to redefine firstNumber and secondNumber each time we want
to add two values We can just call the function with different arguments and that's all that there is to it, as seen in in the following figure:
Defining and calling functions
After reviewing the essential concepts of variables, operations, arrays, objects, conditionals, loops, and functions, we are ready to put it all together into libraries,
as we will explain next
The SayHi project requires 3 parameters: your name, age, and profession
(in that order)
Trang 21In the function definition, these three parameters are named a, b, and c.
The function returns a greeting using these values:
*/
function SayHi(a,b,c){
var person = {name: a, age: b, profession: c};
return 'My name is ' + person.name + ' and am ' + person.age + ' years old I am a ' + person.profession + '.';
}
/* Object definition
=================
The introducingMyself object is an object variable that gets the first h3 element
in the document This element has a property called textContent where we will display the result of calling SayHi with the following indicated parameters:
Trang 22Save both files and open index.html with your web browser To change the text inside the <h3> tags, simply pass different parameters to the SayHi function inside test.js and save the changes The result should be similar to the following figure:
In the real world, it is not practical to edit a JavaScript library each time you want
to change the content of a HTML element To do this, you would typically rely on HTML controls (such as text boxes and buttons) and use the JavaScript to handle things that require some form of logic The preceding example, while basic and not very useful, is effective to illustrate the way JavaScript statements can be saved into
a file that can be referenced and utilized on the HTML side
You can find the code for this example at https://github.com/gacanepa/
javascript-exercises Alternatively, this working example is available at
https://jsfiddle.net/gacanepa/0yswLco6/
Trang 23Getting Started with
ECMAScript 6
In the previous section, we reviewed the history of JavaScript and gave you a brief mind-refresher of several fundamental programming concepts as applied up until ECMAScript 5, the version which all web developers worldwide are familiar with and most web browsers are compatible with
As we also mentioned earlier, the latest specification of JavaScript is ECMAScript 6, which has new features and functionality In this section, we will explain what
these features are, and where and how you would like to consider using them in
an application After going through this section, you should also be able to write cleaner and more powerful JavaScript code—compared to previous versions of the language—to implement the same functionality
Before we dive into ECMAScript 6, it is important to check the compatibility of
our preferred web browser with the new features of the language In the following GitHub blog (http://kangax.github.io/compat-table/es6/), you will be able
to find a table that lists ECMAScript 6 features and compatibility with major modern web browsers
To perform the exercises and demonstrations in this section, you can
use any text editor that you feel comfortable with Notepad++ in
Windows and Gedit/Pluma in Linux are only some examples that we
will use here, but feel free to use something else Additionally, we can
use Codepen (http://codepen.io) or ES6 Fiddle (http://www.
es6fiddle.net/); both are online services that allow us to test the
code snippets we will present here—along with the Firefox web console,
as we did in the previous section Additionally, you can find the files
with the code in
https://github.com/gacanepa/javascript-exercises, and the complete working examples in these files
Trang 24That said, let's get started.
Template strings
Template strings introduce several features that solve limitations in regular
JavaScript strings For example, let's consider the case of a multiline string in
ECMAScript 5, which produces a SyntaxError: unterminated string
literal message when you execute it:
var greeting = "Hi! This
is a wonderful day, isn't it?";
To avoid this, in ECMAScript 5 you would use backslashes, as follows:
var greeting = "Hi! This \
is a wonderful day, isn't it?";
In ECMAScript 6, you can write much cleaner code:
var greeting = `Hi! This
is a wonderful day, isn't it?`;
Both methods are illustrated in the following figure:
Multiline strings in ECMAScript 5 and 6
Trang 25Another advantage of template strings consists of string interpolation (also known as
string substitution) What you would do with one or more string concatenations and
several objects with property methods, you can do more easily with template strings and substitution
For example, let's define an object variable named person, as follows:
var person = {name: "Gabriel", age: "33", profession: "developer", saySomething: function msg(d){return "This is my message: " + d}};
With ECMAScript 5, the following line returns a personal presentation:
console.log("My name is " + person.name + " and I'm a " +
person.profession + " " + person.saySomething("Happy Tuesday!"));
Whereas, in ECMAScript 6, template strings allow to output the same presentation with the following:
console.log(`My name is ${person.name} and I'm a
${person.profession} ${person.saySomething("Happy Tuesday!")}`);
This is much shorter and easier to read
The preceding example is shown with more clarity in the following figure:
Comparing regular string concatenation with template string substitution
Using Template strings, you can enclose any JavaScript expression inside ${}, not just variables For example, if you replace ${person.name} with ${person.name
toUpperCase()}, the person's name will be printed
in uppercase, as indicated by the toUpperCase() JavaScript function
Trang 26Tagged templates
Tagged templates represent an advanced form of template strings as they can tell the difference between literals and values resulting from an operation or a JavaScript expression, as shown earlier In other words, tagged templates allow us to take different actions on literals and values An example will help us illustrate this feature
In the following code snippet, namesToUpper is a function that is applied to the template between backticks The function definition takes two arrays (stringsand values) as parameters, which contain the literals and the values found in the template, respectively:
function namesToUpper(strings, values) {
return strings.reduce(function test(a, b, c) {
return ${a}${values[c - 1].toUpperCase()}${b};
})
}
var fName = "Gabriel";
var mName = "Alejandro";
var lName = "Cánepa";
console.log(namesToUpper `First Name: ${fName}, Middle Name:
${mName}, Last Name: ${lName}`);
If you replace the return lines with two console.log() calls (one for each array), the output should be shown in the following figure:
Applying a function to a tagged template
Trang 27We can now use template strings to build a return value as per the code snippet that
we shared earlier Note how, in the following figure, only the elements in the valuesarray are converted to uppercase
Using tagged templates
In simple words, you can use tagged templates in any situation where you need to follow different courses of action on literals and associated values For example, you can use tagged templates to sanitize input from a form In this situation you certainly want to prevent special characters from being passed to the backend application in
order to avoid a SQL injection or a cross-side scripting (XSS) attack.
Arrow functions
With arrow functions, you can obtain the same functionality as regular function expressions but with shorter syntax Additionally, arrow functions inherit the thisvalue from the enclosing context so that you don't need to use an extra variable to pass an object from a parent function to an enclosed method
To replace a regular function with an arrow method, enclose its parameters inside parentheses and append the arrow notation (=>) followed by the JavaScript extension inside curly brackets In either case (parameter listing or expression definition), the parentheses or curly brackets can be omitted if there is only one parameter or if the expression consists of only one line
With that in mind, let's rewrite the namesToUpper() function that we used earlier:
function namesToUpper(strings, values) {
return strings.reduce((a, b, c) => {
return `${a}${values[c - 1].toUpperCase()}${b}`;
})
Trang 28var fName = "Gabriel";
var mName = "Alejandro";
var lName = "Cánepa";
console.log(namesToUpper `First Name: ${fName}, Middle Name:
${mName}, Last Name: ${lName}`);
As you can see in the following figure, the code still works as expected:
Using arrow functions to replace regular methods
For another example, let's define a Counter object and increment its value (starting at
0) by one each second until it reaches 5:
var p = new Counter();
Using arrow functions, this.value inside setInterval still refers to the Counterobject Without arrow functions, this would switch to the global window object This can be observed using the following code snippet:
function Counter(){
Trang 29var timer = setTimeout(function test() {
console.log(this);
}, 1000);
}
var p = new Counter();
The comparison between these two approaches (arrow functions versus regular functions) and their corresponding effects on this inside a child method, is shown
in the following figure:
Scope of this using arrow functions vs regular methods
As you can see, arrow functions simplify the code syntax, makes it much more readable, and provide the same functionality with fewer lines
Trang 30Folks who are familiar with Object-Oriented Programming (OOP) have welcomed
this feature with open arms Similarly to other programming languages, with
ECMAScript 6, you can now create objects with properties and methods using the class keyword This results, again, in code that is cleaner and easier to maintain ECMAScript 6 does this without creating a new OOP model in the language, but uses a clearer syntax to handle objects and inheritance
Up until ECMAScript 5, here's an example of what you would do to instantiate an object of the individual type and to print a message to the console:
var individual = function Person(fName, lName, profession, age) { // Properties
The preceding code snippet gets the job done However, let's see how we can
improve the code using a JavaScript class and other ECMAScript 6-specific features that we have discussed previously:
Trang 31Both alternatives return the output shown in the following figure, but using classes helps us write better and more understandable code:
Using classes to create objects
Another advantage that is associated with using classes to create and instantiate objects is that we can also inherit from parent classes that may have some more generic methods and properties Building upon our previous example, let's add
a parent (also known as base) class named Employee with two generic properties (hireDate and monthlySalary):
Trang 32Properties available in Employee are made available to a Person object using the super() function inside the constructor call In addition to this, methods in the parent class are available directly to the child object In the following case, our Person child class will inherit hireDate, monthlySalary, and getMonthlySalary()(two properties and a method in the Employees class, respectively):
class Person extends Employee {
constructor(fName, lName, profession, age, hireDate,
Trang 33As you can see in the preceding example, to invoke a class, we need to use the newkeyword We do not do this directly as you would do with a function object in ECMAScript 5 (Person()).
The let keyword
Similarly to var, the let keyword can be used to instantiate new variables However, when the let keyword is used inside a block within a function, the new variable is only available inside such a block Let's illustrate this with the following example:
guessName();
function guessName() {
var sayName = "John Doe";
if (sayName === "John Doe") {
let msg = `the name is ${sayName}`