0% found this document useful (0 votes)
12 views

Advanced Javascript: Arrow Functions, Template Literals, Array Destructing

bootstrap

Uploaded by

rahulnakka74
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Advanced Javascript: Arrow Functions, Template Literals, Array Destructing

bootstrap

Uploaded by

rahulnakka74
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

GMR Institute of Technology

GMRIT/ADM/F-44
Rajam, Andhra Pradesh
REV.: 00
(An Autonomous Institution Affiliated to JNTUGV, AP)

Cohesive Teaching – Learning Practices (CTLP)


Class 4th Sem. – B. Tech Department: CSE
Course
Course Web Coding and Development 21CS405
Code
Prepared by Mr. Gangu Dharmaraju
Advanced JavaScript: Arrow functions, Template Literals, Array Destructing,
Lecture Topic
Object Destructing, Classes and Modules – ES6 imports and exports
Course Outcome (s) CO2, CO3 Program Outcome (s) PO1, PO2 , PSO2
Duration 1 Hr Lecture 6 to 12 Unit II
Pre-requisite (s) Knowledge of Basic Programming and Basic JavaScript Concepts

❖ Objective

❖ Apply dynamic effects and validations using JavaScript skills to real-world projects
❖ Demonstrating the ability to build interactive and dynamic web applications

❖ Intended Learning Outcomes (ILOs)

At the end of this session the students will able to:

A. Understand the basic syntax and structure of JavaScript program


B. Define and call functions with parameters and return values
C. Create and manipulate arrays using array methods (e.g., push, pop, splice).
D. Access and modify HTML elements using the Document Object Model (DOM).
E. Use ES6 features such as arrow functions, template literals, and destructuring.

❖ 2D Mapping of ILOs with Knowledge Dimension and Cognitive Learning Levels of


RBT

Cognitive Learning Levels


Knowledge
Remember Understand Apply Analyse Evaluate Create
Dimension
Factual
Conceptual B A C
Procedural D E
Meta Cognitive

GMRIT, Rajam, Andhra Pradesh


❖ Teaching Methodology

❖ Chalk & Board, Visual Presentation

❖ Evocation

❖ Deliverables
Lecture - 6
➢ Arrow functions
❖ Arrow function {()=>} is concise way of writing JavaScript functions in shorter way.
Arrow functions were introduced in the ES6 version. They make our code more
structured and readable.
❖ Arrow functions are anonymous functions i.e. functions without a name but they
are often assigned to any variable. They are also called Lambda Functions.
❖ Example
o Arrow Function without Parameters
hello = () => {
return "Hello World!";
}
Result:
Hello World!

o Arrow Function with Parameters


let add = ( x, y, z ) => {
console.log( x + y + z )
}

add( 10, 20, 30 );


Result:
60
o Arrow Function with Default Parameters
let values = ( x, y, z = 30 ) => {
console.log( x + " " + y + " " + z);
}

values( 10, 20 );
Result:
GMRIT, Rajam, Andhra Pradesh
10 20 30
o Arrow functions can be async by prefixing the expression with the async
keyword.
async param => expression
async (param1, param2, ...paramN) => {
statements
}
o Advantages of Arrow Functions
- Arrow functions reduce the size of the code.
- The return statement and function brackets are optional for single-line
functions.
- It increases the readability of the code.
- Arrow functions provide a lexical this binding. It means, they inherit the
value of “this” from the enclosing scope. This feature can be advantageous
when dealing with event listeners or callback functions where the value of
“this” can be uncertain.
o Limitations of Arrow Functions
- Arrow functions do not have the prototype property.
- Arrow functions cannot be used with the new keyword.
- Arrow functions cannot be used as constructors.
- These functions are anonymous and it is hard to debug the code.
- Arrow functions cannot be used as generator functions that use the yield
keyword to return multiple values over time.
Lecture - 7
➢ Template Literals (Template Strings)
❖ Template literals (template strings) allow you to use strings or embedded
expressions in the form of a string. They are enclosed in backticks ``. For example,
const name = 'Jack';
console.log(`Hello ${name}!`); // Hello Jack!
➢ Array Destructing
❖ Destructuring means to break down a complex structure into simpler parts. With
the syntax of destructuring, you can extract smaller fragments from objects and
arrays. It can be used for assignments and declaration of a variable.
❖ Destructuring is an efficient way to extract multiple values from data that is stored
in arrays or objects. When destructuring an array, we use their positions (or index)
in an assignment.
❖ Let us try to understand the array destructuring by using some illustrations:
var arr = ["Hello", "World"]
// destructuring assignment
var [first, second] = arr;
console.log(first); // Hello
console.log(second); // World
Result:
Hello
World
❖ By using the rest operator (…) in array destructuring, you can put all the remaining
elements of an array in a new array.
❖ Let us try to understand it with an example.
var colors = ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange"];

