0% found this document useful (0 votes)
25 views22 pages

Simple To Memorize - Js

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

Simple To Memorize - Js

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

Simple selectors (select elements based on name, id, class)

Combinator selectors (select elements based on a specific relationship between them)


Pseudo-class selectors (select elements based on a certain state)
Pseudo-elements selectors (select and style a part of an element)
Attribute selectors (select elements based on an attribute or attribute value)

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

Combinator selectors (select elements based on a specific relationship between them)


--------------------------------------------------------------------------------

div p {
background-color: yellow;
}

div > p {
background-color: yellow;
}

div + p {
background-color: yellow;
}
div ~ p {
background-color: yellow;
}

Pseudo-class selectors (select elements based on a certain state)


---------------------------------------------------------------------
What are Pseudo-classes?
A pseudo-class is used to define a special state of an element.

For example, it can be used to:

Style an element when a user mouses over it


Style visited and unvisited links differently
Style an element when it gets focus

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;
}

/* mouse over link */


a:hover {
color: #FF00FF;
}

/* selected link */
a:active {
color: #0000FF;
}

Pseudo-element selectors (select elements based on a certain state)


-----------------------------------------------------------------
A CSS pseudo-element is used to style specified parts of an element.

For example, it can be used to:

Style the first letter, or line, of an element


Insert content before, or after, the content of an element

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;
}

Attribute selectors (select elements based on an attribute or attribute value)


--------------------------------------------------------------------------

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".

import { createBrowserHistory } from 'history';

export const history = createBrowserHistory();

import { Redirect, Switch, Route, Router } from "react-router-dom";

<Router history={history}>

</Router>

Array to object:
------------------

Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}

{ ...['a', 'b', 'c'] }

['a', 'b', 'c'].reduce((a, v) => ({ ...a, [v]: v}), {})


// { a: "a", b: "b", c: "c" }

Object to Array :
-----------------

const person = {
firstName: 'John',
lastName: 'Doe'
};

const propertyNames = Object.keys(person);


const propertyValues = Object.values(person);
const entries = Object.entries(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

const points = [40, 100, 1, 5, 25, 10];


points.sort(function(a, b){return a - b});
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
Array.join();

const fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits[fruits.length] = "Kiwi";

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 :
--------------------

const myArray = text.split(" ");

const myArray = text.split(""); - split characters including spaces

const myArray = text.split("o");


text.split(); - same text is returned

text.substr(1, 4); - from index 1 pics 4 characters


str.substr(2); - index 2 to end
text.substring(1, 4); - index 4 excluded

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");

Array elements can be deleted using the JavaScript operator delete.

Using delete leaves undefined holes in the array.

Use pop() or shift() instead.

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))

const food = { beef: '🥩', bacon: '🥓' };

const cloneFood = Object.assign({}, food);

console.log(cloneFood);
// { beef: '🥩', bacon: '🥓' }

const food = { beef: '🥩', bacon: '🥓' };

const cloneFood = JSON.parse(JSON.stringify(food));

console.log(cloneFood);
// { beef: '🥩', bacon: '🥓' }

valueOf() method
normalObj.hasOwnProperty("p")

var foo = 'bar'


var baz = { foo }
console.log(baz.foo)

"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++

var myobj = new Object;


myobj.a = 5;
myobj.b = 12;

// Removes the ‘a’ property


delete myobj.a;
console.log ("a" in myobj) // yields "false"
var val1 = {name: "Tom"};
var val2 = {name: "Tom"};
console.log(val1 == val2) // return false

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

var val1 = {name: "Tom"};


var val2 = val1

console.log(val1 == val2) // return true


console.log(val1 === val2) // return true

// Whole-script strict mode syntax


"use strict";
v = "Hi! I'm a strict mode script!"; // ERROR: Variable v is not declared

the concept of hoisting does not apply to scripts that are run in the Strict Mode.

var balance = 5000


console.log(typeof balance)
var balance = {message:"hello"}
console.log(typeof balance)

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);

let text = "The rain in SPAIN stays mainly in the plain";


text.match(/ain/);

let text = "The rain in SPAIN stays mainly in the plain";


text.match(/ain/gi);

let text = "Mr. Blue has a blue house";


let position = text.search("Blue");

let text = "Mr. Blue has a blue house";


let position = text.search(/Blue/);

let text = "Mr. Blue has a blue house";


let position = text.search(/blue/gi);

let text = "Hello world!";

// Look for "Hello"

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);

