Prince Joal
Software Engineer
  • Name: Prince

  • Birthday: 28 February 1993

  • Job: Freelancer

  • Email: [email protected]

  • Skype: 1081a1d198d8081c

javascript with prince joal

JavaScript (usually shortened as JS) is a lightweight, interpreted, object-oriented programming language with first-class functions. It’s best known as the scripting language for Web pages, although it’s also used in many non-browser applications. Dynamic, multi-paradigm, prototype-based scripting language that supports object-oriented, imperative, and functional programming paradigms.This article will teach you some fundamental or advanced javascript functions that will assist you in writing code.

Use at() on array and string

// From
const arr = [1,2,3,4];
arr[arr.length-2]; // 3
arr.slice(-2)[0]; // 3

const str = "1234"
str[str.length-2] // '3'
str.slice(-2)[0] // '3'

// to
const arr=[1,5,3,2]
arr.at(-2) //3

const str = "1234"
str.at(-2) //3

 

There are 3 way’s to do a shallow copy of an array

// First

const arrData = [1,2,3,4];
const arrDataCopy = [...arrData];

// Second

const arrData=[1,2,3,4];
const arrDataCopy=arrData.slice();

//third
const arrData=[1,2,3,4];
const arrDataCopy=Array.from(arrData);

 

Convert Object to array

// OBJECT.ENTRIES() & OBJECT.VALUES()
// This is a feature that was introduced in ES8 that allows you to convert a literal object into a key/value pair array.

const devs = { senior: 'Tarun', junior: 'Prince', fresher: 'Nishit' }; 
const arr = Object.entries(devs); 
console.log(arr);

/** Output:
[ 'senior', 'Tarun' ],
[ 'junior', 'Prince' ],
[ 'fresher', 'Nishit' ]
**/


//This is also a new feature introduced in ES8 that performs a similar function to Object.entries(), but without the key part.
const devs = { senior: 'Tarun', junior: 'Prince', fresher: 'Nishit'];
const arr = Object.values(devs); 
console.log(arr);

/** Output: 
['Tarun', 'Prince', 'Nishit' ]
**/

 

ES6 new syntax checking value exist or not

// OLD
let isvalid = (user) => user && user.address && user.address.zipcode;

//NEW
let isValid = (address) => user?.address?.zipcode;

 

JavaScript ES2022 Feature

New method ‘Object.hasOwn(obj, propKey)’ provides a safe way to check if an object ‘obj’ has an own (non-inherited) property with the key “propKey

const proto = {
protoProp: 'protoProp', 
}; 

const obj = {
__proto__: proto,
objProp: 'objProp',
}

assert.equal('protoProp' in obj, true); // (A)

