It is used to provide additional features to JavaScript objects.
JavaScript was created by Brendan Eich in 1995 and became an ECMA standard in 1997.
ECMAScript is the official name of the language.
ECMAScript versions have been abbreviated to ES1, ES2, ES3, ES5, and ES6.
1) let, const, and var
The let keyword allows you to declare a variable with block scope.
Example
var a = 10;
// Here a is 10
{
let a = 2;
// Here a is 2
}
// Here a is 10
The const keyword allows you to declare a constant (a JavaScript variable with a constant value).
Constants are similar to let variables, except that the value cannot be changed.
var x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
Call back function in JavaScript:-
A callback is a function passed as an argument to another function.
Using a callback, you could call the calculator function (myCalculator) with a callback, and let the calculator function run the callback after the calculation is finished.
When to Use a Callback?
Where callbacks really shine is in asynchronous functions, where one function has to wait for another function (like waiting for a file to load).
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
Arrow Functions
Arrow functions allow a short syntax for writing function expressions.
You don't need the function keyword, the return keyword, and the curly brackets.
Syntax:-
const identifier = ()=>expression
// ES5
var x = function(x, y) {
return x * y;
}
// ES6
const x = (x, y) => x * y;
The For/Of Loop
The JavaScript for/of statement loops through the values of an iterable objects.
for/of lets you loop over data structures that are iterable such as Arrays, Strings, Maps, NodeLists, and more.
The for/of loop has the following syntax:
for (variable of iterable) {
// code block to be executed
}
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x + " ";
}
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x + " ";
}
JavaScript Maps:-
identifer = new Map()
identifer.set(key:value)
const apples = {name: 'Apples'};
const bananas = {name: 'Bananas'};
const oranges = {name: 'Oranges'};
// Create a new Map
const fruits = new Map();
// Add new Elements to the Map
fruits.set(apples, 500);
fruits.set(bananas, 300);
fruits.set(oranges, 200);
Example of Map:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var stu = new Map();
stu.set("rno","1001");
stu.set("sname","xyz");
stu.set("branch","cs");
stu.set("fees",45000);
document.write(stu.get("rno") + "<br>");
for(var key of stu.keys())
{
document.write(key + " " + stu.get(key) + "<br>");
}
var s = "";
for(var item of stu.entries())
{
s = s + item + "<br>";
}
document.write(s);
stu.delete("rno");
var data = "";
stu.forEach(function(key,value){
data = data + key + " " + value + " ";
});
document.write(data);
</script>
</body>
</html>
JavaScript Sets:-
Example
// Create a Set
const letters = new Set();
// Add some values to the Set
letters.add("a");
letters.add("b");
letters.add("c");
for(let d of letters.values()){
JavaScript Classes:-
JavaScript Classes are templates for JavaScript Objects. it is used to define the characteristics and behavior of the object. Use the keyword class to create a class.
Always add a method named constructor():
class ClassName {
constructor() { ... }
}
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
JavaScript Promises:-
A Promise is a JavaScript object that links "Producing Code" and "Consuming Code".
"Producing Code" can take some time and "Consuming Code" must wait for the result.
JavaScript is single-threaded, meaning that two bits of the script cannot run at the same time; they have to run one after another. A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
const myPromise = new Promise(function(my resolve, myReject) {
// "Producing Code" (May take some time)
myResolve(); // when successful
myReject(); // when error
});
// "Consuming Code" (Must wait for a fulfilled Promise).
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
Example Using a Promise
const myPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() { myResolve("Wecome in SCS !!"); }, 3000);
});
myPromise.then(function(value) {
document.getElementById("demo").innerHTML = value;
});
Another Example of Promise Object to define success and failure both:
var flag=false;
const myPromise = new Promise(
function(myResolve, myReject) {
setTimeout(function() {
if (flag) {
myResolve("Wecome in SCS !!");
}
else {
myReject("Sorry !!");
}}, 3000);
});
myPromise.then(function(value) {
console.log(value);
}).catch(function(value) {console.log(value);});
Another Example:-
Promises can be chained together
When writing Promises to solve a particular problem, you can chain them together to form logic.
var add = function(x, y) {
return new Promise((resolve,reject) => {
var sum = x + y;
if (sum) {
resolve(sum);
}
else {
reject(Error("Could not add the two values!"));
}
});
};
var subtract = function(x, y) {
return new Promise((resolve, reject) => {
var sum = x - y;
if (sum) {
resolve(sum);
}
else {
reject(Error("Could not subtract the two values!"));
}
});
};
// Starting promise chain
add(2,2)
.then((added) => {
// added = 4
return subtract(added, 3);
})
.then((subtracted) => {
// subtracted = 1
return add(subtracted, 5);
})
.then((added) => {
// added = 6
return added * 2;
})
.then((result) => {
// result = 12
console.log("My result is ", result);
})
.catch((err) => {
// If any part of the chain is rejected, print the error message.
console.log(err);
});
Another way to implement Promise and Async, Await:-
async is used to create a promise object implicit and await is used to wait for the execution of the method until the promise block will not be completed.
it is used to perform asynchronous operations and implement blocking of code functionality.
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait until the promise resolves (*)
console.log(result); // "done!"
}
f();
The Symbol Type:-
A JavaScript Symbol is a primitive datatype just like a Number, String, or Boolean.
It represents a unique "hidden" identifier that no other code can accidentally access.
For instance, if different coders want to add a person.id property to a person's object belonging to a third-party code, they could mix each other's values.
Using Symbol() to creaa unique identifierers solves this problem:
<!DOCTYPE html>
<html>
<body>
<h2>Using JavaScript Symbol()</h2>
<p id="demo"></p>
<script>
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
let id = Symbol('id');
person[id] = 140353;
document.getElementById("demo").innerHTML = person[id] + " " + person.id;
</script>
</body>
</html>
Default Parameter Values:-
ES6 allows function parameters to have default values.
Example
function myFunction(x, y = 10) {
// y is 10 if not passed or undefined
return x + y;
}
myFunction(5); // will return 15
Function Rest Parameter:-
The rest parameter (...) allows a function to treat an indefinite number of arguments as an array:
function sum(...args) {
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
let x = sum(4, 9, 16, 25, 29, 100, 66, 77);
Multi-line Strings:-
ES6 also provides Multi-line Strings. Users can create multi-line strings by using back-ticks(`).
It can be done as shown below :
let greeting = `Hello World,
Greetings to all,
Keep Learning and Practicing!`
Template Literals
ES6 introduces very simple string templates along with placeholders for the variables. The syntax for using the string template is ${PARAMETER} and is used inside of the back-ticked string.
let name = `My name is ${firstName} ${lastName}`
Modules in JavaScript:-
Previously, there was no native support for modules in JavaScript. ES6 introduced a new feature called modules, in which each module is represented by a separate ".js" file.
We can use the "import" or "export" statement in a module to import or export variables, functions, classes, or any other component from/to different files and modules.
create filename first.js
export var name="Ravi Kumar"
var email="ravikumar@gmail.com"
export function display(){
console.log("Name: "+name)
console.log("Email: "+email)
}
Access Code
import { display,name } from './First.js';
console.log(name);
display();
Create File Name FirstModule.js and Write this code
export var name = "XYZ"
export default function getName()
{
console.log("welcome")
}
Create Second File Name SecondModule.html
<script type="module">
import getName from "./FirstModule.js";
getName();
</script>
DE structuring Assignments:
it is used to extract values of array and object to assign into normal variable.
Example:
const person= {name:"Ravi",age:25,city:"Bangalore"}
const {name,age,city}=person
console.log(name,age)
console.log(person.city)
Example for Array:
const numbers=[1,2,3,4,5]
const [num1,num2,...num3]=numbers
console.log(num1,num2)
console.log(num3)
Collection in JavaScript:
In JavaScript collection is a a group of data that can consist of
various types of data that have different behaviors
Type of Collection
1) Indexed collections
2) Keyed collections
3) DOM (DOCUMENT OBJECT MODEL) collections
Indexed collections:
The indexed collection contains data that is ordered by index and can also be
accessed using this index. An index means the position of data. For example,
imagine people in a queue. The person most close to the counter has an index of 0,
so they are at position 0.
Array
The most popular and well-known collection of data is an array.
An array is an index collection of ordered elements that have their own index and
can be accessed by this index.
Arrays can contain any data type and even other arrays.
Regular arrays are not type-based.
This means that you don’t have to define what data type you are going to
use inside the array. You can use everything together and anytime you want.
Regular Array: It has not any data type restriction
ref = [item1,item2,item3,...]
TypedArray
A TypedArray in JavaScript is a special type of array that provides a
mechanism to read and write raw binary data in memory buffers.
Unlike regular arrays, typed arrays are specifically designed to handle
binary data efficiently, and each element in a typed array is of the same type,
such as Int8, Uint8, Float32, etc.
Syntax:
ref = new Datatype(size)
let arr = new Uint8Array(5)
// Creating a TypedArray (Float32Array)
let typedArray = new Float32Array(5);
// An array with 5 elements, all initialized to 0
// Setting values
typedArray[0] = 1.1;
typedArray[1] = 2.2;
typedArray[2] = 3.3;
// Accessing elements
console.log(typedArray[0]); // Output: 1.1
// Iterating over a TypedArray
for (let element of typedArray) {
console.log(element);
}
// Output:
// 1.1
// 2.2
// 3.3
// 0
// 0
// Creating a TypedArray from an existing array
let normalArray = [10, 20, 30, 40, 50];
let typedArrayFromArray = new Int16Array(normalArray);
console.log(typedArrayFromArray); // Output: Int16Array [10, 20, 30, 40, 50]
array and typedarray defination and example
Array
An Array in JavaScript is a list-like object that allows you to store and manipulate
a collection of items. These items can be of any type (numbers, strings, objects, etc.). Arrays are zero-indexed, meaning the first element is at index 0.
Example:
javascript
// Creating an Array
let array = [1, 2, 3, 4, 5];
// Accessing elements
console.log(array[0]); // Output: 1
// Adding elements
array.push(6);
console.log(array); // Output: [1, 2, 3, 4, 5, 6]
// Removing elements
array.pop();
console.log(array); // Output: [1, 2, 3, 4, 5]
// Iterating over an Array
for (let element of array) {
console.log(element);
}
// Output:
// 1
// 2
// 3
// 4
// 5
TypedArray
A TypedArray in JavaScript is a special type of array that provides a
mechanism to read and write raw binary data in memory buffers. Unlike regular arrays,
typed arrays are specifically designed to handle binary data efficiently, and
each element in a typed array is of the same type, such as Int8, Uint8, Float32,
etc.
Example:
javascript
// Creating a TypedArray (Float32Array)
let typedArray = new Float32Array(5); // An array with 5 elements,
all initialized to 0
// Setting values
typedArray[0] = 1.1;
typedArray[1] = 2.2;
typedArray[2] = 3.3;
// Accessing elements
console.log(typedArray[0]); // Output: 1.1
// Iterating over a TypedArray
for (let element of typedArray) {
console.log(element);
}
// Output:
// 1.1
// 2.2
// 3.3
// 0
// 0
// Creating a TypedArray from an existing array
let normalArray = [10, 20, 30, 40, 50];
let typedArrayFromArray = new Int16Array(normalArray);
console.log(typedArrayFromArray); // Output: Int16Array [10, 20, 30, 40, 50]
Key Differences:
Element Types: Array can hold elements of any type, while TypedArray holds elements of a specific type (e.g., Int8, Uint8, Float32).
Performance: TypedArray is more efficient for handling binary data and performing numerical operations.
Initialization: Array can be initialized with any elements, whereas TypedArray is initialized with a specified number of elements of the same type.
Keyed collections
A keyed collection is a data collection ordered by keys instead of an index and
consists of key-value pairs. In JavaScript,
we have two types of keyed collections — Map and Set.
Map
A map is a simple key-value pair object where you can iterate through elements in insertion order. Keys always need to be unique just like an index.
To create a map you can use a map constructor and then add the desired elements by using a set method. The key name needs to be a string and a value can be any data type.
In JavaScript, Map and WeakMap are both objects that allow you to store key-value pairs. However, they have some important differences:
Map
Stores key-value pairs: Keys can be of any type (e.g., objects, primitive types).
Maintains insertion order: You can iterate over the items in the order they were added.
No automatic garbage collection: Keys are not garbage collected if they're not referenced elsewhere in the program.
// Creating a Map
let map = new Map();
// Setting key-value pairs
map.set('name', 'Alice');
map.set('age', 25);
map.set({ id: 1 }, 'objectKey');
// Getting values
console.log(map.get('name')); // Output: Alice
console.log(map.get('age')); // Output: 25
// Iterating over Map
for (let [key, value] of map) {
console.log(`${key}: ${value}`);
}
// Output:
// name: Alice
// age: 25
// [object Object]: objectKey
WeakMap
Stores key-value pairs: Keys must be objects (not primitive types).
Does not maintain insertion order: No way to iterate over items.
Automatic garbage collection: Keys are garbage collected if there are no other references to the object.
// Creating a WeakMap
let weakMap = new WeakMap();
// Creating objects for keys
let obj1 = { name: 'Alice' };
let obj2 = { age: 25 };
// Setting key-value pairs
weakMap.set(obj1, 'Object 1');
weakMap.set(obj2, 'Object 2');
// Getting values
console.log(weakMap.get(obj1)); // Output: Object 1
console.log(weakMap.get(obj2)); // Output: Object 2
// Deleting an object
obj1 = null;
// Since obj1 is now null, it will be garbage collected and removed from WeakMap
Set
A Set is a collection of unique values. Each value can only occur once in a Set,
and it maintains the insertion order, meaning you can iterate over
items in the order they were added.
Example:
// Creating a Set
let set = new Set();
// Adding values
set.add(1);
set.add(2);
set.add(2); // Duplicate values are ignored
set.add(3);
set.delete(3)
for(let item of set){
console.log("Item is "+item);
}
// Checking for values
console.log(set.has(2)); // Output: true
console.log(set.has(4)); // Output: false
WeakSet
A WeakSet is similar to a Set, but it only holds objects and does
not prevent them from being garbage-collected.
This means that if there are no other references to an object stored
in a WeakSet,
it will be garbage-collected and automatically removed from the WeakSet.
// Creating a WeakSet
let weakSet = new WeakSet();
// Creating objects for values
let obj1 = { name: 'Alice' };
let obj2 = { age: 25 };
// Adding objects
weakSet.add(obj1);
weakSet.add(obj2);
// Checking for objects
console.log(weakSet.has(obj1)); // Output: true
console.log(weakSet.has(obj2)); // Output: true
// Deleting an object
obj1 = null;
// Since obj1 is now null, it will be garbage collected and removed from WeakSet
console.log(weakSet.has(obj1)); // Output: false
Key Differences:
Value Types: Set can contain any type of value, whereas WeakSet only contains objects.
Garbage Collection: Objects in a WeakSet are garbage-collected if there are no other references to them.
Iteration: Set supports iteration over its values; WeakSet does not support iteration and doesn't maintain insertion order.
POST Answer of Questions and ASK to Doubt