// Look for "W3Schools"


let result2 = /W3Schools/.exec(text);

let text = "The best things in life are free";


let pattern = /e/;
let result = pattern.test(text); // returns true if pattern exists in text

var str = "Apples are round, and apples are juicy.";


var sliced = str.slice(3, -2);
console.log(sliced); // o/p : les are round, and apples are juic

var str = "Apples are round, and apples are juicy.";


var splitted = str.split(" ", 4); // o/p : [ 'Apples', 'are', 'round,', 'and' ]

var str = "Apples are round, and apples are juicy.";


//str.substr(startIndex,num_of_elements_from_startindex)
console.log("(1,2): " + str.substr(1,2)); //pp
console.log("(-2,2): " + str.substr(-2,2)); //y.
console.log("(1): " + str.substr(1)); //pples are round, and apples are juicy.
console.log("(-20, 2): " + str.substr(-20,2)); // nd
console.log("(20, 2): " + str.substr(20,2)); // d

o/p:
----

(1,2): pp
(-2,2): y.
(1): pples are round, and apples are juicy.
(-20, 2): nd
(20, 2): d

var str = "Apples are round, and apples are juicy.";


console.log("(1,2): " + str.substring(1,2)); // p
console.log("(0,10): " + str.substring(0, 10)); //Apples are
console.log("(5): " + str.substring(5));//s are round, and apples are juicy

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.

var str = new String("Hello world");


console.log(str.valueOf( ));

var str = 'hello world!!!';


console.log(str.startsWith('hello'));

var str = 'Hello World !!! ';

console.log(str.endsWith('Hello'));
console.log(str.endsWith('Hello',5));// checks 'Hello' only in first 5 characters

var str = 'Hello World';

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

var myBook = new String("Perl");