GMRIT, Rajam, Andhra Pradesh


// destructuring assignment
var [a,b,...args] = colors;
console.log(a);
console.log(b);
console.log(args);
Result:
Violet
Indigo
[ 'Blue', 'Green', 'Yellow', 'Orange' ]
❖ Swapping Variables
var x = 100, y = 200;
[x, y] = [y, x];
console.log(x); // 200
console.log(y); // 100
Result:
200
100
Lecture - 8
➢ Object Destructing
❖ It is similar to array destructuring except that instead of values being pulled out of
an array, the properties (or keys) and their corresponding values can be pulled out
from an object.
❖ When destructuring the objects, we use keys as the name of the variable. The
variable name must match the property (or keys) name of the object. If it does not
match, then it receives an undefined value. This is how JavaScript knows which
property of the object we want to assign.
❖ In object destructuring, the values are extracted by the keys instead of position (or
index).

❖ First, try to understand the basic assignment in object destructuring by using the
following example.
❖ Example:
const num = {x: 100, y: 200};
const {x, y} = num;
console.log(x); // 100
console.log(y); // 200
Result:
100
200
❖ Object destructuring and default values
o Like array destructuring, a default value can be assigned to the variable if the
value unpacked from the object is undefined. It can be clear from the following
example.
const {x = 100, y = 200} = {x: 500};
console.log(x); // 500
console.log(y); // 200
Result:
500
200

GMRIT, Rajam, Andhra Pradesh


❖ Assigning new variable names
o We can assign a variable with a different name than the property of the object.
You can see the illustration for the same as follows:
const num = {x: 100, y: 200};
const {x: new1, y: new2} = num;
console.log(new1); //100
console.log(new2); //200
Result:
100
200
❖ Object destructuring and rest operator
o By using the rest operator (…) in object destructuring, we can put all the
remaining keys of an object in a new object variable.
let {a, b, ...args} = {a: 100, b: 200, c: 300, d: 400, e: 500}
console.log(a);
console.log(b);
console.log(args);
Result:
100
200
{ c: 300, d: 400, e: 500 }
Lecture - 9
❖ Classes
❖ Classes are an essential part of object-oriented programming (OOP). Classes are
used to define the blueprint for real-world object modeling and organize the code
into reusable and logical parts.

❖ Before ES6, it was hard to create a class in JavaScript. But in ES6, we can create the
class by using the class keyword. We can include classes in our code either by class
expression or by using a class declaration.
❖ A class definition can only include constructors and functions. These components
are together called as the data members of a class. The classes contain constructors
that allocates the memory to the objects of a class. Classes contain functions that
are responsible for performing the actions to the objects.
❖ Syntax: Class Declaration
class Class_name{
}
❖ Syntax: Class Expression
var var_name = new class_name {
}
❖ Let us see the illustration for the class expression and class declaration.
❖ Example - Class Declaration
class Student{
constructor(name, age){
this.name = name;
this.age = age;
}
}

GMRIT, Rajam, Andhra Pradesh


