/* Enabling design mode will make the entire web page editable, just by clicking and typing. To use it,
open up the console and run: */
document.designMode = "on";<input type="range" min="1" max="5" value="2" />
<input type="search" />
<input type="tel" />
<input type="time" />
<input type="color" />
<input type="datetime-local" />
<input type="week" />
<input type="month" />
<input type="url" /><!-- Can give tooltip to any tag with title -->
<p title="Tooltip">Tooltip</p><!-- different favicon for light and dark mode -->
<head>
<link
rel="icon"
type="image/svg+xml"
href="dark-icon.svg"
media="(prefers-color-scheme:dark)"
/>
<link
rel="icon"
type="image/svg+xml"
href="light-icon.svg"
media="(prefers-color-scheme:light)"
/>
</head><!-- When you need to run some calculations on your inputs and get a result instantly, you can use the <output> element to display the results without writing any external JS -->
<form
oninput="total.value=Number(amount.value) + (Number(amount.value) * Number(tip.value)/100)"
>
<input type="number" id="amount" value="0" /> +
<input type="number" id="tip" value="0" /> =
<output name="total" for="amount tip"></output>
</form><!-- You can add a special <meta> tag inside of your document head to refresh the page at a set interval or to redirect users to different websites after a set delay -->
<!-- refresh after 30s -->
<meta http-equiv="refresh" content="30" />
<!-- redirect after 30s -->
<meta http-equiv="refresh" content="30;https://www.youtube.com/" /><!-- For users who are on mobile devices, you can use the <input/> tag with a capture attribute to open the user's camera and allow them to take a photo or video to upload to your website. On desktop the default behavior of uploading files is kept -->
<!-- Opens back facing camera to take video -->
<input type="file" capture="environment" accept="video/*" />
<!-- Opens front facing camera to take photo -->
<input type="file" capture="user" accept="image/*" /><!-- When you have lots of images in your website but you don't wanna wait a longer time for the browser to load all the images then show the content of the site you can lazy load images it will show other content of the site then slowly load images -->
<img src="image.png" loading="lazy" alt="image" /><!-- Disable right click for the entire website -->
<body oncontextmenu="return false"></body>
<!-- Disable right click for a specific element-->
<section oncontextmenu="return false"></section><!-- input suggestion -->
<input list="lists" />
<datalist id="lists">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</datalist><!-- multiple image with different widths have a single scaling -->
<picture>
<source media="{min-width:650px}" srcset="image.png" />
<source media="{min-width:550px}" srcset="image.png" />
<img src="image.png" style="width:auto" />
</picture><!-- This lets the page be rendered first and then render the images slowly -->
<img src="image.png" loading="lazy" /><!-- This is useful where you have many anchors tag but their base url is same -->
<head>
<base href="http://twitter.com/" target="_blank"> />
</head>
<body>
<a href="Elon musk">
</body><!-- This will redirect the user to provided url in 4s and then set to 0 for an immediate redirect -->
<head>
<meta http-equiv="refresh" content="4;URL=URL" />
</head><!-- Group the options -->
<select>
<optgroup label="Fruit">
<option>Apple</option>
<option>Mango</option>
<option>Banana</option>
</optgroup>
<optgroup label="Car">
<option>Bugatti</option>
<option>Lamborgini</option>
<option>Koenigseg</option>
</optgroup>
</select>-
Dialog/Modal
<dialog> <form> <input type="text" /> <button formmethod="dialog" type="submit">Cancel</button> <button type="submit">Submit</button> </form> </dialog>
const dialog = document.querySelector("dialog"); dialog.show(); // Opens a non-modal dialog dialog.showModal(); // Opens a modal dialog.addEventListener("click", (e) => { const dialogDimensions = dialog.getBoundingClientRect(); if ( e.clientX < dialogDimensions.left || e.clientX > dialogDimensions.right || e.clientY < dialogDimensions.top || e.clientY > dialogDimensions.bottom ) { dialog.close(); // Closes the dialog } });
-
Accordion
<details> <summary>Open</summary> <p>lorem ipsem</p> </details>
-
Progress bar
<label for="prog">Download</label> <progress id="prog" value="50" max="100"></progress>
-
Autocomplete
<input list="lists"> <datalist id="lists"> <option>op1</option> <option>op2</option> <option>op3</option> </datalist> </input>
-
Popover
<button popovertarget="pop">Open</button> <div id="pop" popover> <p>lorem ipsem</p> </div>
-
Multiple
<input type="file" multiple />
The multiple attribute allows the user to enter multiple values on an input. It is a boolean attribute valid for file or email input types and the select element. For an email input, if and only if the multiple attribute is specified, the value can be a list of comma-separated email addresses. Any whitespace is removed from each address in the list. For a file input, the user can select multiple files in the as usual (holding down Shift or Crtl).
-
Accept
<input type="file" accept=".png, .jpg" />
The input element has the accept attribute that allows you to specify the types of files the user can upload. You need to pass it a string containing a comma-separated list of unique file type specifiers. You can also use it to specify only audio, image, or video format.
-
Contenteditable
<div contenteditable="true">I'm a cool editable div ;)</div>
contenteditable is a global attribute (common to all HTML elements) that makes the HTML content editable by the user or not. However, be careful with changes only made to visible content vs the DOM content.
-
Spellcheck
<p contenteditable="true" spellcheck="true">Thanks furr checkinng my speling :)</p>
The spellcheck is another global attribute that you can use to check spelling and grammar on HTML elements such as input fields and other editable elements. Note: Typically non-editable elements are not checked for spelling errors, even if the spellcheck attribute is set to true and the browser supports spellchecking.
-
Translate
<footer><p translate="no">LearnPine</p></footer>
translate tells the browser whether the content should be translated or not. For instance, you can use it to prevent Google Translate from automatically trying to translate your company's or brand's name.
-
Poster
<video controls src="https://bit.ly/3nWh78w" poster="posterImage.png"></video>
Use the poster attribute to specify an image to be shown while the video is downloading, or until the user hits the play button. If the image isn't specified, nothing is displayed until the first frame is available, then the first frame is shown as the poster frame.
-
Download
<a href="index.html" download="fileName">Download me :)</a>
Use the download attribute combined with an
aelement to instruct browsers to download a URL instead of navigating to it, so the user will be prompted to save it as a local file. You can also specify the file name. -
Style
<body> <style contenteditable style="display:block; white-space:pre;"> html { background: #bada55; } </style> </body>
<header>and<footer>: These elements represent the header and footer of a document or a section.<nav>: This element is used for the part of the website that contains navigation links.<article>: This element represents a self-contained composition in a document, like a blog post, a news story, or a forum post.<section>: This element represents a standalone section of a document, which doesn’t have a more specific semantic element to represent it.<aside>: This element is used for content that is indirectly related to the main content, like a sidebar or pull quotes.<figure>and<figcaption>: These elements are used for representing a piece of self-contained flow content, optionally with a caption.<details>: Defines additional details that the user can view or hide.<summary>: Defines a visible heading for a<details>element.<main>: Specifies the main content of a document.<mark>: Defines marked/highlighted text.<time>: Defines a date/time
<p hidden></p>
hide the content of the element<video poster="image.png"></video> Shown while the video isn't playing<optgroup></optgroup>
is a great way to add a little definition between groups of options inside a select box<acronym></acronym> is a way to define or further explain a group of words. When you hover
over text that has the acronym tag used, a box appears below with the text from the title
tag.<wbr></wbr> Defines a word break opportunity in a long string of text.<address></address>
Describes an address information<article></article>
Defines an article<aside></aside>
Describes contain set(or write) on aside place in page contain<audio></audio> Specific audio content<video></video> Used to embed video content.<base /> Define a base URL for all the links with in a web page<bb></bb> Define browser command, that command invoke as per client action<bdo></bdo> Specific direction of text display<blockquote></blockquote>
Specifies a long quotation<canvas></canvas> Specifies the display graphics on HTML web document<caption></caption>
Define a table caption<cite></cite> Specifies a text citation<code></code> Specifies computer code text<command></command> Define a command button, invoke as per user action<datalist></datalist> Define a list of pre-defined options surrounding input tag<details></details>
Define a additional details hide or show as per user action<embed /> Define a embedding external application using a relative plug-in<figcaption></figcaption>
Represents a caption text corresponding with a figure element<kbd></kbd>Used to identify text that are represents keyboard input.<legend></legend>
Used to add a caption (title) to a group of related form elements that are grouped
together into the fieldset tag.<map></map>Defines an clickable image map.<mark></mark>Used to highlighted (marked) specific text.<menu></menu> Used to display a unordered list of items/menu of commands.<meter></meter>Used to measure data within a given range.<param />
Provides parameters for embedded object element.<pre></pre>
Used to represents preformatted text.<progress></progress>Represents the progress of a task.<samp></samp> Represents text that should be interpreted as sample output from a computer
program.<sub></sub> Represents inline subscript text.<sup></sup>Represents inline superscript text.<time></time>Represents the date and/or time in an HTML document.HTML Table Generator
HTML Marquee Generator
HTML Marquee Falling Text Code Generator
| Character | Decimal Entity | Name Entity | Description |
|---|---|---|---|
| None Breaking Space | |||
| " | " | " | Double Quotation mark |
| ' | ' | ' | Single Quotation mark |
| & | & | & | ampersand |
| < | < | < | less-than |
| > | > | > | greater-than |
| # | # | Hass Sign | |
| % | % | Percentage Sign | |
| ( | ( | Left Parenthesis | |
| ) | ) | Right Parenthesis | |
| * | * | Left Parenthesis | |
| + | + | Plus Sign | |
| - | - | Hyphen | |
| / | / | Slash |
| Character | Decimal Entity | Name Entity | Description |
|---|---|---|---|
| © | © | © | Copyright Symbol |
| ™ | ™ | ™ | Trademark Symbol |
| ® | ® | ® | Registered Symbol |
| Character | Decimal Entity | Name Entity | Description |
|---|---|---|---|
| ¢ | ¢ | ¢ | Cent Currency(�) |
| £ | £ | £ | English Pound Currency |
| ¤ | ¤ | ¤ | General Currency |
| ¥ | ¥ | ¥ | Japanese Yen |
| € | € | € | European Euro |
| $ | $ | $ | Dollar Sign |
| ₣ | ₣ | ₣ | Franc Sign |
| Character | Decimal Entity | Name Entity | Description |
|---|---|---|---|
| ' | ‘ | ‘ | Left/Opening single quote |
| ' | ’ | ’ | Right/Closing single quote |
| " | “ | “ | Left/Opening double quote |
| " | ” | ” | Right/Closing double quote |
| Character | Decimal Entity | Name Entity | Description |
|---|---|---|---|
| ← | ← | Leftward Arrow | |
| ↑ | ↑ | Upward Arrow | |
| → | → | Rightward Arrow | |
| ↓ | ↓ | Downward Arrow |
| Character | Decimal Entity | Name Entity | Description |
|---|---|---|---|
| ♠ | ♠ | Spade Suit | |
| ♣ | ♣ | Club Suit | |
| ♥ | ♥ | Heart Suit | |
| ♦ | ♦ | Diamond Suit |
| Name | CSS |
|---|---|
| Universal | *{} |
| Type | div{} |
| Class | .className{} |
| Id | #idName{} |
| Name | CSS |
|---|---|
| Descendent | div a {} |
| Direct Child | div > a {} |
| General Sibling | div ~ a {} |
| Adjacent sibling | div + a {} |
| Or | div, a {} |
| And | div.c {} |
| Name | CSS |
|---|---|
| Has | [a] |
| Exact | [a="1"] |
| Begin With | [a^="1"] |
| Ends With | [a$="1"] |
| Substring | [a*="1"] |
| Name | CSS |
|---|---|
| Before | div::before {} |
| After | div::after {} |
| Name | CSS |
|---|---|
| Hover | button::hover {} |
| Focus | button::focus {} |
| Required | input::required {} |
| Checked | input::checked {} |
| Disabled | input::disabled {} |
| First Child | div::first-child {} |
| Last Child | div::last-child {} |
| Nth Child | div::nth-child(2n) {} |
| Nth Last Child | div::nth-last-child(3) {} |
| Only Child | div::only-child {} |
| First of Type | div::first-of-type {} |
| Last of Type | div::last-of-type {} |
| Nth of Type | div::nth-of-type(2n) {} |
| Nth Last of Type | div::nth-last-of-type(2) {} |
| Only of Type | div::only-of-type {} |
| Not | div::not(span) {} |
.html {
cursor: url("image.png"), auto; /*Set image as cursor*/
}/* To Toggle Dark/light mode */
.html {
filter: invert(1) hue-rotate(180deg);
}/* List bullet-point marker change */
li::marker {
content: "@";
font-size: 1.2rem;
}html {
/* To stop scrolling whole page instead of section */
overscroll-behavior: none;
}
.scroolable-section {
/* To make scroll bouncy */
overscroll-behavior: contain;
}html {
scroll-snap-type: y mandatory;
/* if you have a nav that is 30px in height */
scroll-padding-top: 30px;
}
section {
height: 100vh;
scroll-snap-align: start;
}.card {
.heading {
font-weight: bold;
h1 {
color: goldenrod;
}
}
}.article {
container-type: inline-size;
}
@container (min-width:700px) {
.card {
flex-direction: column;
font-size: max(1.2rem, 1em + 2cqi);
}
}body {
background-color: color-mix(in srgb, red 10%, blue);
}body {
background: black;
}
/* Before */
@media (min-width: 300px) and(max-width:600px) {
body {
background: green;
}
}
/* Now */
@media (300px <= width <= 600px) {
body {
background: green;
}
}
@media (width <= 600px) or (orientation: landscape) {
body {
background: white;
}
}.class {
all: initial; /* Reset all properties.*/
pointer-events: none; /* Define pointer hover or click events.*/
perspective: 1000px; /* Define how far the object is away from the user.*/
scroll-behavior: smooth; /*Smoothly animate scroll instead of straight jump*/
user-select: none; /*Whether text of an element can be selected*/
writing-mode: vertical-rl; /*Laid out of the text horizontal or vertical*/
}.img {
filter: drop-shadow(2px, 4px, 8px, #585858); /*Add shadow to transparent image*/
}p {
-webkit-line-clamp: 3; /*Limit the content of a block container to specified number of line*/
}/* Animate hiding and showing with auto height */
.body {
height: 0;
transition: height 0.5s;
}
.body.show {
height: calc-size(auto);
}/* Starting style animation */
.box {
background-color: red;
height: 100px;
width: 100px;
transition: scale 1s;
@starting-style {
scale: 0;
}
}<!-- Will clamp the text to max line <3> or give value -->
<div className="line-clamp-3">text</div>
<!-- Will clamp the text to max 1 line -->
<div className="truncate">text</div><!-- put space between children without flex box -->
<div className="divide-y-8">
<div className="size-8"></div>
<div className="size-8"></div>
<div className="size-8"></div>
</div><!-- gradient -->
<div
className="h-48 w-full bg-gradient-to-r from-red-500 to-green-500 via-white from-20%"
></div><!-- button focus rings -->
<button className="size-8 bg-red-500 ring-4 ring-green-500">Click</button>// To style the console
console.log(
"%c Demo status: %c loaded ",
"background: #ddd; color: #000; padding: 4px; border-radius: 2px",
"background: #6f6; color: #000; padding: 4px; border-radius: 2px; margin-left: 1ch",
);
// It will make the Demo status white and loaded green background- Generate a random number in a given range
- Find the difference between two arrays
- Convert truthy/falsy to boolean(true/false)
- Repeat a string
- Check how long an operation takes
- Two ways to remove an item in a specific in an array
- Did you know you can flat an array?
- Get unique values in an array
- Copy Text to Clipboard
- Nested Destructuring
- URLSearchParams
- Count elements in an array
- Aliases with JavaScript Destructuring
- The Object.is() method determines whether two values are the same value
- Freeze an object
- Printing Object keys and values
- Capture the right click event
- In HTML5, you can tell the browser when to run your JavaScript code
- Nullish coalescing operator
- Optional chaining
- globalThis
- The second argument of JSON.stringify lets you cherry-pick 🍒 keys to serialize.
- Fire an event listener only once.
- Vanilla JS toggle
- Check if a string is a valid JSON
- getBoundingClientRect
- Check if a node is in the viewport
- Notify when element size is changed
- Date Formatter
- Reversing string
- JavaScript Performance API
- Array
- Closure
- Intl Formatter Docs
- Console Logging Methods
- UUID and Date
- Discriminating Union
- Hide the Source Code of a Web Page
- Swapping Values
- Copy to Clipboard
- Destructuring Aliases
- Get Value as Data Type
- Remove Duplicates from Array
- Compare Two Arrays by Value
- Shuffling Array
- Comma Operator
// Returns a random number(float) between min (inclusive) and max (exclusive)
const getRandomNumber = (min, max) => Math.random() * (max - min) + min;
getRandomNumber(2, 10);
// Returns a random number(int) between min (inclusive) and max (inclusive)
const getRandomNumberInclusive = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
};
getRandomNumberInclusive(2, 10);const firstArr = [5, 2, 1];
const secondArr = [1, 2, 3, 4, 5];
const diff = [
...secondArr.filter((x) => !firstArr.includes(x)),
...firstArr.filter((x) => !secondArr.includes(x)),
];
console.log("diff", diff); //[3,4]
function arrayDiff(a, b) {
return [
...a.filter((x) => b.indexOf(x) === -1),
...b.filter((x) => a.indexOf(x) === -1),
];
}
console.log("arrayDiff", arrayDiff(firstArr, secondArr)); //[3,4]
const difference = (a, b) => {
const setA = new Set(a);
const setB = new Set(b);
return [...a.filter((x) => !setB.has(x)), ...b.filter((x) => !setA.has(x))];
};
difference(firstArr, secondArr); //[3,4]
console.log("difference", difference(firstArr, secondArr));const myVar = null;
const mySecondVar = 1;
console.log(Boolean(myVar)); // false
console.log(!!myVar); // false
console.log(Boolean(mySecondVar)); // true
console.log(!!mySecondVar); // truelet aliens = "";
for (let i = 0; i < 6; i++) {
aliens += "👽";
}
//👽👽👽👽👽👽
Array(6).join("👽");
//👽👽👽👽👽👽
"👽".repeat(6);
//👽👽👽👽👽👽//The performance.now() method returns a DOMHighResTimeStamp, measured in milliseconds.
//performance.now() is relative to page load and more precise in orders of magnitude.
//Use cases include benchmarking and other cases where a high-resolution time is required
//such as media (gaming, audio, video, //etc.)
var startTime = performance.now();
doSomething();
const endTime = performance.now();
console.log("this doSomething took " + (endTime - startTime) + " milliseconds.");//Mutating way ✔
const muatatedArray = ["a", "b", "c", "d", "e"];
muatatedArray.splice(2, 1);
console.log(muatatedArray); //['a','b','d','e']
//Non-mutating way ✔
const nonMuatatedArray = ["a", "b", "c", "d", "e"];
const newArray = nonMuatatedArray.filter((item, index) => !(index === 2));
console.log(newArray); //['a','b','d','e']const myArray = [2, 3, [4, 5], [7, 7, [8, 9, [1, 1]]]];
myArray.flat(); // [2, 3, 4, 5 ,7,7, [8, 9, [1, 1]]]
myArray.flat(1); // [2, 3, 4, 5 ,7,7, [8, 9, [1, 1]]]
myArray.flat(2); // [2, 3, 4, 5 ,7,7, 8, 9, [1, 1]]
//if you dont know the depth of the array you can use infinity
myArray.flat(infinity); // [2, 3, 4, 5 ,7,7, 8, 9, 1, 1];const numbers = [1, 1, 3, 2, 5, 3, 4, 7, 7, 7, 8];
//Ex1
const unieqNumbers = numbers.filter((v, i, a) => {
console.log(v);
console.log(i);
console.log(a);
a.indexOf(v) === i;
});
console.log(unieqNumbers); //[1,3,2,5,4,7,8]
//Ex2
const unieqNumbers2 = Array.from(new Set(numbers));
console.log(unieqNumbers2); //[1,3,2,5,4,7,8]
//Ex3
const unieqNumbers3 = [...new Set(numbers)];
console.log(unieqNumbers3); //[1,3,2,5,4,7,8]
//EX4 lodash
const unieqNumbers4 = _.uniq(numbers);
console.log(unieqNumbers4); //[1,3,2,5,4,7,8]function copyToClipboard() {
const copyText = document.getElementById("myInput");
copyText.select();
document.execCommand("copy");
}
//new API
function copyToClipboard() {
navigator.clipboard.writeText(document.querySelector("#myInput").value);
}const user = {
id: 459,
name: "JS snippets",
age: 29,
education: {
degree: "Masters",
},
};
const {
education: { degree },
} = user;
console.log(degree); //Masters//The URLSearchParams interface defines utility methods to work with the query string of a URL.
const urlParams = new URLSearchParams("?post=1234&action=edit");
console.log(urlParams.has("post")); // true
console.log(urlParams.get("action")); // "edit"
console.log(urlParams.getAll("action")); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append("active", "1")); // "?post=1234&action=edit&active=1"const myFruits = ["Apple", "Orange", "Mango", "Banana", "Apple", "Apple", "Mango"];
//first option
const countMyFruits = myFruits.reduce((countFruits, fruit) => {
countFruits[fruit] = (countFruits[fruit] || 0) + 1;
return countFruits;
}, {});
console.log(countMyFruits);
// { Apple:3, Banana:1, Mango:2, Orange:1 }
//seconf option ✔
const fruitsCounter = {};
for (const fruit of myFruits) {
fruitsCounter[fruit] = fruitsCounter[fruit] ? fruitsCounter[fruit] + 1 : 1;
}
console.log(fruitsCounter);
// { Apple:3, Banana:1, Mango:2, Orange:1 }//There are cases where you want the destructured variable to have a different name than the property name
const obj = {
name: "JSsnippets",
};
// Grabs obj.name as { pageName }
const { name: pageName } = obj;
//log our alias
console.log(pageName); // JSsnippetsObject.is("foo", "foo"); // true
Object.is(null, null); // true
Object.is(Nan, Nan); // true 😱
const foo = { a: 1 };
const bar = { a: 1 };
Object.is(foo, foo); // true
Object.is(foo, bar); // falseconst obj = {
name: "JSsnippets",
age: 29,
address: {
street: "JS",
},
};
const frozenObject = Object.freeze(obj);
frozenObject.name = "weLoveJS"; // Uncaught TypeError
//Although, we still can change a property’s value if it’s an object:
frozenObject.address.street = "React"; // no error, new value is set
delete frozenObject.name; // Cannot delete property 'name' of #<Object>
//We can check if an object is frozen by using
Object.isFrozen(obj); //trueconst obj = {
name: "JSsnippets",
age: 29,
};
//Object.entries() method is used to return an array consisting of enumerable property
//[key, value] pairs of the object which are passed as the parameter.
for (let [key, value] of Object.entries(obj)) {
console.log(`${key}: ${value}`);
}
//expected output:
// "name: Jssnippets"
// "age: 29"
// order is not guaranteedwindow.oncontextmenu = () => {
console.log("right click");
return false; // cancel default menu
};
//or
window.addEventListener(
"contextmenu",
() => {
console.log("right click");
return false; // cancel default menu
},
false,
);//Without async or defer, browser will run your script immediately, before rendering the elements that's below your script tag.
<script src="myscript.js"></script>
//With async (asynchronous), browser will continue to load the HTML page and render it while the browser load and execute the script at the same time.
//Async is more useful when you really don't care when the script loads and nothing else that is user dependent depends upon that script loading.(for scripts likes Google analytics)
<script async src="myscript.js"></script>
//With defer, browser will run your script when the page finished parsing. (not necessary finishing downloading all image files.
<script defer src="myscript.js"></script>// an equality check against nullary values (e.g. null or undefined). Whenever the expression to the left of the ?? operator evaluates to either //undefined or null, the value defined to the right will be returned.
const foo = undefined ?? "default string";
console.log(foo);
// expected output: "default string"
const age = 0 ?? 30;
console.log(age);
// expected output: "0"const car = {};
const carColor = car.name.color;
console.log(carColor);
// error- "Uncaught TypeError: Cannot read property 'carColor' of undefined
//In JavaScript, you can first check if an object exists, and then try to get one of its properties, like this:
const carColor = car && car.name && car.name.color;
console.log(carColor);
//undefined- no error
//Now this new optional chaining operator will let us be even more fancy:
const newCarColor = car?.name?.color;
console.log(newCarColor);
//undefined- no error
//You can use this syntax today using @babel/plugin-proposal-optional-chainingAccessing the global property in JavaScript has always posed some difficulty. This is because
different platforms have different ways to access it.
Client-side JavaScript uses window or self
Node.js uses global
Web workers use self
The globalThis property provides a standard way of accessing the global 'this' value across environments. you can access the global object in a consistent manner without having to know which environment the code is being run in.
console.log(globalThis) //get the global this depends on your environmentconst user = {
id: 459,
name: "JS snippets",
age: 29,
education: {
degree: "Masters",
},
};
JSON.stringify(user, [name, age], 2);
/*
returns
{
"name": "JS snippets",
"age": 29
}
*/const el = document.getElementById("btn");
function myClickHandler() {
console.log("this click will only fire once");
}
el.addEventListener("click", myClickHandler, {
once: true,
});const span = document.querySelector("span");
let classes = span.classList;
span.addEventListener("click", function () {
let result = classes.toggle("active");
if (result) {
console.log("active class was added");
} else {
console.log("active class was removed");
}
});function isJson(str) {
try {
JSON.parse(str);
} catch (e) {
//the json is not ok
return false;
}
//the json is ok
return true;
}//getBoundingClientRect provides you with important pieces of data about an
//HTML element’s size and positioning.
const bodyBounderies = document.body.getBoundingClientRect();
// => {
// top: Number,
// left: Number,
// right: Number,
// bottom: Number,
// x: Number,
// y: Number,
// width: Number,
// height: Number,
// }const image = document.querySelector(".animate-me");
observer = new IntersectionObserver((entries) => {
const [myImg] = entries;
if (myImg.intersectionRatio > 0) {
myImg.target.classList.add("fancy");
} else {
myImg.target.classList.remove("fancy");
}
});
observer.observe(image);const foo = document.getElementById("foo");
const observer = new ResizeObserver((entries) => {
for (let entry of entries) {
const cr = entry.contentRect;
console.log = `Size: ${cr.width}px X ${cr.height}px`;
}
});
observer.observe(foo);// Date Formatter
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
const dateArr = userDate.split("/");
const day = dateArr[1].length === 2 ? dateArr[1] : "0" + dateArr[1];
const month = dateArr[0].length === 2 ? dateArr[0] : "0" + dateArr[0];
const year = dateArr[2];
return year + month + day;
}
console.log(formatDate("1/31/2014"));
// or
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
console.log("Parse", Date.parse(userDate)); //Parse number
console.log("new", typeof new Date(userDate)); //new object
var x = new Date(userDate);
var y = x.getFullYear().toString();
var m = (x.getMonth() + 1).toString();
var d = x.getDate().toString();
d.length == 1 && (d = "0" + d);
m.length == 1 && (m = "0" + m);
var yyyymmdd = y + m + d;
return yyyymmdd;
}
console.log(formatDate("12/31/2014"));// Simply reversing the string wont give the solution.
// Get each word.
// Reverse It
// Again rejoin
var str = "This is fun, hopefully.";
// console.log(str.split("").reverse().join("").split(" ").reverse().join(" "));
console.log(
str
.split(" ")
.map((el) => el.split("").reverse().join(""))
.join(" "),
);
// with regex
String.prototype.replaceAll = function (find, replace) {
var target = this;
return target.replace(new RegExp(find, "g"), replace);
};
str = "ghktestlllltest-sdds";
str = str.replaceAll("test", "");
console.log(str);
// str = "ghktestlllltest-sdds"
// str = str.replace(/test/g, '');
// alert(str)The Performance API is designed to help developers locate and solve performance problems and optimize page loading speed and user experience. It can be used in the following scenarios:
- Web Page Performance Monitoring
- Performance Optimization
- User Experience Analysis
- Performance Benchmarking
-
Get Page Load Time:
const loadTime = window.performance.timing.loadEventEnd - window.performance.timing.navigationStart; console.log(`Page load time: ${loadTime}ms`);
-
Measuring Resource Load Time:
const resourceTiming = window.performance.getEntriesByType("resource"); resourceTiming.forEach((resource) => { console.log(`${resource.name} load time: ${resource.duration}ms`); });
-
Monitor User Interaction Latency:
const interactionStart = Date.now(); document.addEventListener("click", () => { const interactionEnd = Date.now(); const interactionDelay = interactionEnd - interactionStart; console.log(`User click delay:${interactionDelay}ms`); });
-
Page Load Time Monitoring and Optimization:
// Monitoring page load time const loadTime = window.performance.timing.loadEventEnd - window.performance.timing.navigationStart; console.log(`Page load time: ${loadTime}ms`); // Monitor resource load time const resourceTiming = window.performance.getEntriesByType("resource"); resourceTiming.forEach((resource) => { console.log(`${resource.name} load time: ${resource.duration}ms`); });
-
Resource loading performance analysis:
// Monitor the load time of a critical resource const keyResources = [ "https://example.com/css/style.css", "https://example.com/js/main.js", ]; keyResources.forEach((resource) => { const resourceEntry = window.performance.getEntriesByName(resource)[0]; console.log(`${resource} load time: ${resourceEntry.duration}ms`); });
-
User interaction latency monitoring:
// Monitor user click latency const interactionStart = Date.now(); document.addEventListener("click", () => { const interactionEnd = Date.now(); const interactionDelay = interactionEnd - interactionStart; console.log(`User click delay: ${interactionDelay}ms`); });
-
Page Animation Performance Monitoring:
// Monitoring animation performance function measureAnimationPerformance() { const animationStart = performance.now(); // Execute animation operations requestAnimationFrame(() => { const animationEnd = performance.now(); const animationDuration = animationEnd - animationStart; console.log(`Animation execution time: ${animationDuration}ms`); }); } measureAnimationPerformance();
-
:
const loadTime = window.performance.timing.loadEventEnd - window.performance.timing.navigationStart; console.log(`Page load time: ${loadTime}ms`);
Common Functional Array Methods:
- map(callback):
- Creates a new array by applying a function to each element of the original array.
- Example:
const doubledNumbers = numbers.map(number => number * 2);
- filter(callback):
- Creates a new array containing elements that pass a certain test.
- Example:
const evenNumbers = numbers.filter(number => number % 2 === 0);
- reduce(callback, initialValue):
- Reduces an array to a single value by applying a function to each element and accumulating a result.
- Example:
const sum = numbers.reduce((accumulator, number) => accumulator + number, 0);
- forEach(callback):
- Executes a function for each element of an array, but doesn't create a new array.
- Example:
numbers.forEach(number => console.log(number));
- find(callback):
- Returns the first element in an array that satisfies a test.
- Example:
const firstEvenNumber = numbers.find(number => number % 2 === 0);
- some(callback):
- Tests whether at least one element in an array passes a test.
- Example:
const hasEvenNumber = numbers.some(number => number % 2 === 0);
- every(callback):
- Tests whether all elements in an array pass a test.
- Example:
const allEvenNumbers = numbers.every(number => number % 2 === 0);
Key Advantages:
- Concise and expressive: Functional array methods often lead to more concise and readable code compared to traditional loops.
- Chainable: Array methods can be chained together to create complex operations in a fluent style.
- Pure and predictable: Functional approaches often emphasize pure functions and immutability, promoting easier testing and reasoning about code.
- Performance optimizations: Some functional array methods can be optimized by JavaScript engines for better performance.
In essence, functional array functions provide a powerful and elegant way to manipulate and process arrays in JavaScript, leading to cleaner, more maintainable, and potentially more performant code.
// Last element
arr.at(-1);
// 2nd last element
arr.at(-2);A function that has access to variables in its outer (enclosing) function's scope, even after the outer function has returned. Closures can have multiple nested functions, creating closures within closures. This allows for even more encapsulation and control over data access.
function createCounter() {
let count = 0; // Outer scope variable
return function () {
// Inner function (closure)
count++;
return count;
};
}
const counter1 = createCounter();
const counter2 = createCounter();
console.log(counter1()); // Output: 1
console.log(counter2()); // Output: 1 (separate count for each closure)
console.log(counter1()); // Output: 2
console.log(counter2()); // Output: 2-
Date Time
const formatter = new Intl.DateTimeFormat("en-US"); console.log(formatter.format(new Date()));
-
Relative Time Format
const formatter = new Intl.RelativeTimeFormat(undefined, { numeric: "auto" }); console.log(formatter.format(1, "day");
-
Number Format
const currencyFormatter = new Intl.NumberFormat(undefined, { currency: "USD", style: "currency", }); const unitFormatter = new Intl.NumberFormat(undefined, { unit: "liter", style: "unit", unitDisplay: "long", }); const numberFormatter = new Intl.NumberFormat(undefined, { notation: "compact" }); const fractionFormatter = new Intl.NumberFormat(undefined, { maximumFractionDigits: 2, minimumFractionDigits: 1, }); console.log(currencyFormatter.format(15412154));
-
To print array as a table
const users = [ { name: "a", age: 25 }, { name: "b", age: 26 }, ]; console.table(users);
-
To print How much Time it take
console.time("Loop"); for (let i = 0; i < 100000; i++) { // } console.timeEnd("Loop");
-
JS Built in uuid generator API
console.log(crypto.randomUUID());
-
Get time difference between dates in hour
const today = new Date(); const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); const timeDiff = today.getTime() - yesterday.getTime(); const diffInMs = Math.abs(timeDiff); const diffInMinutes = Math.floor(diffInMs / (1000 * 60 * 60));
// Discriminating Union
type LoadingState = {
state: "Loading";
};
type SuccessState = {
state: "Success";
data: { id: string; name: string };
};
type ErrorState = {
state: "Error";
error: { message: string };
};
type CurrentState = LoadingState | SuccessState | ErrorState;
function print(loc: CurrentState) {
switch (location.state) {
case "Loading":
console.log(location.state);
break;
case "Success":
console.log(location.data.name);
break;
case "Error":
console.log(location.error.message);
break;
default:
break;
}
}<script>
document.addEventListener("contextmenu", e => e.preventDefault(), false);
document.addEventListener("keydown", e => {
// DISABLE CONTROL AND ALL FUNCTION KEYS
// if (e.ctrlKey || (e.keyCode>=112 && e.keyCode<=123)) {
// DISABLE CONTROL AND F12
if (e.ctrlKey || e.keyCode==123) {
e.stopPropagation();
e.preventDefault();
}
});
</script>let array = [1, 2, 3, 4, 5];
[array[0], array[4]] = [array[4], array[0]];function copyToClipBoard(str) {
const element = document.createElement("textarea");
element.value = str;
document.body.appendChild(element);
element.select();
document.execCommand("copy");
document.body.removeChild(element);
}
function handleClick() {
let text = document.querySelector("#text");
copyToClipBoard(text.innerText);
}const language = {
name: "JavaScript",
founded: 1995,
founder: "Brendan Eich",
};
const { name: languageName, founder: creatorName } = language;
console.log(languageName, creatorName); // Output: JavaScript Brendan Eichconst element = document.querySelector("#number").valueAsNumber;
console.log(typeof element); // Output: numberconst array = [1, 2, 2, 2, 3, 5, 6, 5];
console.log([...new Set(array)]); // Output: [1, 2, 3, 5, 6]const hasSameElements = (a, b) => {
return a.length === b.length && a.every((v, i) => v === b[i]);
};
console.log(hasSameElements([1, 2], [1, 2])); // Output: true
console.log(hasSameElements([1, 2], [2, 1])); // Output: falseconst numbers = [1, 2, 3, 4, 5, 6];
console.log(numbers.sort(() => Math.random() - 0.5)); // Output: [3, 5, 1, 6, 4, 2] (example, output may vary)let x = 1;
x = (x++, x);
console.log(x); // Output: 2
let y = (2, 3);
console.log(y); // Output: 3
let a = [[1, 2, 3, 4], [3, 4, 5], [5, 6], [7]];
for (let i = 0, j = 3; i <= 3; i++, j--) {
console.log("a[" + i + "][" + j + "] = " + a[i][j]);
// Output:
// a[0][3] = 4
// a[1][2] = 5
// a[2][1] = 6
// a[3][0] = 7
}