console.log(myBook.repeat(2));

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()} !!`);

var text =`Hello \n World`


console.log(text)

var raw_text = String.raw`Hello \n World `


console.log(raw_text) // prints string as it is with out breaking line @ \n

Tagged Templates - need to know

var arr_names = new Array(4)


var arr_names = new Array(4)

var names = new Array("Mary","Tom","Jack","Jill")


for(var i = 0;i<names.length;i++) {
console.log(names[i])
}
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
var alphaNumeric = alpha.concat(numeric);

function isBigEnough(element, index, array) {


return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
console.log("Test Value : " + passed ); // returns true or false

function isBigEnough(element, index, array) {


return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].filter(isBigEnough);
console.log("Test Value : " + passed ); // returns array of elements satisfying
condition

var nums = new Array(12,13,14,15)


console.log("Printing original array......")

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)
})

var index = [12, 5, 8, 130, 44].indexOf(8);


var arr = new Array("First","Second","Third");
var str = arr.join();console.log("str : " + str );
var str = arr.join(", ");

var index = [12, 5, 8, 130, 44].lastIndexOf(8);


console.log("index is : " + index );
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
console.log("roots is : " + roots );

var numbers = [1, 4, 9];


var element = numbers.pop();

var numbers = new Array(1, 4, 9);


var length = numbers.push(10);

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()

var arr = [10, 1, 2, 3].shift();


console.log("Shifted value is : " + arr )

var arr = ["orange", "mango", "banana", "sugar", "tea"];


console.log("arr.slice( 1, 2) : " + arr.slice( 1, 2) ); // arr.slice( 1, 2) : mango

function isBigEnough(element, index, array) {


return (element >= 10);
}
var retval = [2, 5, 8, 1, 4].some(isBigEnough);
console.log("Returned value is : " + retval );

var arr = new Array("orange", "mango", "banana", "sugar");


var sorted = arr.sort(); // arr itself will get sorted

var arr = ["orange", "mango", "banana", "sugar", "tea"];


var removed = arr.splice(2, 0, "water");
console.log("After adding 1: " + arr );
console.log("removed is: " + removed);

o/p:
-----
After adding 1: orange,mango,water,banana,sugar,tea
removed is:

removed = arr.splice(3, 1);//o/p: removed is: sugar

var arr = new Array("orange", "mango", "banana", "sugar");


var str = arr.toString(); // o/p: orange,mango,banana,sugar

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

var numbers = [1, 2, 3];


var oddNumber = numbers.findIndex((x) => x % 2 == 1); // o/p : 0

var numbers = [1, 2, 3];


var val = numbers.entries();
val.next() // o/p : { value: [ 0, 1 ], done: false }

"use strict"
for (let i of Array.from('hello')) {
console.log(i)
}

o/p :
-------
h
e
l
l
o

Array.from(['a', 'b'].keys() // o/p : [ 0, 1 ]

"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])
}

var multi = [[1,2,3],[23,24,25]]


function disp() {
return new Array("Mary","Tom","Jack","Jill")
}
var nums = disp()
for(var i in nums) {
console.log(nums[i])
}

let names = ['Mohtashim','Kannan','Kiran']


let [n1,n2,n3] = names;

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)

var foo = 'bar'


var baz = { foo:foo }
console.log(baz.foo)

var obj_name = new Object();


obj_name.property = value;
OR
obj_name["key"] = value

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

// Create new role type called Guest


var guest_role = Object.create(roles);
guest_role.type = "Guest";
guest_role.displayType(); // Output:Guest

"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

var myobj = new Object;


myobj.a = 5;
myobj.b = 12;

// Removes the ‘a’ property


delete myobj.a;
console.log ("a" in myobj) // yields "false"

var val1 = {name: "Tom"};


var val2 = {name: "Tom"};
console.log(val1 == val2) // return false
console.log(val1 === val2) // return false
In the above example, val1 and val2 are two distinct objects that refer to two different
memory addresses. Hence on comparison for equality, the operator will return false.

let student = {
rollno:20,
name:'Prijin',
cgpa:7.2
}

let {name,cgpa} = student


let {name:student_name,cgpa:student_cgpa}=student
let student = {
rollno:20,
name:'Prijin',
cgpa:7.2
}

// destructuring to already declared variable


let rollno;
({rollno} = student)
console.log(rollno)

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 {c1,...others} = customers


console.log(c1)
console.log(others)

let emp = {
id:101,
address:{
city:'Mumbai',
pin:1234
}
}
let {address} = emp;

let {address:{city,pin}} = 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));

let str = 'JJavascript is Fun to Work , very Fun '


let regex = /[A-Z]/g // g stands for global matches
let result = str.match(regex);
console.log(result)

let str = 'Javascript is fun to Work , very Fun '


let regex = /Fun/gi; // replaces all
occurence of search string irrespective of case sensitivity
console.log(str.replace(regex,'enjoyable'));
console.log(str)
console.log(str.search(regex)) // index of first occcurance of search string
o/p
Javascript is enjoyable to Work , very enjoyable
Javascript is fun to Work , very Fun
15

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

let cgpa_list = [7.5,8.5,6.5,9.5]


let iter = cgpa_list.entries()
for(let cgpa of iter){
console.log(cgpa[1])
}

o/p
7.5
8.5
6.5
9.5

const products = [{name:'Books',quantity:10},


{name:'Pen',quantity:20},
{name:"Books",quantity:30}
]
console.log( products.find(p=>p.name==="Books")) //{ name: 'Books', quantity: 10 }

let nosArr = [10,20,30,40]


console.log(nosArr.fill(0,1,3))// value ,start,end //[ 10, 0, 0, 40 ]
//[10,0,0,40]

console.log(nosArr.fill(0,1)) // [10,0,0,0] // value , start

console.log(nosArr.fill(0,1)) // [10,0,0,0] // value , start


console.log(nosArr.fill(0)) // [ 0, 0, 0, 0 ]

console.log(Array.of(10))
console.log(Array.of(10,20,30))

console.log(nosArr.fill(0,1)) // [10,0,0,0] // value , start


console.log(nosArr.fill(0)) // [ 0, 0, 0, 0 ]

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]

let emp1 = {ename:'Prijin'}


let emp2 = {ename:'Prijin'}
console.log(Object.is(emp1.ename,emp2.ename)) // true

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

var dt = new Date(1993, 6, 28, 14, 39, 7);


console.log( "Formated Date : " + dt.toLocaleDateString()) //Formated Date : 28/7/1993

o/p:
Formated Date : 7/28/1993

var dt = new Date(1993, 6, 28, 14, 39, 7);


console.log( "Formated Date : " + dt.toLocaleString());

o/p:

7/28/1993, 2:39:07 PM

dt.toLocaleString('en-US', { hour12: true }) //Formated Date : 7/28/1993, 2:39:07 PM

var dt = new Date(1993, 6, 28, 14, 39, 7);


console.log( "Formated Date : " + dt.toLocaleTimeString());
dt.toLocaleTimeString('en-US', { hour12: false })
o/p:

Formated Date : 2:39:07 PM


var dateobject = new Date(1993, 6, 28, 14, 39, 7);
console.log( dateobject.valueOf()); //743850547000

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

var res = Number.isNaN(value);

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

var num = new Number(7.123456);


console.log(num.toPrecision());//7.123456
console.log(num.toPrecision(1));//7
console.log(num.toPrecision(2));//7.1
var num = new Number(10);
console.log(num.valueOf());

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;
}

let x = sum(4, 9, 16, 25, 29, 100, 66, 77);


Array.from("ABCDEFG") // Returns [A,B,C,D,E,F,G]

npm run build


npm run test
import { render, screen } from "@testing-library/react";

//General way
render() {
return(
<MyInput onChange={this.handleChange.bind(this) } />
);
}
//With Arrow Function
render() {
return(
<MyInput onChange={ (e) => this.handleOnChange(e) } />
);
}

import ReactDOM from 'react-dom';


import { React, Component } from 'react';
import { useState } from 'react';
import React from 'react';

import { useReducer } from 'react';


import { useEffect, useState } from 'react';
import { useRef, useState } from 'react';
import { useContext } from 'react';
import { Fragment } from 'react';
ReactDOM.render(<App />, document.getElementById('root'));
import './index.css';
import App from './App';
import mealsImage from '../../assets/meals.jpg';
import { render, waitFor, screen } from "@testing-library/react";

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

"pump".replace("p", "b"); //"bump" - only replaces first "p"

const color = "olive green";


const msg = `My favorite color is: ${color}`

const str = `There are ${60 * 60 * 24} seconds in a day`

// 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']
]

for (let i = 0; i < seatingChart.length; i++) {


const row = seatingChart[i];
console.log(`ROW #${i + 1}`)
for (let j = 0; j < row.length; j++) {
console.log(row[j])
}
}
const subreddits = ['cringe', 'books', 'chickens', 'funny', 'pics', 'soccer', 'gunners'];

