[go: up one dir, main page]

0% found this document useful (0 votes)
6 views23 pages

Lecture 1

The document provides an overview of ES6 classes and their features, including class syntax, object instantiation, inheritance, method overriding, and static methods. It also covers JavaScript variables, array methods, destructuring, the spread operator, and ES6 modules for better code organization. Key concepts such as single inheritance, multiple inheritance, and examples of various array methods are highlighted throughout the document.

Uploaded by

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

Lecture 1

The document provides an overview of ES6 classes and their features, including class syntax, object instantiation, inheritance, method overriding, and static methods. It also covers JavaScript variables, array methods, destructuring, the spread operator, and ES6 modules for better code organization. Key concepts such as single inheritance, multiple inheritance, and examples of various array methods are highlighted throughout the document.

Uploaded by

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

ES6 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. 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.
Class
Syntax: Class Expression
var var_name = new class_name { }
Syntax: Class Declaration
class Class_name{ }
Example:-Class Declaration
class Student{
constructor(name, age){
this.name = name;
this.age = age;
}
}
Instantiating an Object from class
we can instantiate an object from class by using the new keyword.
var obj_name = new class_name([arguements])
Accessing functions
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. Syntax : obj.function_name();
The Static keyword
The static keyword is used for making the static functions in the class.
Static functions are referenced only by using the class name.
Class inheritance
ES6 simplified the implementation of inheritance by using
the extends and super keyword. Inheritance is the ability to create
new entities from an existing one. The class that is extended for
creating newer classes is referred to as superclass/parent class,
while the newly created classes are called subclass/child class.
Syntax : class child_class_name extends parent_class_name{ }
Types of inheritance:
1. Single-level Inheritance :It is defined as the inheritance in which
a derived class can only be inherited from only one base class. It
allows a derived class to inherit the behavior and properties of a
base class, which enables the reusability of code as well as adding
the new features to the existing code. It makes the code less
repetitive.
Types of
inheritance:
Single inheritance:

It allows a derived class to inherit the behavior and properties of a base


class, which enables the reusability of code as well as adding the new
features to the existing code. It makes the code less repetitive.
Multiple Inheritance
In multiple inheritance, a class can be inherited from several classes. It
is not supported in ES6.

