Вы находитесь на странице: 1из 82

Unit 2

Emerging JavaScript
Contents

• Introduction
• Declaring Variables in ES6
• Arrow Function
• Transpiling ES6
• Objects and Arrays
• Promises
• Classes
• ES6 Modules
Introduction
• ECMAScript (ES) / ES6 is a scripting language specification
standardized by ECMAScript International.
• Used by applications to enable client-side scripting.
Languages like JavaScript, Jscript and ActionScript are
governed
• Since its release in 1995, JavaScript has gone through many
changes.
– Adding interactive elements to web pages much simpler
– Robust with DHTML and AJAX
– Node.js, JavaScript has become a language that is used to build full-
stack applications.
– The committee that is and has been in charge of shepherding the
changes to JavaScript is the European Computer Manufacturers
Association (ECMA).
• Changes to the language are community-driven by this
specification.
Setting Up ES6 Environment
• Install node.js
• Visual Studio Code
ES6 Syntax
• Syntax defines the set of rules for writing programs.
Every language specification defines its own syntax.
• A JavaScript program can be composed of −
– Variables − Represents a named memory block that can store values
for the program.
– Literals − Represents constant/fixed values.
– Operators − Symbols that define how the operands will be processed.
– Keywords − Words that have a special meaning in the context of a
language.
• Modules − Represents code blocks that can be reused across
different programs/scripts.
• Comments − Used to improve code readability. These are ignored
by the JavaScript engine.
• Identifiers − These are the names given to elements in a program
like variables, functions, etc. The rules for identifiers are −
– Identifiers can include both, characters and digits. However, the
identifier cannot begin with a digit.
– Identifiers cannot include special symbols except for underscore (_) or a
dollar sign ($).
– Identifiers cannot be keywords. They must be unique.
– Identifiers are case sensitive. Identifiers cannot contain spaces.
• Whitespace and Line Breaks
– ES6 ignores spaces, tabs, and newlines that appear in programs. You
can use spaces, tabs, and newlines freely in your program and you are
free to format and indent your programs in a neat and consistent way
that makes the code easy to read and understand .
• JavaScript is Case-sensitive
– JavaScript is case-sensitive. This means that JavaScript differentiates between
the uppercase and the lowercase characters.
• Semicolons are Optional
– Each line of instruction is called a statement. Semicolons are optional
in JavaScript.
Sample Code
• console.log("hello world")
• console.log("We are learning ES6")
– A single line can contain multiple statements.
– However, these statements must be separated
by a semicolon.
Comments in JavaScript

• Comments are a way to improve the readability of a program.