for (let subreddit of subreddits) {


console.log(`Visit reddit.com/r/${subreddit}`)
}
const seatingChart = [
['Kristen', 'Erik', 'Namita'],
['Geoffrey', 'Juanita', 'Antonio', 'Kevin'],
['Yuma', 'Sakura', 'Jack', 'Erika']
]

for (let row of seatingChart) {


for (let student of row) {
console.log(student);

Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
}
}

for (let char of "hello world") {


console.log(char)
}

const testScores = {
keenan: 80,
damon: 67,
kim: 89,
shawn: 91,
marlon: 72,
dwayne: 77,
nadia: 83,
elvira: 97,
diedre: 81,
vonnie: 60
}

for (let person in testScores) {


console.log(`${person} scored ${testScores[person]}`);
}

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 newMovies = movies.map(movie => (


`${movie.title} - ${movie.score / 10}`
))
console.log('newMovies',newMovies);

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];

const filtered = numbers.filter(n => {


return n < 10
})
console.log('filtered',filtered);

const badMovies = movies.filter(m => m.score < 70)


movies.filter(m => m.score > 80).map(m => m.title);
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];

const doubles = numbers.map(function (num) {


return num * 2;
})

const titles = movies.map(function (movie) {


return movie.title.toUpperCase();
})
const total = prices.reduce((total, price) => total + price)

