Lectures Notes
Of Day 14
JavaScript ES6 Features
Objective:
The objective of today's
lesson is to introduce and understand the new features introduced in ES6
(ECMAScript 2015) that simplify and improve the way we write JavaScript. These
features include arrow functions, template literals, destructuring, and the let
and const keywords for variable declaration. By the end of this class, you will
be able to use these modern JavaScript features effectively in your code.
1. Arrow Functions
Arrow functions are a
shorter syntax for writing functions in JavaScript. They make your code more
concise and are particularly useful for functions that consist of a single line
of code. Arrow functions also behave differently in terms of how this is handled.
Syntax:
// Basic syntax of an
arrow function
const functionName =
(parameter1, parameter2) => {
// function body
return parameter1
+ parameter2;
};
- If
the function has only one parameter, you can omit the parentheses around
the parameter:
const square = num =>
num * num; // No need for parentheses around 'num'
- If
the function consists of only one expression, you can omit the curly
braces {} and return statement:
const add = (a, b) =>
a + b; // Implicit return
Advantages:
- Shorter
syntax: Arrow functions allow for more
concise function definitions.
- this
binding: Unlike traditional functions,
arrow functions do not have their own this context. They inherit this from
the surrounding context, making them ideal for use in methods, event
listeners, etc., where you want to refer to the surrounding scope’s this.
Example:
const greet = name =>
console.log(`Hello, ${name}!`);
// Invoking the arrow
function
greet("Alice");
// Output: Hello, Alice!
2. Template Literals
Template literals (also
known as template strings) are a feature in ES6 that allows you to embed
expressions inside string literals. This makes string concatenation easier and
more readable.
Syntax:
Template literals are
enclosed by backticks (``) rather than regular quotes (' or ").
- Simple
String Example:
let greeting = `Hello,
World!`;
- Embedding Expressions:
- You can embed expressions
inside ${} within template literals.
let name = "John";
let age = 30;
let message = `My name is
${name} and I am ${age} years old.`;
console.log(message);
// Output: My name is John and I am 30 years old.
Advantages:
- Multiline
Strings: Template literals allow you to
create multiline strings easily without the need for concatenation or
escape characters.
let multiLine = `This is a
multiline string
using template
literals.`;
console.log(multiLine);
- Expression
Interpolation: You can insert any expression
inside ${}. This makes it easier to manipulate data inside strings.
3. Destructuring
Destructuring is a
convenient way to extract values from arrays or objects and assign them to
variables in a concise manner. This feature reduces the need for manually
accessing properties or array elements.
Array Destructuring:
In array destructuring,
you unpack values from an array into separate variables.
Syntax:
let [variable1, variable2] = array;
- Example:
let numbers = [10, 20, 30];
let [a, b] = numbers;
console.log(a); //
Output: 10
console.log(b); //
Output: 20
- Skipping
Values: You can skip certain values by
leaving empty slots.
let [first, , third] = numbers;
console.log(first);
// Output: 10
console.log(third);
// Output: 30
Object Destructuring:
With object
destructuring, you can extract values from an object and assign them to
variables with matching names.
Syntax:
let { key1, key2 } = object;
- Example:
let person = { name:
"Alice", age: 25 };
let { name, age } =
person;
console.log(name);
// Output: Alice
console.log(age);
// Output: 25
- Renaming Variables: If you want to assign a property to a variable with a different name, you can do this:
let person = { name:
"Alice", age: 25 };
let { name: fullName,
age: yearsOld } = person;
console.log(fullName);
// Output: Alice
console.log(yearsOld);
// Output: 25
Advantages of Destructuring:
- Cleaner
code: Destructuring makes your code more readable
and concise.
- Flexible
variable assignment: You can extract and rename
variables easily in a single step.
- Works
well with functions: You can destructure
function parameters directly.
4. let and const for Variable Declaration
Before ES6, JavaScript
only had the var keyword for variable declarations. However, var has several
issues, including function scope, hoisting, and redeclaration. ES6 introduced
two new keywords for variable declaration: let and const.
let:
- let
is used to declare variables that can be reassigned later.
- It
has block scope, meaning it is only accessible within the
block (or curly braces) in which it is defined.
Syntax:
let variableName = value;
- Example:
let x = 10;
x = 20; // You can
reassign the value of x
console.log(x); //
Output: 20
const:
- const
is used to declare variables that cannot be reassigned.
- Like
let, const also has block scope.
- While
the value of a const variable cannot be reassigned, objects or arrays
assigned to const variables can still be modified.
Syntax:
const variableName = value;
- Example:
const pi = 3.14;
pi = 3.1415; //
Error: Assignment to constant variable.
- Example
with objects:
const person = { name: "John", age: 30 };
person.age = 31; //
Allowed: properties of a const object can be changed.
console.log(person.age);
// Output: 31
Key Differences between let, const, and var:
- var
is function-scoped, whereas let and const are block-scoped.
- var
allows redeclaration within the same scope, while let and const do not.
- const
cannot be reassigned, while let can.
Summary:
In this lesson, we have
learned about important ES6 features that significantly improve JavaScript
programming:
- Arrow
Functions provide a concise syntax and a
more predictable handling of this.
- Template
Literals allow for easier string
interpolation, multiline strings, and cleaner code.
- Destructuring enables
easy unpacking of values from arrays and objects.
- let
and const provide block-scoped variable
declarations, with const ensuring that a variable's value cannot be
reassigned.
These ES6 features help
make JavaScript code cleaner, more efficient, and easier to maintain.
Practice Exercise:
1. Arrow
Functions: Write an arrow function that takes two parameters, a and b, and
returns their sum.
2. Template
Literals: Create a string using template literals that displays your full
name and age, like "My name is John, and I am 25 years old."
3. Destructuring:
Given the object const user = { username: 'alice', email: 'alice@example.com'
}, destructure it into separate variables username and email and print them to
the console.
4. let and
const: Declare a constant PI with the value 3.14, and a variable radius
with a value of 5. Calculate the area of a circle using PI and radius, and log
the result.