❖ Example - Class Expression
var Student = class{
constructor(name, age){
this.name = name;
this.age = age;
}
}
❖ Instantiating an Object from class Like other object-oriented programming
languages, we can instantiate an object from class by using the new keyword.
❖ Syntax
var obj_name = new class_name([arguements])
❖ Example
var stu = new Student('Peter', 22)
❖ Accessing functions
o The object can access the attributes and functions of a class. We use the '.' dot
notation (or period) for accessing the data members of the class.
o Syntax
obj.function_name();
o Example
class Student {
constructor(name, age) {
this.n = name;
this.a = age;
}
stu() {
console.log("The Name of the student is: ", this.n)
console.log("The Age of the student is: ",this. a)
}
}
var stuObj = new Student('Peter',20);
stuObj.stu();
Result:
The Name of the student is: Peter
The Age of the student is: 20
Lecture - 10
❖ Static keyword
o The static keyword is used for making the static functions in the class. Static
functions are referenced only by using the class name.
o Example
class Example {
static show() {
console.log("Static Function")
}
}
Example.show() //invoke the static method
Result:
Static Function

GMRIT, Rajam, Andhra Pradesh


Lecture – 11 &12

➢ Modules
❖ Modules are the piece or chunk of a JavaScript code written in a file. JavaScript
modules help us to modularize the code simply by partitioning the entire code into
modules that can be imported from anywhere. Modules make it easy to maintain
the code, debug the code, and reuse the piece of code. Each module is a piece of
code that gets executed once it is loaded.
❖ Modules in ES6 is an essential concept. Although it is not available everywhere, but
today we can use it and can transpile into ES5 code. Transpilation is the process of
converting the code from one language into its equivalent language. The ES6
module transpiler tool is responsible for taking the ES6 module and converts it into
a compatible code of ES5 in the AMD (Asynchronous module definition is a
specification for the JavaScript programming language) or in the CommonJS style.
❖ Exporting a Module
o JavaScript allows us to export a function, objects, classes, and primitive values
by using the export keyword. There are two kinds of exports:
o Named Exports: The exports that are distinguished with their names are called
as named exports. We can export multiple variables and functions by using the
named export.
o Default Exports: There can be, at most, one value that can be exported by using
the default export.
❖ Importing a Module
o To import a module, we need to use the import keyword. The values which are
exported from the module can be imported by using the import keyword. We
can import the exported variables, functions, and classes in another module. To
import a module, we simply have to specify their path.
o When you import the named export, you must have to use the same name as the
corresponding object. When you import the default export, we can use any
name of the corresponding object.

❖ Example - Named Export and Import


o Here, we are creating two JavaScript modules in which the first JavaScript
module is Mobile.js, and the second module name is App.js. We are also creating
an HTML file Example.html. Then, we will execute this .html file in the server.
o
o Next, we have to manually link the JavaScript file in the HTML file by using the
src attribute in the <script></script> tag. But the module still will not work. To
enable the module, we have to use the type = "module" in the <script></script>
tag.
o Example.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

GMRIT, Rajam, Andhra Pradesh


<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script type = "module" src = "App.js"></script>
<title>Document</title>
</head>
<body>
<h1>ES6 Modules import and export</h1>
</body>
</html>
o Mobile.js
class Display{
show(){
console.log("Hello World :)");
}
}
function javaT(){
console.log("Welcome to javaTpoint");
}
export {Display,javaT};
o App.js

import {Display,javaT} from "./Mobile.js";


const d = new Display();
d.show();
javaT();
o Output
Run the above Example.html file in the live server. Then, open the terminal in
the browser by using ctrl+shift+I. After the successful execution, you will get the
following output:

❖ Sample Questions

Remember

1. Define Fuctions.
2. List out advantages of JavaScript

Understanding

1. Explain the concept of Array Intialization and declaration with example


2. Discuss about Function types

GMRIT, Rajam, Andhra Pradesh


9. Stimulating Question (s)

1. Design a dynamic web page for Registration with validations


2. Design a web page with export and importing modules concept

10. Mind Map

11. Student Summary

At the end of this session, the facilitator (Teacher) shall randomly pic-up few students to
summarize the deliverables.

12. Reading Materials


❖ Advanced Java Script Speed up web development with powerful and benefits of Java Script,
Zachary Shute, Packt Publishers
❖ https://www.tutorialspoint.com/javascript/index.htm
❖ https://www.geeksforgeeks.org/javascript/

13. Scope for Mini Project

❖ Develop a dynamic web page for Registration with validations.

GMRIT, Rajam, Andhra Pradesh

You might also like