const minPrice = prices.reduce((min, price) => {


if (price < min) {
return price;

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 highestRated = movies.reduce((bestMovie, currMovie) => {


if (currMovie.score > bestMovie.score) {
return currMovie;
}
return bestMovie;
})

const exams = [80, 98, 92, 78, 77, 90, 89, 84, 81, 77]

exams.every(score => score >= 75)


movies.some(movie => movie.year > 2015)
const scores = [929321, 899341, 888336, 772739, 543671, 243567, 111934];

const [gold, silver, bronze, ...everyoneElse] = scores;


const { email, firstName, lastName, city, bio } = user;

const { born: birthYear, died: deathYear = 'N/A' } = user;

function fullName({ firstName, lastName }) {


return `${firstName} ${lastName}`
}
movies.filter(({ score }) => score >= 90)
movies.map(({ title, score, year }) => {
return `${title} (${year}) is rated ${score}`
})

function sum(...nums) {
return nums.reduce((total, el) => total + el)
}
sum(1,2,3) // 6

function raceResults(gold, silver, ...everyoneElse) {


console.log(`GOLD MEDAL GOES TO: ${gold}`)
console.log(`SILVER MEDAL GOES TO: ${silver}`)
console.log(`AND THANKS TO EVERYONE ELSE: ${everyoneElse}`)
}
const nums = [13, 4, 5, 21, 3, 3, 1, 2, 7, 6, 4, 2, 53456];
// SPREAD IN FUNCTIONS
Math.max(nums) //NaN
Math.max(...nums) //53456

// SPREAD IN ARRAYS
const cats = ['Blue', 'Scout', 'Rocket'];
const dogs = ['Rusty', 'Wyatt'];

const allPets = [...cats, ...dogs];


// SPREAD IN OBJECTS
const feline = { legs: 4, family: 'Felidae' };
const canine = { isFurry: true, family: 'Caninae' };

const catDog = { ...feline, ...canine };

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.');
}

const response = await fetch(`${FIREBASE_DOMAIN}/quotes.json`, {


method: 'POST',
body: JSON.stringify(quoteData),
headers: {
'Content-Type': 'application/json',
},
});
const data = await response.json();
{props.comments.map((comment) => (
<CommentItem key={comment.id} text={comment.text} />
))}
const prodIndex = curState.products.findIndex(p => p.id === productId);

const allLinks = document.querySelectorAll('a');

for (let link of allLinks) {


link.innerText = 'I AM A LINK!!!!'
}

for (let link of allLinks) {


link.style.color = 'rgb(0, 108, 134)';
link.style.textDecorationColor = 'magenta';
link.style.textDecorationStyle = 'wavy'
}
const container = document.querySelector('#container');

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;

x | | y // Returns 220 since the first value is truthy

x | | z // Returns 220 since the first value is truthy

x && y // Returns "Hello" since both the values are truthy

y && z // Returns undefined since the second value is falsy

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)
}

isNaN("Hello") // Returns true


isNaN(345) // Returns false
isNaN('1') // Returns false, since '1' is converted to Number type which results in 0 ( a
number)
isNaN(true) // Returns false, since true converted to Number type results in 1 ( a
number)
isNaN(false) // Returns false
isNaN(undefined) // Returns true

eval()
parseInt()
parseFloat()
escape()
unescape()
var x = 50;

var y = 30;

var a = eval("x * y")


parseInt("15.00")
var c = parseFloat("40")
document.write("The result of parseFloat is: " + c + "<br>")
let msg1 = escape("JavaScript Predefined Functions")
let msg2 = unescape("JavaScript Predefined Functions")
document.cookie = "key1 = value1; key2 = value2; expires = date";
getElementByClass(‘classname’)//: Gets all the HTML elements that have the specified
classname.
getElementById(‘idname’)//: Gets an HTML element by its ID name.
getElementbyTagName(‘tagname’)//: Gets all the HTML elements that have the specified
tagname.
querySelector()//: Takes CSS style selector and returns the first selected HTML element.

import { useState, useEffect, useCallback } from 'react';

import { useParams } from 'react-router-dom';


const params = useParams();
{props.comments.map((comment) => (
<CommentItem key={comment.id} text={comment.text} />
))}

import { useRef, useEffect } from 'react';


import { Fragment } from 'react';

import { NavLink } from 'react-router-dom';


import { Link } from 'react-router-dom';
import { Prompt } from 'react-router-dom';
import { useHistory, useLocation } from 'react-router-dom';
quotes.sort((quoteA, quoteB) => {
if (ascending) {

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;
}
});

const history = useHistory();


const location = useLocation();

const queryParams = new URLSearchParams(location.search);

const isSortingAscending = queryParams.get('sort') === 'asc';


history.push({
pathname: location.pathname,
search: `?sort=${(isSortingAscending ? 'desc' : 'asc')}`
});

import { useReducer, useCallback } from 'react';

const history = useHistory();


history.push('/quotes');

import { useParams, Route, Link, useRouteMatch } from 'react-router-dom';

const match = useRouteMatch();


const params = useParams();
import { Route, Switch, Redirect } from 'react-router-dom';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createSlice } from '@reduxjs/toolkit';

import { useContext } from 'react';


const cartCtx = useContext(CartContext);
const numberOfCartItems = items.reduce((curNumber, item) => {
return curNumber + item.amount;
}, 0);
import { Provider } from 'react-redux';
import { configureStore } from '@reduxjs/toolkit';

import { BrowserRouter } from 'react-router-dom';


import { Route, Switch, Redirect } from 'react-router-dom';
import { NavLink } from 'react-router-dom';

Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com

You might also like