Multi-level Inheritance
In Multi-level inheritance, a derived class is created from another
derived class. Thus, a multi-level inheritance has more than one parent
class.
Example
class Animal{
eat(){
console.log("eating...");
}
}
class Dog extends Animal{
bark(){
console.log("barking...");
}
}
class BabyDog extends Dog{
weep(){
console.log("weeping...");
}
}
var d=new BabyDog();
d.eat();
d.bark();
d.weep();
Method Overriding and
Inheritance
It is a feature that allows a child class to provide a specific implementation of a method which has been already
provided by one of its parent class. Some rules defined for method overriding:-
1. The method name must be the same as in the parent class.
2. Method signatures must be the same as in the parent class.
use strict' ;
class Parent {
show() {
console.log("It is the show() method from the parent class");
}
}
class Child extends Parent {
show() {
console.log("It is the show() method from the child class");
}
}
var obj = new Child();
obj.show();
Super
keyword
It is introduced in ECMAScript 2015 or ES6. The super.prop and super[expr] expressions are readable in the
definition of any method in both object literals and classes.
'use strict' ;
class Parent {
show() {
console.log("It is the show() method from the parent class");
}
}
class Child extends Parent {
show() {
super.show();
console.log("It is the show() method from the child class");
}
}
var obj = new Child();
obj.show();
Static Methods:
Static methods in a class are methods that are bound to the class rather than to
instances of the class. They don’t require an instance of the class to be called and
don’t access or modify the instance’s state (i.e., they don’t use self). Static methods
are useful when you need a function that belongs to a class logically but doesn't need
access to any class or instance-specific data.
class MathOperations { static add(a, b) { return a + b; } }
const resultAdd = MathOperations.add(10, 5);
console.log("Add:", resultAdd);
Arrow
Functions
Arrow functions are introduced in ES6, which provides you a more
accurate way to write the functions in JavaScript. Arrow functions
are anonymous functions (the functions without a name and not bound
with an identifier). They don't return any value and can declare without
the function keyword. Arrow functions cannot be used as the
constructors. The context within the arrow functions is lexically or
statically defined. They are also called as Lambda Functions in
different languages.
Syntax for defining the arrow function
const functionName = (arg1, arg2, ?..) => {
//body of the function
}
JavaScript Variables
Variables are Containers for Storing Data. JavaScript Variables can be
declared in 4 ways:
1. Automatically
2. Using var
3. Using let
4. Using const
Property let const var
Scope block-scoped block-scoped function-scoped
Reassignment yes No yes
Redeclaration No No yes
Temporal Dead Zone yes yes No
Hoisting hoisted, but let is hoisted, but const is hoisted, but var is initialized
remain uninitialized. remain uninitialized. with undefined
Array
methods
JavaScript array is an object that represents a collection of similar type of
elements. here are 3 ways to construct array in JavaScript
1.By array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
Example:-
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
2.By creating instance of Array directly (using new
keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();
Example:-
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
3.By using an Array constructor
(using new keyword)
you need to create instance of array by passing arguments in
constructor so that we don't have to provide value explicitly. The
example of creating object by array constructor is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
JavaScript Array Methods
Methods Description
concat() It returns a new array object that contains two or more merged arrays.
copywithin() It copies the part of the given array with its own elements and returns the modified array.
entries() It creates an iterator object and a loop that iterates over each key/value pair.
every() It determines whether all the elements of an array are satisfying the provided function conditions.
flat() It creates a new array carrying sub-array elements concatenated recursively till the specified depth.
flatMap() It maps all array elements via mapping function, then flattens the result into a new array.
fill() It fills elements into an array with static values.
from() It creates a new array carrying the exact copy of another array element.
filter() It returns the new array containing the elements that pass the provided function conditions.
find() It returns the value of the first element in the given array that satisfies the specified condition.
findIndex() It returns the index value of the first element in the given array that satisfies the specified condition.
forEach() It invokes the provided function once for each element of an array.
includes() It checks whether the given array contains the specified element.
indexOf() It searches the specified element in the given array and returns the index of the first match.
isArray() It tests if the passed value ia an array.
join() It joins the elements of an array as a string.
keys() It creates an iterator object that contains only the keys of the array, then loops through these keys.
lastIndexOf() It searches the specified element in the given array and returns the index of the last match.
map() It calls the specified function for every array element and returns the new array
of() It creates a new array from a variable number of arguments, holding any type of argument.
pop() It removes and returns the last element of an array.
push() It adds one or more elements to the end of an array.
reverse() It reverses the elements of given array.
reduce(function, initial) It executes a provided function for each value from left to right and reduces the array to a single value.
reduceRight() It executes a provided function for each value from right to left and reduces the array to a single value.
some() It determines if any element of the array passes the test of the implemented function.
shift() It removes and returns the first element of an array.
slice() It returns a new array containing the copy of the part of the given array.
sort() It returns the element of the given array in a sorted order.
splice() It add/remove elements to/from the given array.
toLocaleString() It returns a string containing all the elements of a specified array.
toString() It converts the elements of a specified array into string form, without affecting the original array.
unshift() It adds one or more elements in the beginning of the given array.
values() It creates a new iterator object carrying values for each index in the array.
JavaScript Array concat()
Method
The JavaScript array concat() method combines two or more arrays and
returns a new string. This method doesn't make any change in the original
array. The concat() method is represented by the following syntax:
array.concat(arr1,arr2,....,arrn)
Example:-
<script>
var arr1=["C","C++","Python"];
var arr2=["Java","JavaScript","Android"];
var result=arr1.concat(arr2);
document.writeln(result);
</script>
<script>
var arr1=["C","C++","Python"];
var arr2=["Java","JavaScript","Android"];
var arr3=["Ruby","Kotlin"];
var result=arr1.concat(arr2,arr3);
document.writeln(result);
</script>
<script>
var arr=["C","C++","Python"];
var result= arr.concat("Java","JavaScript","Android");
document.writeln(result);
</script>
Object Destructuring
Destructuring assignment makes it easy to assign array values and object properties to
variables.
<p id="demo"></p>
<script>
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
let { firstName, age } = person;
document.getElementById("demo").innerHTML = firstName + " is " + age + " years old.";
</script>
Spread operator syntax (...)

function sum(x, y, z) { return x + y + z;}


const numbers = [1, 2, 3];
console.log(sum(...numbers));
console.log(sum.apply(null, numbers));
The new Map() Method
map() creates a new array from calling a function for every array element.
map() does not execute the function for empty elements.
map() does not change the original array.
Example:
const numbers = [4, 9, 16, 25];
const newArr = numbers.map(Math.sqrt)
const numbers = [65, 44, 12, 4];
const newArr = numbers.map(myFunction)

function myFunction(num) {
return num * 10;
}
ES6 modules
ES6 modules allow you to organize your JavaScript code into separate files, making it easier to maintain,
reuse, and manage dependencies. Here's a simple example demonstrating how to use ES6 modules.
Creating a Module (Exporting):
// mathUtils.js
export function add(a, b) {
return a + b;
}

export function subtract(a, b) {


return a - b;
}

// You can also export variables, classes, etc.


export const PI = 3.14159;
Using a Module (Importing)
Now, in another file, say app.js, you can import and use
these functions and constants:
javascript
// app.js
import { add, subtract, PI } from './mathUtils.js';
console.log("Addition:", add(5, 3)); // Output: Addition: 8
console.log("Subtraction:", subtract(5, 3)); // Output:
Subtraction: 2
console.log("Value of PI:", PI);

You might also like