Comments can be used to include additional information about a
program like the author of the code, hints about a
function/construct, etc.
• Comments are ignored by the compiler.
• JavaScript supports the following types of comments −
– Single-line comments (//) − Any text between a // and the end of a line is
treated as a comment.
– Multi-line comments (/* */) − These comments may span multiple lines.
• Example
– //this is single line comment
– /* This is a Multi-line comment */
Your First JavaScript Code

• Let us start with the traditional “Hello World” example".


– var message = "Hello World“
– Consol
• The program can be analysed as −
– Line 1 declares a variable by the name message.
– Variables are a mechanism to store values in a program.
– Line 2 prints the variable’s value to the prompt.
– Here, the console refers to the terminal window.
– The function log () is used to display the text on the screen.
Executing the Code

• We shall use Node.js to execute our code.


• Step 1 − Save the file as Test.js
• Step 2 − Right-click the Test.js file under the working files option in
the project-explorer window of the Visual Studio Code.
• Step 3 − Select Open in Command Prompt option.
• Step 4 − Type the following command in Node’s terminal window.
• node Test.js The following output is displayed on successful
execution of the file.
– Hello World
ES6 Variables
• A variable, by definition, is “a named space in the memory” that
stores values. In other words, it acts as a container for values in a
program. Variable names are called identifiers.
• Following are the naming rules for an identifier−
– Identifiers cannot be keywords.
– Identifiers can contain alphabets and numbers.
– Identifiers cannot contain spaces and special characters, except the
underscore (_) and the dollar ($) sign.
– Variable names cannot begin with a number.
Type Syntax

• A variable must be declared before it is used.


• ES5 syntax used the var keyword to achieve the
same.
• The ES5 syntax for declaring a variable is as
follows.
• //Declaration using var keyword
– var variable_name
– Eg: var name = "Tom"
console.log("The value in the variable is: "+name)
ES6 declaration
• ES6 introduces the following variable
declaration syntax −
– Using the const
– Using the let
• Variable initialization refers to the process of storing
a value in the variable.
• A variable may be initialized either at the time of its
declaration or at a later point in time.
const

• A constant is a variable that cannot be changed.


• Like other languages had done before it, JavaScript
introduced constants with ES6.
• Before constants, all we had were variables, and variables
could be overwritten:
– var pizza = true
– pizza = false
– console.log(pizza)
– ES6 defintion using const
• const pizza = true
• pizza = false
• console.log(pizza);
– Will throw an error (check it in lab session);
Variable Scope
• Before we understand let, let us understand the
concepts of dynamic typing and scoping of variables
• JavaScript and Dynamic Typing
– JavaScript is an un-typed language.
– This means that a JavaScript variable can hold a value of any
data type.
– Unlike many other languages, you don't have to tell JavaScript
during variable declaration what type of value the variable will
hold.
– The value type of a variable can change during the execution of a
program and JavaScript takes care of it automatically. This
feature is termed as dynamic typing.
JavaScript Variable Scope
• The scope of a variable is the region of your program in
which it is defined.
– Traditionally, JavaScript defines only two scopes-global and local.
• Global Scope − A variable with global scope can be accessed from
within any part of the JavaScript code.
• Local Scope − A variable with a local scope can be accessed from
within a function where it is declared.
• The following example declares two variables by the
name num - one outside the function (global scope) and the
other within the function (local scope).
var num = 10
function test()
{
var num = 100
console.log("value of num in test() "+num)
}
console.log("value of num outside test() "+num)
test()
• The following output is displayed on successful execution.
–value of num outside test() 10
–value of num in test() 100
• ES6 defines a new variable scope - The Block scope.
let
• JavaScript now has lexical variable scoping.
• In JavaScript, we create code blocks with curly braces ({}).
• With functions, these curly braces block off the scope of variables.
• On the other hand, think about if/else statements.
• If you’re coming from other languages, you might assume that these blocks
would also block variable scope. This is not the case.
• If a variable is created inside of an if/else block, that variable is not scoped to
the
• block:
– var topic = "JavaScript"
– if (topic) {
– var topic = "React"
– console.log('block', topic) // block React
– }
• The Let and Block Scope
function test()
{ var num = 100
console.log("value of num in test() "+num)
{ console.log("Inner Block begins")
let num = 200
console.log("value of num : "+num)
}
} test()
• The block scope restricts a variable’s access to the block in which it
is declared.
• The var keyword assigns a function scope to the variable.
• Unlike the var keyword, the let keyword allows the script to restrict
access to the variable to the nearest enclosing block.
Variable Hoisting

• The scope of a variable declared with var is its current


execution context, which is either the enclosing function or, for
variables declared outside any function, global.
• Variable hoisting allows the use of a variable in a JavaScript
program, even before it is declared.
var main = function()
{
for(var x = 0;x<5;x++)
{ console.log(x);
}
console.log("x can be accessed outside the block scope x value is :"+x); console.log('x is
hoisted to the function scope');
}
main();
The const

• The const declaration creates a read-only reference to a value.


• It does not mean the value it holds is immutable, just that the
variable identifier cannot be reassigned.
• Constants are block-scoped, much like variables defined using the
let statement.
• The value of a constant cannot change through re-assignment, and it
can't be re-declared.
• The following rules hold true for a variable declared using
the const keyword −
– Constants cannot be reassigned a value.
– A constant cannot be re-declared.
– A constant requires an initializer. This means constants must be initialized during
its declaration.
• Functions 
Functions
– They are the building blocks of readable, maintainable,
and reusable code.
– Functions are defined using the function keyword.
– Following is the syntax for defining a standard function.
function function_name()
{ // function body }
– To force execution of the function, it must be
called. This is called as function invocation.
Following is the syntax to invoke a function.
function_name()
Classification of Functions

– Functions may be classified as


• Returning and Parameterized functions.
Returning functions

• Functions may also return the value along with control, back to the
caller.
– Such functions are called as returning functions.
• Following is the syntax for the returning function.
function function_name()
{
//statements return value;
}
– A returning function must end with a return statement.
– A function can return at the most one value. In other words,
there can be only one return statement per function.
– The return statement should be the last statement in the
function.
• Functions may also return the value along with control, back to the
caller.
– Such functions are called as returning functions.
• Following is the syntax for the returning function.
function function_name()
{
//statements return value;
}
– A returning function must end with a return statement.
– A function can return at the most one value. In other words,
there can be only one return statement per function.
– The return statement should be the last statement in the
function.
Parameterized functions
• Parameters are a mechanism to pass values to functions.
• Parameters form a part of the function’s signature.
• The parameter values are passed to the function during its
invocation.
• Unless explicitly specified, the number of values passed to a function
must match the number of parameters defined.
function function_name(parameter1, paramerter2,…)
{
}
Template Strings
• Template strings provide us with an alternative to string
concatenation.
• They allow us to insert variables into a string.
• Traditional string concatenation uses plus sign to compose
a string using variable values and strings:
– console.log(lastName + ", " + firstName + " " +
middleName)
– With a template, we can create one string and insert the variable values by
surrounding them with ${ }:

– console.log(`${lastName}, ${firstName} ${middleName}`)


• Any JavaScript that returns a value can be added to a template
string between the $ { } in a template string.
• Template strings honor whitespace, making it easier to draft up
email templates, code examples, or anything else that contains
whitespace.
• Now you can have a string that spans multiple lines without
breaking your code
Template Literals
• Template literals are the string with embedded code and
variables inside.
• Template literal allows concatenation and interpolation in much
more comprehensive and clear in comparison with prior versions of
ECMAScript.
• Let see an example of concatenating a string in JavaScript.
– var a="Hello";
– var b="John";
– var c = a+ " " + b;
– console.log(c); //outputs Hello John;
– In ES6 concatenation and interpolation is done by backtick` in a single line.
– To interpolate a variable simply put in to {} braces forwarded by $ sign.>/p>
// In ES6
let a="Hello";
let b="John";
let c=`${a} ${b}`;
console.log(c); //outputs Hello John;
Default Parameters
• Languages including C++ and Python allow developers to
declare default values for function arguments.
– Default parameters are included in the ES6 spec, so in the event
that a value is not provided for the argument, the default value will
be used.
function logActivity(name="Shane McConkey", activity="skiing")
{
console.log( `${name} loves ${activity}` )
}
Arrow Functions
• Arrow functions are a useful new feature of ES6.
• With arrow functions:
– you can create functions without using the function keyword.
– do not have to use the return keyword.
– have an entire function declaration on one line.
– remove return because the arrow points to what should be returned.
– if the function only takes one argument, we can remove the
parentheses around the arguments.
var = birthday = function()
{
return “Happy Birthday”
}
ES6 method of defining arrow function
var birthday =()=>”Happy Birthday”
console.log(birthday))
var birthday = ( age, name ) =>
{
return "Happy " + age + "th birthday, " + name + "!"
};
console.log( birthday( 34, "James" ) ); // Happy 34th birthday, James!
Coding for Browser
Compatibility..
Notion of Transpiling and Bable
• What is Transpiling?
• Not all web browsers support ES6, and even those
that do don’t support everything.
• The only way to be sure that your ES6 code will
work is to convert it to ES5 code before running it
in the browser.
• This process is called transpiling.
Transpiling ES6
– One of the most popular tools for transpiling is Babel.
– In the past, the only way to use the latest JavaScript features was to wait
weeks, months, or even years until browsers supported them.
– Now, transpiling has made it possible to use the latest features of
JavaScript right away.
– The transpiling step makes JavaScript similar to other languages.
– Transpiling is not compiling: our code isn’t compiled to binary.
– Instead, it’s transpiled into syntax that can be interpreted by a wider range
of browsers.
– Also, JavaScript now has source code, meaning that there will be some files
that belong to your project that don’t run in the browser.
• Transpiling simply means taking out ES6 code and
converting it into ES5 so it can be read by all browsers —
like a safety precaution!
• There are many transpiling tools, the most popular are
also the ones that support the most ES6 features:
– Babel.js
– Closure
– Traceur
– You can use any off these, but out of the three listed, but Babel is
most recommended for smaller projects.
– Please follow their simple steps for installing Babel into your
project via Node: https://babeljs.io/
Additional information
• For larger projects webpack is recommended.
• Webpack does a lot of complicated things:
– transpiling code
– SAS conversions
– dependency management
– replacing tools such as Grunt, Gulp and Browserify. 
BABLE HOME PAGE
• Consider the following example which is a ES6
code before transpiling
– const add = (x=5, y=10) => console.log(x+y);
– After Transpiling:
"use strict";
var add = function add()
{
var x = arguments.length <= 0 || arguments[0] === undefined ? 5 :
arguments[0];
var y = arguments.length <= 1 || arguments[1] === undefined ? 10 :
arguments[1];
return console.log(x + y);
};
ES6 Objects and Arrays

• ES6 gives us new ways for working with objects and arrays and for
scoping the variables within these datasets.
• These features include
– Destructuring
– Object literal enhancement
– Spread operator
Destructuring Assignment
• The destructuring assignment allows you to locally scope fields
within an object and to declare which values will be used.
var sandwich =
{
bread: “soft",
cheese: “cheddar",
toppings: [“cucumber", "tomato", “pineapple"]
}
var {bread, cheese} = sandwich
console.log(bread, cheese)
The above shown code pulls bread and cheese out of the object and creates
local variables for them.
We can also change the values of the sandwich
structure:
var {bread, cheese} = sandwich
bread = "garlic"
cheese = “cottage cheese"
console.log(sandwich.bread, sandwich.cheese)
•Destructuring is also more declarative, meaning that our code
is more descriptive about what we are trying to accomplish
• We can also destructure incoming function arguments.
Consider this function that would log a person’s name as a
lord:
var lordify = regularPerson =>
{
console.log(`${regularPerson.firstname} of Canterbury`)
}
var regularPerson =
{ firstname: "Bill", lastname: "Wilson“ }
lordify(regularPerson)
• Instead of using dot notation syntax to dig into objects, we can
destructure the values that we need out of regularPerson:
var lordify =
({firstname}) =>
{ console.log(`${firstname} of Canterbury`) }
lordify(regularPerson)

• Values can also be destructured from arrays.


• Imagine that we wanted to assign the first value of an array to a
variable name:
var [firstResort] = ["Kirkwood", "Squaw", "Alpine"]
console.log(firstResort)
• We can also pass over unnecessary values with list
matching using commas.
• List matching occurs when commas take the place of
elements that should be skipped.
• With the same array, we can access the last value by
replacing the first two values with commas:
var [,,thirdResort] = ["Kirkwood", "Squaw", "Alpine"]
console.log(thirdResort) // Alpine
Object Literal Enhancement
• Object literal enhancement is the opposite of destructuring.
• It is the process of restructuring or putting back together.
• With object literal enhancement, we can grab variables
from the global scope and turn them into an object:
var name = "Tallac"
var elevation = 9738
var funHike = {name,elevation}
console.log(funHike) // {name: "Tallac", elevation: 9738}
–name and elevation are now keys of the funHike object.
• We can also create object methods with object literal
enhancement or restructuring:
var name = “Mt. Everest"
var elevation = 8848
var print = function()
{
console.log(`Mt. ${this.name} is ${this.elevation} feet tall`)
}
var funHike = {name, elevation, print}
funHike.print() // Mt. Everest is 8848 m tall
Notice we use this to access the object keys.
Defining function without function key word
const skier = { name, sound,
powderYell() {
let yell = this.sound.toUpperCase()
console.log(`${yell} ${yell} ${yell}!!!`)
},
speed(mph) {
this.speed = mph
console.log('speed:', mph)
}
}
• Object literal enhancement allows us to pull global variables into objects and
reduces typing by making the function keyword unnecessaryily
The Spread Operator
• The spread operator is three dots (...) performs several
different tasks.
• First, the spread operator allows us to combine the contents
of arrays
• For example, if we had two arrays, we could make a third
array that combines the two arrays into one:
var peaks = ["Tallac", "Ralston", "Rose"]
var canyons = ["Ward", "Blackwood"]
var tahoe = [...peaks, ...canyons]
console.log(tahoe.join(', ')) // Tallac, Ralston, Rose, Ward,
Blackwood
All of the items from peaks and canyons are pushed into a new array
called tahoe.
• What if I want the last item of the array to be the first item?
– Let’s take a look at how the spread operator can help us deal
with a problem.
– Using the peaks array from the previous sample, let’s
imagine that we wanted to grab the last item from the array
rather than the first.
– We could use the Array.reverse method to reverse the array
in combination with array destructuring:
var peaks = ["Tallac", "Ralston", "Rose"]
var [last] = peaks.reverse()
console.log(last) // Rose
console.log(peaks.join(', ')) // Rose, Ralston, Tallac
• The reverse function has actually altered or
mutated the array.
• But we do not want this every time!
• How to solve this problem?
– In a world with the spread operator, we don’t have to mutate the
original array;
– We can create a copy of the array and then reverse it:
• var peaks = ["Tallac", "Ralston", "Rose"]
• var [last] = [...peaks].reverse()
• console.log(last) // Rose
• console.log(peaks.join(', ')) // Tallac, Ralston, Rose
– Since we used the spread operator to copy the array, the peaks array is
still intact and can be used later in its original form.
Other uses of spread
• The spread operator can also be used to get some, or
the rest, of the items in the array:
var lakes = ["uttarahalli", "sankey", "yediyur"]
var [first, ...rest] = lakes
console.log(lakes)
console.log(rest.join(“: "))
Other uses of spread
• The spread operator can also be used for objects.
• Using the spread operator with objects is similar to using it with arrays.
• In this example, we’ll use it the same way we combined two arrays into
a third array, but instead of arrays, we’ll use objects:
var morning = Output:
{ {
breakfast: “idli", breakfast: 'idli',
lunch: “chapatti, dal and rice"
lunch: 'chapatti, dal and rice',
}
dinner: 'rice and sambar'
var dinner = “rice and sambar“
var backpackingMeals =
}
{
...morning,
dinner
}
console.log(backpackingMeals)
Promises
• Promises give us a way to make sense out of asynchronous behavior.
• When making an asynchronous request, one of two things can happen:
– everything goes as we hope
– or
– there’s an error.
• There may be several different types of successful or unsuccessful
requests.
• For example, we could try several ways to obtain the data to reach
success.
• We could also receive multiple types of errors.
• Promises give us a way to simplify back to a simple pass or fail.
• We need to understand the concept of callback
• Asynchronous call
Objects
• JavaScript supports extending data types.
• JavaScript objects are a great way to define custom
data types.
• An object is an instance which contains a set of
key value pairs.
– Unlike primitive data types, objects can represent
multiple or complex values and can change over
their life time.
– The values can be scalar values or functions or even array
of other objects.
Syntax of the object
• Object Initializers
– Like the primitive types, objects have a literal
syntax:
–  curly braces ({and})
– Following is the syntax for defining an object.
var identifier =
{ Key1:value,
Key2: function () { //functions },
Key3: [“content1”,” content2”]
}
• Example: Object Initializers
var person =
{ firstname:"Tom",
lastname:"Hanks",
func:function(){return "Hello!!"},
};
//access the object values
console.log(person.firstname)
console.log(person.lastname)
console.log(person.func())
• The Object() Constructor
– JavaScript provides a special constructor function
called Object() to build the object.
– The new operator is used to create an instance of an
object.
– To create an object, the new operator is followed by
the constructor method.
• Following is the syntax for defining an
object.
var obj_name = new Object();
obj_name.property = value;
OR
obj_name["key"] = value
Example
var myCar = new Object()
myCar.make = "Ford" //define an object
myCar.model = “Ecosport”
myCar.year = 2019
console.log(myCar["make"]) //access the object property
console.log(myCar["model"])
console.log(myCar["year"])
• Note:
var myCar = new Object();
myCar.make = "Ford";
console.log(myCar["model"])

What is the output?


Unassigned properties of an object are undefined.
Classes
• Previously in JavaScript, there were no official classes.
• Types were defined by functions.
• We had to create a function and then define methods on the
function object using the prototype:
function Vacation(destination, length) {
this.destination = destination
this.length = length }
Vacation.prototype.print = function() {
console.log(this.destination + " | " + this.length + " days")
}
Creating instance of the class
var trip = new Vacation(« Singapore", 7)
trip.print() // Singapore | 7 days
• Note: The rule of thumb with capitalization is that all types should be
capitalized. Thus all class names are capitalized
Class Declaration in ES6
• ES6 introduces class declaration, but JavaScript still works the same
way.
• Functions are objects, and inheritance is handled through the
prototype, but this syntax makes more sense if you come from classical
object orientation:
class Vacation
{
constructor(destination, length)
{
this.destination = destination
this.length = length
}
print() {
console.log(`${this.destination} will take ${this.length} days.`) }
}
Creating instance of the class
• Create a new instance of the class using the
new keyword.
• Then you can call the custom method on the
class:
const trip = new Vacation("Santiago, Chile", 7)
trip.print() // Santiago, Chile will take 7 days.
function Vacation(destination, length) { Output
    this.destination = destination Santiago, Chile | 7 days
    this.length = length }
    Vacation.prototype.print = function() {
    console.log(this.destination + " | " + this.length 
+ " days")
    }
    
const trip = new Vacation("Santiago, Chile", 7)
trip.print() 
• Syntax for creating class
class class_name { }
Eg: class Polygon
{
constructor(height, width)
{
this.height = height;
this.width = width;
}
}
var obj = new Polygon(10,12)
Extending the class
• Classes can also be extended.
• When a class is extended, the subclass inherits the
properties and methods of the superclass.
• These properties and methods can be manipulated from
here, but as a default, all will be inherited.
• You can use Vacation as an abstract class to create
different types of vacations.
• For instance, an Expedition can extend the Vacation
class to include gear:
class Expedition extends Vacation {
constructor(destination, length, gear)
{
super(destination, length)
this.gear = gear
}
print() {
super.print()
console.log(`Bring your ${this.gear.join(" and your ")}`)
}
}
• Creating a new instance works the exact same way—
create a variable and use the new keyword:
const trip = new Expedition("Mt. Whitney", 3,
["sunglasses", "prayer flags", "camera"])
trip.print()

// Mt. Whitney will take 3 days.


// Bring your sunglasses and your prayer flags and your camera)
ES6 Modules
• What is a Module?
• A JavaScript module is a piece of reusable code that can
easily be incorporated into other JavaScript files.
• A module is nothing more than a chunk of JavaScript code
written in a file.
• The functions or variables in a module are not available for
use, unless the module file exports them
• JavaScript modules are stored in separate files, one file per
module.
• In simpler terms, the modules help you to write the code in
your module and expose only those parts of the code that
should be accessed by other parts of your code
• There are two options when creating and
exporting a module:
• you can export multiple JavaScript objects from a single
module
OR
• one JavaScript object per module.
Additional information
• ES6 modules is a very powerful concept.
• Although support is not available everywhere yet, you
can play with ES6 code today and transpile into ES5.
• You can use Grunt, Gulp, Babel or some other transpiler
to compile the modules during a build process
Exporting a Module
• To make available certain parts of the module, use the
export keyword.
• Following is the syntax to export a module.
• Export a single value or element - Use export default
• Syntax:
– export default element_name
• Export multiple values or elements
• Syntax:
– export {element_name1,element_name2,....}
• Let us consider a file helper.js from which two JavaScript
are exported:
• export const print(message) => log(message, new Date())
• export const log(message, timestamp) => console.log(`$
{timestamp.toString()}: ${message}`)
– export can be used to export any JavaScript type that will be consumed in another
module.
– In this example the print function and log function are being exported.
– Any other variables declared in text-helpers.js will be local to that module.
– You may also export a default variable
– Both export and export default can be used on any JavaScript type:
primitives, objects, arrays, and functions.
• You may also import modules using the
import statement.
– import { print, log } from './text-helpers'
import freel from './mt-freel'
• CommonJS
• CommonJS is the module pattern that is supported by all versions of
Node.js.
• You can still use these modules with Babel and webpack.