Javascript Notes
Javascript Notes
JavaScript is case-sensitive
You can also convert one data type to another as per your needs. The
type conversion that you do manually is known as explicit type
conversion.
b.parseInt()
c.parseFloat()
Function makes the code reusable. You can declare it once and
use it multiple times.
Also, when the variable is used inside the function, the variable is
hoisted only to the top of the function. For example,
// program to display value
var a = 4;
function greet() {
b = 'hello';
console.log(b); // hello
var b;
}
greet(); // hello
console.log(b)
In the above example, variable b is hoisted to the top of the
function greet and becomes a local variable. Hence b is only accessible
inside the function. b does not become a global variable.
1. Object literal:-
Const person={
“name”:”Vinita”,
“age”:18
“name”:”Vinita”,
“age”:18
})
function Person() {
this.name=”Vinita”,
this.age=”18”
name: 'Sam',
age: 30,
person.greet(); // hello
the JavaScript method is an object property that has a function
value like greet is object method.
You can access an object method using a dot notation. The syntax
is: like objectname.methodkey() ex. person.greet()
// creating an object
let student = { };
// adding a property
student.name = 'John';
// adding a method
student.greet = function() {
console.log('hello');
// accessing a method
student.greet(); // hell
In JavaScript, this keyword when used with the object's
method refers to the object. this is bound to an object.
Accessor Property
In JavaScript, accessor properties are methods that get or set the
value of an object. For that, we use these two keywords:
const student = {
// data property
firstName: 'Monica',
// accessor property(getter)
get getName() {
return this.firstName;
};
console.log(student.firstName); // Monica
console.log(student.getName); // Monica
// trying to access as a method
console.log(student.getName()); // error
JavaScript Setter
In JavaScript, setter methods are used to change the values of an
object. For example,
const student = {
firstName: 'Monica',
//accessor property(setter)
set changeName(newName) {
this.firstName = newName;
}
};
console.log(student.firstName); // Monica
console.log(student.firstName); // Sarah
Array Methods:-
find():-
returns the first value of an array element that passes a test
findIndex():-
includes();-
slice():-
splice():-
removes or replaces existing elements and/or adds new
elements
A multidimensional array is an array that contains another
array.
JavaScript string is a primitive data type that is used to
work with texts.
Backticks are generally used when you need to include
variables
or expressions into a string. This is done by wrapping
variables or expressions with ${variable or expression}
In JavaScript, strings are immutable. That means the
characters of a string cannot be changed. For example,
let a = 'hello';
a[0] = 'H';
console.log(a); // "hello"
let a = 'hello';
a = 'Hello';
console.log(a); // "Hello"
confirm() displays the confirm dialog box containing message with ok and cancel button.
setTimeout() performs action after specified time like calling function, evaluating expressions et
10 mimeTypes[] returns the array of mime type. It is supported in Netscape and Firefox o
Types of Errors
Syntax Error: Error in the syntax. For example, if you write consol.log('your
result'); , the above program throws a syntax error. The spelling of console is
a mistake in the above code.
Runtime Error: This type of error occurs during the execution of the
program. For example,
calling an invalid function or a variable.
These errors that occur during runtime are called exceptions.
console.log(name);
let add = sum(4, 9);
console.log(add); // 13
/ inside module.js
export {
function1,
function2
};
Default Export
You can also perform default export of the module. For example,
// default export
export default function greet(name) {
return `Hello ${name}`;
}
You can directly use the default export without enclosing curly brackets {} .
1. You should not use arrow functions to create methods inside objects.
2. You cannot use an arrow function as a constructor. For example,
Template Literals:-
Template literals (template strings) allow you to use strings or embedded
expressions in the form of a string. They are enclosed in backticks ``
The process of assigning variables and expressions inside the template literal
is known as interpolation.
Js Spread Operator:-
The spread operator ... is used to expand or spread an iterable or an array.
You can also use the spread syntax ... to copy the items into a single array
if you want to copy arrays so that they do not refer to the same array, you can
use the spread operator. This way, the change in one array is not reflected in
the other.
Rest Parameter
When the spread operator is used as a parameter, it is known as the rest
parameter.
You can also accept multiple arguments in a function call using the rest
parameter.
For Example:-
let func = function(...args) {
console.log(args);
}
func(3); // [3]
func(4, 5, 6); // [4, 5, 6]
JS Map:-
Map is similar to objects in JavaScript that allows us to store elements in
a key/value pair.
To create a Map , we use the new Map() constructor. For example,
// create a Map
const map1 = new Map(); // an empty map
console.log(map1); // Map {}
After you create a map, you can use the set() method to insert elements to
it.
// create a set
let map1 = new Map();
You can access Map elements using the get() method. For example,
let map1 = new Map();
map1.set('info', {name: 'Jack', age: "26"});
You can use the has() method to check if the element is in a Map. For
example,
You can use the has() method to check if the element is in a Map. For
example,
map1.delete('info'); // true
console.log(map1); // Map {}
The clear() method removes all key/value pairs from a Map object. For
example,
let map1 = new Map();
map1.set('info', {name: 'Jack', age: "26"});
You can get the number of elements in a Map using the size property. For example,
let map1 = new Map();
map1.set('info', {name: 'Jack', age: "26"});
console.log(map1.size); // 1
You can iterate through the Map elements using the for...of loop
or forEach() method. The elements are accessed in the insertion order. For
example,
let map1 = new Map();
map1.set('name', 'Jack');
map1.set('age', '27');
You can iterate over the Map and get the key using the keys() method. For
example,
let map1 = new Map();
map1.set('name', 'Jack');
map1.set('age', '27');
You can iterate over the Map and get the values using the values() method.
For example,
let map1 = new Map();
map1.set('name', 'Jack');
map1.set('age', '27');
Map Object
Maps can contain objects and other data Objects can only contain strings and symbols
types as keys. as keys.
The number of elements of a Map can be The number of elements of an object needs to
determined by size property. be determined manually.
Map performs better for programs that Object does not perform well if the program
require the addition or removal of elements requires the addition or removal of elements
frequently. frequently.
JavaScript WeakMap
The WeakMap is similar to a Map. However, WeakMap can only contain
objects as keys. For example,
When you try to add other data types besides objects, WeakMap throws an
error.
const weakMap = new WeakMap();
WeakMaps have methods get() , set() , delete() , and has() . For example,
const weakMap = new WeakMap();
console.log(weakMap); // WeakMap {}
console.log(weakMap); // WeakMap {}
Javascript Set:-
Set is similar to an array that allows us to store multiple items like numbers,
strings, objects, etc. However, unlike an array, a set cannot contain duplicate
values.
To create a Set , you need to use the new Set() constructor. For example,
// create Set
const set1 = new Set(); // an empty set
console.log(set1); // Set {}
When duplicate values are passed to a Set object, the duplicate values are
excluded.
// Set with duplicate values
const set3 = new Set([1, 1, 2, 2]);
console.log(set3); // Set {1, 2}
You can access Set elements using the values() method and check if there is
an element inside Set using has() method. For example,
const set1 = new Set([1, 2, 3]);
You can use the has() method to check if the element is in a Set. For
example,
const set1 = new Set([1, 2, 3]);
You can iterate through the Set elements using the for...of loop
or forEach() method. The elements are accessed in the insertion order.
const set = new Set([1, 2, 3]);
JavaScript WeakSet
The WeakSet is similar to a Set. However, WeakSet can only contain objects
whereas a Set can contain any data types such as strings, numbers, objects,
etc.
let obj = {
message: 'Hi',
sendMessage: true
}
// adding object (element) to WeakSet
weakSet.add(obj);
When you try to add other data types besides objects, WeakSet throws an
error.
console.log(weakSet); // WeakSet {}
// add to a weakSet
weakSet.add(obj);
console.log(weakSet.has(obj)); // true
// delete elements
weakSet.delete(obj);
console.log(weakSet); // WeakSet {}
JavaScript Destructuring
The destructuring assignment introduced in ES6 makes it easy to assign
array values and object properties to distinct variables.
const person = {
name: 'Sara',
age: 25,
gender: 'female'
// destructuring assignment
console.log(age); // 25
console.log(gender); // female
When destructuring objects, you should use the same name for the variable
as the corresponding object key.
If you want to assign different variable names for the object key, you can use:
const person = {
name: 'Sara',
age: 25,
gender: 'female'
// destructuring assignment
console.log(name1); // Sara
console.log(age1); // 25
console.log(gender1); // female
Array Destructuring
You can also perform array destructuring in a similar way. For example,
console.log(x); // one
console.log(y); // two
console.log(z); // three
You can skip unwanted items in an array without assigning them to local
variables. For example,
console.log(z); // three
JavaScript Classes
A class is a blueprint for the object. You can create an object from the class.
The class keyword is used to create a class. The properties are assigned in a
constructor function.
// creating a class
class Person {
constructor(name) {
this.name = name;
}
}
// creating an object
const person1 = new Person('John');
const person2 = new Person('Jack');
console.log(person1.name); // John
console.log(person2.name); // Jack
It is easy to define methods in the JavaScript class. You simply give the name
of the method followed by ()
In JavaScript, getter methods get the value of an object and setter methods
set the value of an object.
You use the get keyword for getter methods and set for setter methods.
class Person {
constructor(name) {
this.name = name;
}
// getter
get personName() {
return this.name;
}
// setter
set personName(x) {
this.name = x;
}
}
A class should be defined before using it. Unlike functions and other
JavaScript declarations, the class is not hoisted.
Classes always follow 'use-strict'. All the code inside the class is
automatically in strict mode.
Js Prototype:-
What is the requirement of a prototype
object?
Whenever an object is created in JavaScript, its corresponding functions are loaded into
memory. So, a new copy of the function is created on each object creation.
In a prototype-based approach, all the objects share the same function. This ignores the
requirement of creating a new copy of function for each object. Thus, the functions are loaded
once into the memory.
Class Inheritance:-
Using class inheritance, a class can inherit all the methods and properties of
another class.
The super keyword used inside a child class denotes its parent class.
If a child class has the same method or property name as that of the parent
class, it will use the method and property of the child class. This concept is
called method overriding.
JavaScript Polymorphism
The polymorphism is a core concept of an object-oriented paradigm that provides a
way to perform a single action in different forms.
JavaScript Abstraction
An abstraction is a way of hiding the implementation details and showing only the
functionality to the users. In other words, it ignores the irrelevant details and shows
only the required one.
JavaScript Proxies
proxies (proxy object) are used to wrap an object and redefine various
operations into the object such as reading, insertion, validation, etc. Proxy
allows you to add custom behavior to an object or a function.
Here,
Javascript setTimeout()
The setTimeout() method executes a block of code after the specified time.
The method executes the code only once.
The commonly used syntax of JavaScript setTimeout is:
setTimeout(function, milliseconds);
JavaScript clearTimeout()
As you have seen in setTimeOut, the program executes a block of code after
the specified time interval. If you want to stop this function call, you can use
the clearTimeout() method.
The syntax of clearTimeout() method is:
clearTimeout(intervalID);
You can also pass additional arguments to the setTimeout() method. The
syntax is:
// function
function greet(name, callback) {
console.log('Hi' + ' ' + name);
callback();
}
// callback function
function callMe() {
console.log('I am callback function');
}
The benefit of using a callback function is that you can wait for the result of a
previous function call and then execute another function call.
Pending
Fulfilled
Rejected
A promise starts in a pending state. That means the process is not complete.
If the operation is successful, the process ends in a fulfilled state. And, if an
error occurs, the process ends in a rejected state.
Create a Promise
To create a promise object, we use the Promise() constructor.
The Promise() constructor takes a function as an argument. The function also
accepts two functions resolve() and reject() .