Simple To Memorize - Js
Simple To Memorize - Js
p {
text-align: center;
color: red;
}
#para1 {
text-align: center;
color: red;
}
.center {
text-align: center;
color: red;
}
p.center {
text-align: center;
color: red;
}
* {
text-align: center;
color: blue;
}
element element div p Selects all <p> elements inside <div> elements
element>element div > p Selects all <p> elements where the parent is a <div> element
element+element div + p Selects the first <p> element that are placed immediately after
<div> elements
element1~element2 p ~ ul Selects every <ul> element that are preceded by a <p>
element
div p {
background-color: yellow;
}
div > p {
background-color: yellow;
}
div + p {
background-color: yellow;
}
div ~ p {
background-color: yellow;
}
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
/* unvisited link */
a:link {
color: #FF0000;
}
/* visited link */
a:visited {
color: #00FF00;
}
/* selected link */
a:active {
color: #0000FF;
}
p::first-line {
color: #ff0000;
font-variant: small-caps;
}
p::first-letter {
color: #ff0000;
font-size: xx-large;
}
p::first-line {
color: #ff0000;
font-variant: small-caps;
}
p.intro::first-letter {
color: #ff0000;
font-size: 200%;
}
The example above will display the first letter of paragraphs with class="intro", in red
and in a larger size
p::first-letter {
color: #ff0000;
font-size: xx-large;
}
a[target] {
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
background-color: yellow;
}
The following example selects all <a> elements with a target attribute
a[target="_blank"] {
background-color: yellow;
}
[class|=top] {
background: yellow;
}
Note: The value has to be a whole word, either alone, like class="top", or followed by a
hyphen( - ), like class="top-text".
<Router history={history}>
</Router>
Array to object:
------------------
Object to Array :
-----------------
const person = {
firstName: 'John',
lastName: 'Doe'
};
prototypical inheritance
https://www.javascripttutorial.net/javascript-prototypal-inheritance/
Array to String :
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let text = fruits.toString(); // Banana,Orange,Apple,Mango
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
String to Array :
--------------------
text.replace("Microsoft", "W3Schools");
text.replace(/MICROSOFT/i, "W3Schools");
text.replace(/Microsoft/g, "W3Schools");
string methods :
----------------
txt.length;
str.slice(7, 13);
str.substring(7, 13);
str.substr(7);
text.replace("Microsoft", "W3Schools");
text1.toUpperCase();
text1.concat(" ", text2);
text1.trim();
text.padStart(4,"x");
text.padEnd(4,"x");
text.charAt(0);
text.charCodeAt(0);
text.split(",")
Array methods:
------------------
fruits.toString();
fruits.join(" * ")
fruits.pop()
fruits.push("Kiwi");
fruits.shift();
fruits.unshift("Lemon");
delete fruits[0];
myGirls.concat(myBoys)
fruits.splice(2, 0, "Lemon", "Kiwi");
fruits.slice(1);
Number.POSITIVE_INFINITY
-Number.MAX_VALUE
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
const food = { beef: '🥩', bacon: '🥓' }
// "Spread"
{ ...food }
// "Object.assign"
Object.assign({}, food)
// "JSON"
JSON.parse(JSON.stringify(food))
console.log(cloneFood);
// { beef: '🥩', bacon: '🥓' }
console.log(cloneFood);
// { beef: '🥩', bacon: '🥓' }
valueOf() method
normalObj.hasOwnProperty("p")
"use strict"
var det = { name:"Tom", ID:"E1001" };
var copy = Object.assign({}, det);
console.log(copy);
for (let val in copy) {
console.log(copy[val])
}
var o1 = { a: 10 };
var o2 = { b: 20 };
var o3 = { c: 30 };
var obj = Object.assign(o1, o2, o3);
var o1 = { a: 10 };
var obj = Object.assign(o1);
obj.a++
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
console.log(val1 === val2) // return false
the concept of hoisting does not apply to scripts that are run in the Strict Mode.
o/p:
number
object
var val = new String(string);
string.length
function employee(id, name) {
this.id = id;
this.name = name;
}
var emp = new employee(123, "Smith");
employee.prototype.email = "[email protected]";
charAt()
charCodeAt()
str1.indexOf( "string" )
str1.localeCompare( "This is beautiful string");
match()
replace() - need to check
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g;
const found = paragraph.match(regex);
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
let result1 = /Hello/.exec(text);
o/p:
----
(1,2): pp
(-2,2): y.
(1): pples are round, and apples are juicy.
(-20, 2): nd
(20, 2): d
o/p :(1,2): p
(0,10): Apples are
(5): s are round, and apples are juicy
string.valueOf() - This method returns the primitive value of a String object.
console.log(str.endsWith('Hello'));
console.log(str.endsWith('Hello',5));// checks 'Hello' only in first 5 characters
console.log(str.includes('hell'))
console.log(str.includes('Hell'));
console.log(str.includes('or'));
console.log(str.includes('or',1)) // starts searching 'or' from index 1
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
function fn() { return "Hello World"; }
console.log(`Message: ${fn()} !!`);
nums.forEach(function(val,index) {
console.log(val)
})
nums.reverse() //reverses the array element
console.log("Printing Reversed array....")
nums.forEach(function(val,index){
console.log(val)
})
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });
console.log("total is : " + total );
[0, 1, 2, 3].reverse()
o/p:
-----
After adding 1: orange,mango,water,banana,sugar,tea
removed is:
unshift() method adds one or more elements to the beginning of an array and returns the
new length of the array.
var arr = new Array("orange", "mango", "banana", "sugar");
var length = arr.unshift("water"); // length : 5
var numbers = [1, 2, 3];
var oddNumber = numbers.find((x) => x % 2 == 1); // o/p : 1
"use strict"
for (let i of Array.from('hello')) {
console.log(i)
}
o/p :
-------
h
e
l
l
o
"use strict"
var nums = [1001,1002,1003,1004]
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
for(let j in nums) {
console.log(nums[j])
}
let locations=['Mumbai','Hyderabad','Chennai']
let [l1,...otherValues] =locations
let name1,name2;
[name1,name2] =names
let first=10,second=20;
[second,first] = [first,second]
var identifier = {
Key1:value, Key2: function () {
//functions
},
Key3: [“content1”,” content2”]
}
Like all JavaScript variables, both the object name (which could be a normal variable)
and the property name are case sensitive. You access the properties of an object with a
simple dot-notation.
var person = {
firstname:"Tom",
lastname:"Hanks",
func:function(){return "Hello!!"},
};
In ES6, assigning a property value that matches a property name, you can omit the
property value.
var foo = 'bar'
var baz = { foo }
console.log(baz.foo)
function Car() {
this.make = "Ford"
}
var obj = new Car()
obj.model = "F123"
var roles = {
type: "Admin", // Default value of properties
displayType : function() {
// Method which will display type of role
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
console.log(this.type);
}
}
// Create new role type called super_role
var super_role = Object.create(roles);
super_role.displayType(); // Output:Admin
"use strict"
var det = { name:"Tom", ID:"E1001" };
var copy = Object.assign({}, det);
console.log(copy);
for (let val in copy) {
console.log(copy[val])
}
var o1 = { a: 10 };
var o2 = { b: 20 };
var o3 = { c: 30 };
var obj = Object.assign(o1, o2, o3);
Unlike copying objects, when objects are merged, the larger object doesn’t maintain a new
copy of the properties. Rather it holds the reference to the properties contained in the
original objects
let student = {
rollno:20,
name:'Prijin',
cgpa:7.2
}
let customers= {
c1:101,
c2:102,
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
c3:103
}
let emp = {
id:101,
address:{
city:'Mumbai',
pin:1234
}
}
let {address} = emp;
let company='TutorialsPoint'
console.log(company.startsWith('Tutorial'))
console.log(company.startsWith('orial',3))
let company = 'TutorialsPoint'
console.log(company.endsWith('Point'));
console.log(company.endsWith('Tutor',5))//5 is length of string in string
'TutorialsPoint' only first 5 chars are verified
let company='TutorialsPoint'
console.log(company.includes('orial'))
console.log(company.includes('orial',4))// search string will be searched from the
index 4 in main string
let name="Kiran-"
console.log(name.repeat(3));
console.log(Number.isFinite(Infinity))//false
console.log(Number.isFinite(-Infinity))//false
console.log(Number.isFinite(NaN))//false
console.log(Number.isFinite(123))//true
console.log(Number.isFinite('123')) // evaluates to false
console.log(isFinite('123')) // evaluates to true,global function
console.log(Number.isNaN('123'))//false
console.log(Number.isNaN(NaN))//true
console.log(Number.isNaN(0/0))//true
console.log(Number.parseFloat('10.3meters')); // 10.3
console.log(Number.parseFloat('abc10.3xyz')); // NaN
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
console.log(Number.parseInt('10meters')) //10
console.log(Number.parseInt('abc10meters')) //NaN
Math.sign(-Infinity) // -1
console.log(Math.trunc(-3.5)) // -3
let marks = [10,20,30,40,50,60]
console.log(marks.copyWithin(0,2,4)) //destination,source start,source end(excluding)
// [ 30, 40, 30, 40, 50, 60 ]
console.log(marks.copyWithin(2,4)) // destination , source start
o/p
7.5
8.5
6.5
9.5
console.log(Array.of(10))
console.log(Array.of(10,20,30))
console.log(Array.of(10))
console.log(Array.of(10,20,30))
o/p:
[10]
[10, 20, 30]
const obj_arr ={
length:2,
0:101,
1:'kannan'
}
-- console.log(obj_arr) //{0: 101, 1: "kannan", length: 2}
const arr = Array.from(obj_arr)
-- console.log(arr) // [101, "kannan"]
for(const element of arr){
console.log(element); // 101
// kannan
}
console.log(Array.from('Javascript')) // ["J", "a", "v", "a", "s", "c", "r", "i",
"p", "t"]
let setObj = new Set(['Training',10,20,20,'Training'])
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
console.log(Array.from(setObj)) // ["Training", 10, 20]
console.log(Array.from([10,20,30,40],n=>n+1)) //[11, 21, 31, 41]
getTime()
Returns the numeric value of the specified date as the number of milliseconds since
January 1, 1970, 00:00:00 UTC
dt.setDate( 24 )
Date.toDateString()
var dt = new Date(1993, 6, 28, 14, 39, 7);
console.log( "Formated Date : " + dt.toDateString() ) //Formated Date : Wed Jul 28 1993
o/p:
Formated Date : 7/28/1993
o/p:
7/28/1993, 2:39:07 PM
This method returns the primitive value of a Date object as a number data type, the
numbePr of milliseconds since midnight 01 January, 1970 UTC.
Math.abs( x ) ;
Math.sign( x ) ;
Math.ceil(x);
Math.floor(x)
Math.trunc(7.7)
Math.round( x ) ;
Math.min(x1, x2,...)
Math.max((x1, x2,...)
Math.random();
Number.MAX_VALUE
Number.MIN_VALUE
Number.NaN;
Number.NEGATIVE_INFINITY
Number.POSITIVE_INFINITY
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
Number.isInteger()
Number.isFinite()
Number.parseFloat("10")
Number.parseInt()
var num3 = 177.237
console.log("num3.toFixed() is "+num3.toFixed()) // 177
console.log("num3.toFixed(2) is "+num3.toFixed(2)) // 177.24
console.log(0b001)
o/p:
1
console.log(0o010)
o/p :
8
function sum(...args) {
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
//General way
render() {
return(
<MyInput onChange={this.handleChange.bind(this) } />
);
}
//With Arrow Function
render() {
return(
<MyInput onChange={ (e) => this.handleOnChange(e) } />
);
}
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
let city = 'Tokyo';
city.length;
let city = 'Tokyo';
city.length;
city[0];
city[3];
'hello'.toUpperCase();
'LOL'.toLowerCase();
' omg '.trim();
'spider'.indexOf('i'); //2
'vesuvius'.indexOf('u');
'cactus'.indexOf('z');
"pancake".slice(3); //cake
"pancake".slice(0, 3); //pan
// Making an array:
const colors = ["red", "orange", "yellow"];
colors[0];
push(value)
pop()
unshift(val)
shift()
const seatingChart = [
['Kristen', 'Erik', 'Namita'],
['Geoffrey', 'Juanita', 'Antonio', 'Kevin'],
['Yuma', 'Sakura', 'Jack', 'Erika']
]
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
}
}
const testScores = {
keenan: 80,
damon: 67,
kim: 89,
shawn: 91,
marlon: 72,
dwayne: 77,
nadia: 83,
elvira: 97,
diedre: 81,
vonnie: 60
}
let total = 0;
let scores = Object.values(testScores);
debugger
for (let score of scores) {
total += score;
}
const deleted = todos.splice(index, 1);
const newTodo = prompt('Ok, what is the new todo?');
const index = parseInt(prompt('Ok, enter an index to delete:'));
!Number.isNaN(index)
const deleted = todos.splice(index, 1);
console.log(`Ok, deleted ${deleted[0]}`);
if (typeof x !== 'number' || typeof y !== 'number')
function makeBetweenFunc(min, max) {
return function (num) {
return num >= min && num <= max;
}
}
let innerfunc=makeBetweenFunc(3,6);
console.log('number falls in interval (3,6) ',innerfunc(8));
function bankRobbery() {
const heroes = ['Spiderman', 'Wolverine', 'Black Panther', 'Batwoman']
function cryForHelp() {
let color = 'purple';
function inner() {
for (let hero of heroes) {
console.log(`${color}, PLEASE HELP US, ${hero.toUpperCase()}`)
}
}
inner();
}
cryForHelp();
}
bankRobbery()
const movies = [
{
title: 'Amadeus',
score: 99
},
{
title: 'Stand By Me',
score: 85
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
},
{
title: 'Parasite',
score: 95
},
{
title: 'Alien',
score: 90
}
]
const person = {
firstName: 'Viggo',
lastName: 'Mortensen',
fullName: function () {
return `${this.firstName} ${this.lastName}`
},
shoutName: function () {
setTimeout(() => {
//keyword 'this' in arrow functions refers to the value of 'this' when the
function is created
console.log("'this' in arrow function",this);
console.log(this.fullName())
}, 1000)
}
}
person.shoutName()
person.shoutName()
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20];
numbers.forEach(function (el) {
if (el % 2 === 0) {
console.log(el)
}
})
movies.forEach(function (movie) {
console.log(`${movie.title} - ${movie.score}/100`)
})
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
}
return min;
})
const exams = [80, 98, 92, 78, 77, 90, 89, 84, 81, 77]
function sum(...nums) {
return nums.reduce((total, el) => total + el)
}
sum(1,2,3) // 6
// SPREAD IN ARRAYS
const cats = ['Blue', 'Scout', 'Rocket'];
const dogs = ['Rusty', 'Wyatt'];
const dataFromForm = {
email: '[email protected]',
password: 'tobias123!',
username: 'tfunke'
}
const newUser = { ...dataFromForm, id: 2345, isAdmin: false }
String.prototype.yell = function() {
return `OMG!!! ${this.toUpperCase()}!!!!! AGHGHGHG!`;
};
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
//We can overwrite an existing Array method like pop (not a good idea):
Array.prototype.pop = function() {
return 'SORRY I WANT THAT ELEMENT, I WILL NEVER POP IT OFF!';
};
const nums = [ 6, 7, 8, 9 ];
nums.pop(); // "SORRY I WANT THAT ELEMENT, I WILL NEVER POP IT OFF!"
const response = await fetch(`${FIREBASE_DOMAIN}/quotes.json`);
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Could not fetch quotes.');
}
document.createElement('div')
pokemon.appendChild(newImg);
const allImages = document.getElementsByTagName('img');
const squareImages = document.getElementsByClassName('square');
const links = document.querySelectorAll('p a');
container.classList.toggle('hide');
const usernameInput = tweetForm.elements.username;
tweetsContainer.addEventListener('click', function (e) {
e.target.nodeName === 'LI' && e.target.remove();
})
document.body.append(img)
typeof "John Doe" // Returns "string"
typeof 3.14 // Returns "number"
typeof true // Returns "boolean"
typeof 234567890123456789012345678901234567890n // Returns bigint
typeof undefined // Returns "undefined"
typeof null // Returns "object" (kind of a bug in JavaScript)
typeof Symbol('symbol') // Returns Symbol
var x = 3;
var y = "3";
x - y //Returns 0 since the variable y (string type) is converted to a number type
var x = 220;
var y = "Hello";
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
var z = undefined;
if (x && y) {
console.log("Code runs"); // This block runs because x && y returns "Hello" (Truthy)
}
if (x || z) {
console.log("Code runs"); // This block runs because x || y returns 220(Truthy)
}
eval()
parseInt()
parseFloat()
escape()
unescape()
var x = 50;
var y = 30;
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
return quoteA.id > quoteB.id ? 1 : -1;
} else {
return quoteA.id < quoteB.id ? 1 : -1;
}
});
Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com