Tải bản đầy đủ (.pdf) (66 trang)

What you need to know about javascript delve into the fundamentals of javascript

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (9.81 MB, 66 trang )


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

/>
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
1
5
6
8
9

Getting Started with ECMAScript 6

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 do 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 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

[ iii ]


Preface

Overview
In 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.
[ iv ]


What you need to know about JavaScript

What 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 and in PDF format at />
[1]


What you need to know about JavaScript

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.

[2]


What you need to know about JavaScript


Also, 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.

[3]


What you need to know about JavaScript

These 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.

[4]


What you need to know about JavaScript

Arrays 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:
rockBands;


Additionally, you can retrieve the value of a specific item in rockBands like
the following:
rockBands[0];

Or, you can also use the following:
rockBands[2];

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'};

[5]


What you need to know about JavaScript

You 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) {
[6]


What you need to know about JavaScript
console.log('The number is equal to five');
}
else {
console.log('The number is NOT equal to five');

}

To illustrate a basic for loop, let's consider the rockBands array variable used
earlier, as follows:
for (var i = 0; i < rockBands.length; i++) {
console.log('Band #' + i + ' is ' + rockBands[i]);
}

In the preceding example, we iterate over the rockBands array using the i number
variable as an index. Finally, we send a different line to the web console in each
iteration. The result is shown in the following figure:

Using conditionals to control flow and loops to repeat actions

[7]


What you need to know about JavaScript

Another 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:
var i = 0;
do {
console.log('Band #' + i + ' is ' + rockBands[i]);
i++;
} while (i < rockBands.length);

You will use conditionals and loops in your JavaScript programs when you need to
take decisions that are based on the values of variables and when you need to repeat

a similar action a given number of times, respectively. Objects will come in handy
when you need to define complex structures with properties and methods instead
of mere lists of items (for which you will want to use an array variable).

Functions

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 for current
naming conventions.
function sum(firstNumber,secondNumber) {
var mySum = firstNumber + secondNumber;
return 'The sum of ' + firstNumber + ' and ' + secondNumber + '
equals ' + mySum;
}
[8]



What you need to know about JavaScript

Thus, 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.

Libraries

In order to provide more complex functionality with little extra effort, you can
combine JavaScript statements and functions into a single file that is invoked in
a web page. These files use the .js (for JavaScript) extension, and they are called
libraries.
Although there are several popular JavaScript libraries (such as jQuery, ReactJS,
and the Dojo Toolkit to name a few examples), you can write your own! Let's see
how to do this.
Save the following code into a file named test.js:
/* Function declaration
====================

The SayHi project requires 3 parameters: your name, age, and profession
(in that order).

[9]



What you need to know about JavaScript

In 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:
*/
var introducingMyself = document.querySelector('h3');
introducingMyself.textContent = SayHi('Gabriel', 33,
'programmer');

We will then create a file named index.html in the same directory where you saved
test.js. Note that, in order to reference the external file test.js, you need to place
the reference inside <script> tags as indicated in the following:
<!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">

<title>Chapter 1</title>
</head>
<body>

First example



<script src="test.js"></script>
</body>
</html>

Some developers place the reference to the .js file inside the head section so that
any function in this file would be available before the document finishes loading,
while others prefer to place it right before the closing </body> tag to favor load
speeds. Although this is a matter of personal preference, the former method is the
recommended practice.

[ 10 ]


What you need to know about JavaScript

Save both files and open index.html with your web browser. To change the text
inside the

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 />javascript-exercises. Alternatively, this working example is available at
/>
[ 11 ]


What you need to know about JavaScript

Getting 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 ( 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 () 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 and the complete working examples in these files.
[ 12 ]


What you need to know about JavaScript

That 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


[ 13 ]


What you need to know about JavaScript

Another 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.

[ 14 ]


×