assert.equal(Object.hasOwn(obj, protoProp'), false); // (B) 

assert.equal(Object.hasown(proto, 'protoProp'), true); // (0)


// Note that in detects inherited properties (line A), while Object hasown() 
// only detects own properties (lines B and C).

for more info click here

 

 

Callback functionality

Callbacks A callback function can be defined as a function passed into another function as a parameter.

// function 

function joal(name, callback) {
console.log('Hi' + ' ' + name); 
callback();
}


// callback function 

function callme() {
console.log('I am callback function');
}


// passing function as an argument 
joal('Prince', callme);

 

 

Generators in JavaScript?

//A generator is a function that can stop midway and then continue from where it stopped. Also, it produces a
sequence of results instead of a single value.


function * generator Function() {
	console.log('First log');
	yield 'Hello, ';
	console.log('second log' );
	yield 'World!';
}

	const generatorObject = generatorFunction();
	console.log(generatorObject.next().value);
	console.log(generatoróbject.next().value);
	console.log(generatorObject.next(.value);


		// First log
		// Hello,
		// Second log
		// World!


//Some use cases: implementing iterables, better async functionality, infinite data streams....

 

Async & Await in JavaScript

//Async & Await Stop and wait until something is resolved.
// • We use the async keyword with a function to represent that the function
is an asynchtonos function. 
// • The async function returns a promise.

const showPost = async() = {
const res = await fetch('https://princejoal.com/post');
}
showPost();

 

 

Count occurrences in Array

const arr = ['a', 'a', 'b', 'c', 'c','d', 'b', 'c'];
const occurrences = arr.reduce((map, item) => { 
		if (map.has(item)) {
				// We have already encountered this item
				// simply increment the count
				map.set(item, map.get(item) + 1);
			} else {
				// This is the first time encountering
				// set the initial count value for this item 
				map.set(item, 1);
			}
				return map;
	}, new Map());

console.log(Occurrences); 
// {'a' → 2, 'b' → 2, 'c' → 3 , 'd' → 1}

 

Select Random element from array

let fruits = ["Apple", "Banana", "Mango", "Orange"]; 
let index = Math.floor(Math.random() * fruits.length);

console.log(fruits[index]);

 

Intersection of a Two arrays

const intersection = (arri, arr2) => {
	const set = new Set(arri); 
	return arr2.filter((x) => set.has(x));
};
	
	console.log(
			intersection([1, 2, 3], [2, 3, 4]) );
	);
	// [2, 3]

 

Javascript String Cheatsheet

"wonderful".at(-1);                                 // l
"wonderful".charAt(2);								// n
"wonderful".concat(" ", "house");					// wonderful house
“wonderful".endsWith("q");							// false
"wonderful".startsWith("w");						// true
"wonderful".includes("der");						// true
"wonderful".indexOf("d");							// 3
"wonderful".split("");								// ["w","o","n","d","e","r","f","u","l"]
"wonderful".padstart(20, .);						// ...................wonderful
"wonderful".padEnd( 20, ".");						// wonderful...................
"wonderful".repeat(3);								// wonderfulwonderfulwonderful
"wonderful".replace("ful", ");						// wonder
"wonderful".search("f");							// 6
"wonderful.substr(3,4);								// derf
"wonderful".substring(3,4);							// d
"wonderful".slice(3,4);								// d
"wonderful".toUpperCase();							// WONDERFUL
"WONDERFUL".toLowerCase();							// wonderful

Javascript Number & Maths Cheatsheet

// Numbers

var pi = 3.141;
pi.toFixed(0);          // returns 3
pi.toFixed(2);          // returns 3.14 - for working with money
pi.toPrecision(2)       // returns 3.1
pi.valueOf();           // returns number
Number(true);           // converts to number
Number(new Date())      // number of milliseconds since 1970
parseInt("3 months");   // returns the first number: 3
parseFloat("3.5 days"); // returns 3.5
Number.MAX_VALUE        // largest possible JS number
Number.MIN_VALUE        // smallest possible JS number
Number.NEGATIVE_INFINITY// -Infinity
Number.POSITIVE_INFINITY// Infinity


// Math.
var pi = Math.PI;       // 3.141592653589793
Math.round(4.4);        // = 4 - rounded
Math.round(4.5);        // = 5
Math.pow(2,8);          // = 256 - 2 to the power of 8
Math.sqrt(49);          // = 7 - square root 
Math.abs(-3.14);        // = 3.14 - absolute, positive value
Math.ceil(3.14);        // = 4 - rounded up
Math.floor(3.99);       // = 3 - rounded down
Math.sin(0);            // = 0 - sine
Math.cos(Math.PI);      // OTHERS: tan,atan,asin,acos,
Math.min(0, 3, -2, 2);  // = -2 - the lowest value
Math.max(0, 3, -2, 2);  // = 3 - the highest value
Math.log(1);            // = 0 natural logarithm 
Math.exp(1);            // = 2.7182pow(E,x)
Math.random();          // random number between 0 and 1
Math.floor(Math.random() * 5) + 1;  // random integer, from 1 to 5

 

Javascript dates Cheatsheet

//Tue Aug 09 2022 23:24:09 GMT+0530 (India Standard Time)
	
	var d = new Date();
//1660067649246 miliseconds passed since 1970
	Number(d) 
	Date("2017-06-23");                 // date declaration
	Date("2017");                       // is set to Jan 01
	Date("2017-06-23T12:00:00-09:45");  // date - time YYYY-MM-DDTHH:MM:SSZ
	Date("June 23 2017");               // long date format
	Date("Jun 23 2017 07:45:00 GMT+0100 (Tokyo Time)"); // time zone
	


// Get Times
	var d = new Date();
	a = d.getDay();     // getting the weekday
	getDate();          // day as a number (1-31)
	getDay();           // weekday as a number (0-6)
	getFullYear();      // four digit year (yyyy)
	getHours();         // hour (0-23)
	getMilliseconds();  // milliseconds (0-999)
	getMinutes();       // minutes (0-59)
	getMonth();         // month (0-11)
	getSeconds();       // seconds (0-59)
	getTime();          // milliseconds since 1970
	

// Setting part of a date
	var d = new Date();
	d.setDate(d.getDate() + 7); // adds a week to a date
	setDate();          // day as a number (1-31)
	setFullYear();      // year (optionally month and day)
	setHours();         // hour (0-23)
	setMilliseconds();  // milliseconds (0-999)
	setMinutes();       // minutes (0-59)
	setMonth();         // month (0-11)
	setSeconds();       // seconds (0-59)
	setTime();          // milliseconds since 1970)

 

Javascript Arrays Cheatsheet


var dogs = ["Bulldog", "Beagle", "Labrador"]; 
var dogs = new Array("Bulldog", "Beagle", "Labrador");  // declaration

alert(dogs[1]);             // access value at index, first item being [0]
dogs[0] = "Bull Terier";    // change the first item

for (var i = 0; i < dogs.length; i++) {     // parsing with array.length
console.log(dogs[i]);
}

								// Methods
dogs.toString();                        // convert to string: results "Bulldog,Beagle,Labrador"
dogs.join(" * ");                       // join: "Bulldog * Beagle * Labrador"
dogs.pop();                             // remove last element
dogs.push("Chihuahua");                 // add new element to the end
dogs[dogs.length] = "Chihuahua";        // the same as push
dogs.shift();                           // remove first element
dogs.unshift("Chihuahua");              // add new element to the beginning
delete dogs[0];                         // change element to undefined (not recommended)
dogs.splice(2, 0, "Pug", "Boxer");      // add elements (where, how many to remove, element list)
var animals = dogs.concat(cats,birds);  // join two arrays (dogs followed by cats and birds)
dogs.slice(1,4);                        // elements from [1] to [4-1]
dogs.sort();                            // sort string alphabetically
dogs.reverse();                         // sort string in descending order
x.sort(function(a, b){return a - b});   // numeric sort
x.sort(function(a, b){return b - a});   // numeric descending sort
highest = x[0];                         // first item in sorted array is the lowest (or highest) value
x.sort(function(a, b){return 0.5 - Math.random()});     // random order sort

 

for more reading other artical related aws click here

Tags: Javascript

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x