Javascript: Difference between revisions
(18 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
=Javascript tips= | =Javascript tips= | ||
== | =Book Online= | ||
== | Found this which might be useful. [[https://exploringjs.com/impatient-js/toc.html]] | ||
=Module Formats= | |||
Before I forget here are the two formats for JavaScript modules CommonJS and ES6 (EMCAScript modules) | |||
[[File:CommonJs And ES6.png]] | |||
=Variables= | |||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
let a = 50; // Can be changed but only valid in scope | let a = 50; // Can be changed but only valid in scope | ||
Line 13: | Line 12: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=Objects= | |||
You can create an object using this | You can create an object using this | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
const sessionId = 1; | const sessionId = 1; | ||
const burke1 = sessionId | const burke1 = sessionId | ||
Line 40: | Line 37: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
= Class Field declarations = | |||
You can declare classes like | You can declare classes like | ||
Line 72: | Line 69: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=Property Syntax= | |||
You can reference a property of an object via a variable. In the example below we have assigned c to myPropertyName. | You can reference a property of an object via a variable. In the example below we have assigned c to myPropertyName. | ||
Line 87: | Line 84: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=Comparisons= | |||
The following would be true with loose comparisons | The following would be true with loose comparisons | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
Line 110: | Line 107: | ||
This is because the type is compared in strict comparisons | This is because the type is compared in strict comparisons | ||
=Array= | |||
==Introduction== | |||
This is about immutable array because it seems this is the way with javascript. | This is about immutable array because it seems this is the way with javascript. | ||
==Add Element to array in Object== | |||
Here is an example of adding an element | Here is an example of adding an element | ||
<syntaxhighlight lang="js"> | <syntaxhighlight lang="js"> | ||
Line 135: | Line 132: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
==Remove Element using an index in an Object Array== | |||
Here is an example of removing an element from a given index | Here is an example of removing an element from a given index | ||
<syntaxhighlight lang="js"> | <syntaxhighlight lang="js"> | ||
Line 162: | Line 159: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
==Replace an Element in an Object array== | |||
Replace a use in an array of users. | Replace a use in an array of users. | ||
<syntaxhighlight lang="js"> | <syntaxhighlight lang="js"> | ||
Line 188: | Line 185: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
==Add== | |||
<syntaxhighlight lang="js"> | <syntaxhighlight lang="js"> | ||
const newArray = myArray.concat(newElement) | const newArray = myArray.concat(newElement) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
==Filter== | |||
<syntaxhighlight lang="js"> | <syntaxhighlight lang="js"> | ||
const newArray = myArray.filter( | const newArray = myArray.filter( | ||
Line 200: | Line 195: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
==Spread== | |||
== Spread == | |||
===Spreading array=== | ===Spreading array=== | ||
Line 224: | Line 217: | ||
<Card { name="Freda" age=30} /> | <Card { name="Freda" age=30} /> | ||
</syntaxhighlight> | </syntaxhighlight> | ||
===Appending to an array=== | ===Appending to an array=== | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
testData: [...prevState.testData, newTestData] | testData: [...prevState.testData, newTestData] | ||
</syntaxhighlight> | </syntaxhighlight> | ||
===Map=== | |||
== Map == | |||
Given we can spread elements we can also spread array e.g | Given we can spread elements we can also spread array e.g | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
Line 237: | Line 227: | ||
{testData.map( element=> <Card {...element} />) } | {testData.map( element=> <Card {...element} />) } | ||
</div> | </div> | ||
</syntaxhighlight> | |||
==Rest== | |||
The rest operator will append remain attributes | |||
<syntaxhighlight lang="javascript"> | |||
const Susan = { | |||
firstName: "Susan", | |||
lastName: "Steward", | |||
legs: { | |||
leg1: "left", | |||
leg2: "right" | |||
}, | |||
age: 14, | |||
hobbies: { | |||
hobby1: "singing", | |||
hobby2: "dancing" | |||
}, | |||
arms: { | |||
arm1: "left", | |||
arm2: "right" | |||
} | |||
}; | |||
const {age, ...rest} = Susan; | |||
console.log("Age:", age); | |||
console.log("Rest:", rest); | |||
</syntaxhighlight> | |||
This outputs the following<br> | |||
[[File:Js REST.png| 800px]] | |||
==Reduce== | |||
It can replace the filter() and find() methods and is also quite handy when doing map() and filter() methods on large amounts of data. Given | |||
<syntaxhighlight lang="javascript"> | |||
let staffs = [ | |||
{ name: "Susan", age: 14, salary: 100 }, | |||
{ name: "Daniel", age: 16, salary: 120 }, | |||
{ name: "Bruno", age: 56, salary: 400 }, | |||
{ name: "Jacob", age: 15, salary: 110 }, | |||
{ name: "Sam", age: 64, salary: 500 }, | |||
{ name: "Dave", age: 56, salary: 380 }, | |||
{ name: "Neils", age: 65, salary: 540 } | |||
]; | |||
</syntaxhighlight> | |||
We can calculate the total with | |||
<syntaxhighlight lang="javascript"> | |||
const totalSalary = staffs.reduce((total, staff) => { | |||
total += staff.salary; | |||
return total; | |||
},0) | |||
console.log(totalSalary); // 2150 | |||
</syntaxhighlight> | |||
Better still add a new field | |||
<syntaxhighlight lang="javascript"> | |||
const salaryInfo = staffs.reduce( | |||
(total, staff) => { | |||
let staffTithe = staff.salary * 0.1; | |||
total.totalTithe += staffTithe; | |||
total['totalSalary'] += staff.salary; | |||
return total; | |||
}, | |||
{ totalSalary: 0, totalTithe: 0 } | |||
); | |||
console.log(salaryInfo); // { totalSalary: 2150 , totalTithe: 215 } | |||
</syntaxhighlight> | |||
==Optional Chaining== | |||
Most languages have this feature such is the dealing with nulls and undefined. Previously we had | |||
<syntaxhighlight lang="javascript"> | |||
let users = [ | |||
{ | |||
name: "Sam", | |||
age: 64, | |||
hobby: "cooking", | |||
hobbies: { | |||
hobb1: "cooking", | |||
hobby2: "sleeping" | |||
} | |||
}, | |||
{ name: "Bruno", age: 56 }, | |||
{ name: "Dave", age: 56, hobby: "Football" }, | |||
{ | |||
name: "Jacob", | |||
age: 65, | |||
hobbies: { | |||
hobb1: "driving", | |||
hobby2: "sleeping" | |||
} | |||
} | |||
]; | |||
</syntaxhighlight> | |||
And when used we get | |||
<syntaxhighlight lang="js"> | |||
users.forEach((user) => { | |||
console.log(user.hobbies.hobby2); | |||
}); | |||
"sleeping" | |||
error: Uncaught TypeError: user.hobbies is undefined | |||
</syntaxhighlight> | |||
With optional chaining we can do | |||
<syntaxhighlight lang="js"> | |||
users.forEach((user) => { | |||
console.log(user ?.hobbies ?.hobby2); | |||
}); | |||
</syntaxhighlight> | </syntaxhighlight> | ||
=functions= | |||
==Simple Functions== | |||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
Line 247: | Line 342: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
==Arrow Functions== | |||
Not great for me so need to write it down. <br><br> | Not great for me so need to write it down. <br><br> | ||
Normal controller no function | Normal controller no function | ||
Line 278: | Line 373: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=Importing= | |||
Using export instead of export default means you have to use destruction to import e.g. | Using export instead of export default means you have to use destruction to import e.g. | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
Line 292: | Line 387: | ||
}); | }); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=destructure= | |||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
Line 335: | Line 428: | ||
// First be 10, restOfitems is and array of 20,30,40 | // First be 10, restOfitems is and array of 20,30,40 | ||
=Template Strings= | |||
This is like c# interpolation using back ticks. | This is like c# interpolation using back ticks. | ||
Line 343: | Line 436: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=Promises and Async= | |||
Old approach to async | Old approach to async | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
const fetchData = async () => { | const fetchData = async () => { | ||
Line 374: | Line 465: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=Generators= | |||
The function * denotes a generator function. The function is executed until yield. Subsequent calls remember the value of yield and continue to the next yield | The function * denotes a generator function. The function is executed until yield. Subsequent calls remember the value of yield and continue to the next yield | ||
Line 406: | Line 497: | ||
{ value: 10000, done: false } | { value: 10000, done: false } | ||
Fred was ere 3 | Fred was ere 3 | ||
=IFFE (Immediately Invoked Function Expression)= | =IFFE (Immediately Invoked Function Expression)= | ||
This I found very hard to understand so wanted to write it up. | This I found very hard to understand so wanted to write it up. | ||
==Normal Function== | ==Normal Function== | ||
This is how a standard function works in Java Script | This is how a standard function works in Java Script | ||
Line 427: | Line 510: | ||
*Lines 1–3 define a function named sayHi. | *Lines 1–3 define a function named sayHi. | ||
*On line 5 we call it with the usual “()” syntax to invoke the function. | *On line 5 we call it with the usual “()” syntax to invoke the function. | ||
=Function Expression= | |||
We can assign a function to a variable in java script. | |||
<syntaxhighlight lang="js" line > | |||
var msg = "Hello, World!"; | |||
var sayHi = function() { | |||
alert(msg); | |||
}; | |||
sayHi(); // shows "Hello, World!" as alert in browser. | |||
</syntaxhighlight> | |||
*Line 1 declares msg variable and assigns a string value to it. | |||
*Lines 2–4 declare sayHi variable and assign a value to it that’s of function type. | |||
*Line 6 calls this sayHi function. | |||
=Two Examples= | |||
Here are too examples of IFFE's | |||
<syntaxhighlight lang="js" line > | |||
// Variation 1 | |||
(function() { | |||
alert("I am an IIFE!"); | |||
}()); | |||
// Variation 2 | |||
(function() { | |||
alert("I am an IIFE, too!"); | |||
})(); | |||
</syntaxhighlight> | |||
*In Variation 1, on line 4, parentheses () for invoking the function expression is contained inside the outer parentheses. The outer parentheses are needed to make a function expression out of that function. | |||
*In Variation 2, on line 9, parentheses () for invoking the function expression is outside the wrapping parentheses for the function expression. | |||
==Private Variables== | |||
Probably needs saying for people who use older javascript but the parameters are private inside an IFFE | |||
<syntaxhighlight lang="js" line > | |||
(function IIFE_initGame() { | |||
// Private variables that no one has access to outside this IIFE | |||
var lives; | |||
var weapons; | |||
init(); | |||
// Private function that no one has access to outside this IIFE | |||
function init() { | |||
lives = 5; | |||
weapons = 10; | |||
} | |||
}()); | |||
</syntaxhighlight> | |||
=IFEs with a return value= | |||
We can return values like any other function with an IFFE | |||
<syntaxhighlight lang="js" line > | |||
var result = (function() { | |||
return "From IIFE"; | |||
}()); | |||
alert(result); // alerts "From IIFE" | |||
</syntaxhighlight> | |||
=Finally we can Pass Parameters= | |||
Not only IIFEs can return values, but IIFEs can also take arguments while they are invoked. | |||
<syntaxhighlight lang="js" line > | |||
(function IIFE(msg, times) { | |||
for (var i = 1; i <= times; i++) { | |||
console.log(msg); | |||
} | |||
}("Hello!", 5)); | |||
</syntaxhighlight> | |||
=react functions and state= | =react functions and state= | ||
Line 511: | Line 657: | ||
document.getElementById('mountNode'), | document.getElementById('mountNode'), | ||
); | ); | ||
</syntaxhighlight> | |||
=Console= | |||
This is a couple of bit did not know | |||
==Group== | |||
Outputs messages together | |||
<syntaxhighlight lang="javascript"> | |||
console.group('Group Name') | |||
console.log('Hello 1') | |||
console.log('Hello 1') | |||
console.log('Hello 2') | |||
console.groupEnd('Group Name') | |||
</syntaxhighlight> | |||
==Time== | |||
Outputs the time taken | |||
<syntaxhighlight lang="javascript"> | |||
for(var i = 0; i < 2000;i++) { | |||
console.log('Fun stuff') | |||
} | |||
</syntaxhighlight> | |||
=CreateObjectURL and RevokeObjectURL= | |||
This allows you to create a local URL to be used for reference. An example would be a binary image stored in a blob. | |||
<syntaxhighlight lang="html"> | |||
!DOCTYPE html> | |||
<html lang="en"> | |||
<head> | |||
<meta charset="UTF-8"> | |||
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |||
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |||
<title>Document</title> | |||
</head> | |||
<body> | |||
<button id = 'btnLoad'>Load</button> | |||
<button id = 'btnUnload'>Unload</button> | |||
<img src = "x" id = 'img1'> | |||
<img src = "x" id = 'img2'> | |||
<img src = "x" id = 'img3'> | |||
<img src = "x" id = 'img4'> | |||
<script> | |||
const btnLoad = document.getElementById("btnLoad") | |||
const btnUnload = document.getElementById("btnUnload") | |||
const img1 = document.getElementById("img1") | |||
const img2 = document.getElementById("img2") | |||
const img3 = document.getElementById("img3") | |||
const img4 = document.getElementById("img4") | |||
const imgs = [] | |||
imgs.push(img1) | |||
imgs.push(img2) | |||
imgs.push(img3) | |||
imgs.push(img4) | |||
let objUrl = null; | |||
imgs.forEach(i => i.addEventListener("click", e => e.target.src = objUrl)) | |||
btnUnload.addEventListener("click", e => URL.revokeObjectURL(objUrl)) | |||
btnLoad.addEventListener("click", async e => { | |||
const result = await fetch("http://localhost:8080/test.png") | |||
const blob = await result.blob() | |||
objUrl = URL.createObjectURL(blob) | |||
alert(`object url created locally ${objUrl}`) | |||
}) | |||
</script> | |||
</body> | |||
</html> | |||
</syntaxhighlight> | |||
=One Liners= | |||
==Get count from Object== | |||
<syntaxhighlight lang="javascript"> | |||
cart.map(item => item.quantity).reduce(previous, next) => previous + next,0) : 0} | |||
</syntaxhighlight> | </syntaxhighlight> |
Latest revision as of 01:39, 10 July 2022
Javascript tips
Book Online
Found this which might be useful. [[1]]
Module Formats
Before I forget here are the two formats for JavaScript modules CommonJS and ES6 (EMCAScript modules)
Variables
let a = 50; // Can be changed but only valid in scope
var a = 50; // Can be changed but global
const a = 50 // Cannot be changed
Objects
You can create an object using this
const sessionId = 1;
const burke1 = sessionId
const burke2 = sessionId +1
const burke3 = sessionId +2
const burke4 = sessionId +3
const burke5 = sessionId +4
const mee = {
burke1,
burke2,
burke3,
burke4,
burke5,
}
Will create a object with keys the same name as the values e.g.
mee.burke1 // = 1
mee.burke2 // = 2
Class Field declarations
You can declare classes like
testData = {
{ name = "Fred", age = 20 }
{ name = "Freda", age = 30 }
}
This will simplify the class state e.g. was
class App Extends React.Component {
constructor(props) {
super(props)
this.state = {
profile: testData,
}
}
}
To
class App Extends React.Component {
state = {
profile: testData,
}
}
Property Syntax
You can reference a property of an object via a variable. In the example below we have assigned c to myPropertyName.
const myPropertyName = 'c'
const myObject = {
a: 5,
b: 10,
[myPropertyName]: 15
}
console.log(myObject.c) // prints 15
Comparisons
The following would be true with loose comparisons
if("20" == 20) {
console.log("true");
}
else {
console.log("false");
}
But false with strict comparisons
if("20" === 20) {
console.log("true");
}
else {
console.log("false");
}
This is because the type is compared in strict comparisons
Array
Introduction
This is about immutable array because it seems this is the way with javascript.
Add Element to array in Object
Here is an example of adding an element
// Given
user = {
name: "fred",
surnname: "blogss", {
cookies: [
"token1",
"token2",
"token3"
]
}
}
// Add the cookie to the user
const newCookies = [...user.cookies, refreshToken];
// Replace the cookies with the newCookies
const newUser = { ...user, cookies: newCookies };
Remove Element using an index in an Object Array
Here is an example of removing an element from a given index
// Given
user = {
name: "fred",
surnname: "blogss", {
cookies: [
"token1",
"token2",
"token3"
]
}
}
// We can remove the one we want with
const tokenIndex = user.cookies.findIndex(
(token) => token === refreshToken
);
const newCookies = [
...user.cookies.slice(0, tokenIndex),
...user.cookies.slice(tokenIndex + 1),
];
Replace an Element in an Object array
Replace a use in an array of users.
// Given
newUser = {
id: 1,
name: "fred",
surnname: "blogss", {
cookies: [
"token1",
"token2",
"token3"
]
}
}
this.userCollection = this.userCollection.map((user) => {
let temp = user;
if (temp.id === newUser.id) {
temp = newUser;
}
return temp;
});
Add
const newArray = myArray.concat(newElement)
Filter
const newArray = myArray.filter(
n=> !myOtherArray.includes(n)
}
Spread
Spreading array
const testData = {
{ name = "Fred", age = 20 }
{ name = "Freda", age = 30 }
}
Spread spreads them e.g.
<Card {...testData[0]} />
<Card {...testData[1]} />
Is the same as
<Card { name="Fred" age=20} />
<Card { name="Freda" age=30} />
Appending to an array
testData: [...prevState.testData, newTestData]
Map
Given we can spread elements we can also spread array e.g
<div>
{testData.map( element=> <Card {...element} />) }
</div>
Rest
The rest operator will append remain attributes
const Susan = {
firstName: "Susan",
lastName: "Steward",
legs: {
leg1: "left",
leg2: "right"
},
age: 14,
hobbies: {
hobby1: "singing",
hobby2: "dancing"
},
arms: {
arm1: "left",
arm2: "right"
}
};
const {age, ...rest} = Susan;
console.log("Age:", age);
console.log("Rest:", rest);
Reduce
It can replace the filter() and find() methods and is also quite handy when doing map() and filter() methods on large amounts of data. Given
let staffs = [
{ name: "Susan", age: 14, salary: 100 },
{ name: "Daniel", age: 16, salary: 120 },
{ name: "Bruno", age: 56, salary: 400 },
{ name: "Jacob", age: 15, salary: 110 },
{ name: "Sam", age: 64, salary: 500 },
{ name: "Dave", age: 56, salary: 380 },
{ name: "Neils", age: 65, salary: 540 }
];
We can calculate the total with
const totalSalary = staffs.reduce((total, staff) => {
total += staff.salary;
return total;
},0)
console.log(totalSalary); // 2150
Better still add a new field
const salaryInfo = staffs.reduce(
(total, staff) => {
let staffTithe = staff.salary * 0.1;
total.totalTithe += staffTithe;
total['totalSalary'] += staff.salary;
return total;
},
{ totalSalary: 0, totalTithe: 0 }
);
console.log(salaryInfo); // { totalSalary: 2150 , totalTithe: 215 }
Optional Chaining
Most languages have this feature such is the dealing with nulls and undefined. Previously we had
let users = [
{
name: "Sam",
age: 64,
hobby: "cooking",
hobbies: {
hobb1: "cooking",
hobby2: "sleeping"
}
},
{ name: "Bruno", age: 56 },
{ name: "Dave", age: 56, hobby: "Football" },
{
name: "Jacob",
age: 65,
hobbies: {
hobb1: "driving",
hobby2: "sleeping"
}
}
];
And when used we get
users.forEach((user) => {
console.log(user.hobbies.hobby2);
});
"sleeping"
error: Uncaught TypeError: user.hobbies is undefined
With optional chaining we can do
users.forEach((user) => {
console.log(user ?.hobbies ?.hobby2);
});
functions
Simple Functions
const X = () => {
console.log("Fred");
}
Arrow Functions
Not great for me so need to write it down.
Normal controller no function
router.get('/customers', (req, res) => {
console.log('this is me');
// console.log(req.query);
res.sendStatus(404);
});
Let put if in a function. We need to make the function signature match the original
function iain(req, res) {
console.log('this is me');
console.log(req.query);
res.sendStatus(404);
}
router.get('/customers', iain)
async now is
async function iain(req, res) {
console.log('this is me');
console.log(req.query);
res.sendStatus(404);
}
router.get('/customers', iain)
Importing
Using export instead of export default means you have to use destruction to import e.g.
import {ActionTypes as types} from '../constants';
For this example constants.js file
import keyMirror from 'keyMirror';
export var ActionType = keyMirror ({
THIS_IS_A_CONST = null
});
destructure
// const PI = Math.PI;
// const E = Math.E;
// const SQRT2 = Math.SQRT2;
// Does the same
const {PI, E, SQRT2} = Math;
You can pass a cirucla to and the radius is automatically extracted. Precision can have a default but can also be passed.
const circle = {
label: 'circleX',
radius: 2,
};
const circleArea = {{radius}, {precision = 2} = {}) =>
(PI * radius * radius).toFixed(precision);
console.log(
circleArea(circle, {precision:5})
);
And arrays
const [first, ...restOfItems] = [10,20,30,40]
// First be 10, restOfitems is and array of 20,30,40
Template Strings
This is like c# interpolation using back ticks.
const html = `<div>${Math.random()}</div>`;
Promises and Async
Old approach to async
const fetchData = async () => {
const resp = await fetch('https://api.github.com');
const data = await resp.json();
console.log(data);
};
fetchData();
New approach
const fetchData = async() => {
const resp = await fetch('http::/api.github.com');
const data = await resp.json();
console.log(data);
}
fetchData();
Generators
The function * denotes a generator function. The function is executed until yield. Subsequent calls remember the value of yield and continue to the next yield
function * myGen(i)
{
while(true)
{
yield i = i * 10;
}
}
fred = myGen(10);
console.log(fred.next());
console.log("Fred was ere 1");
console.log(fred.next());
console.log("Fred was ere 2");
console.log(fred.next());
console.log("Fred was ere 3");
Output would be{ value: 100, done: false }
Fred was ere 1 { value: 1000, done: false } Fred was ere 2 { value: 10000, done: false } Fred was ere 3
IFFE (Immediately Invoked Function Expression)
This I found very hard to understand so wanted to write it up.
Normal Function
This is how a standard function works in Java Script
function sayHi() {
alert("Hello, World!");
}
sayHi(); // shows "Hello, World!" as alert in browser.
- Lines 1–3 define a function named sayHi.
- On line 5 we call it with the usual “()” syntax to invoke the function.
Function Expression
We can assign a function to a variable in java script.
var msg = "Hello, World!";
var sayHi = function() {
alert(msg);
};
sayHi(); // shows "Hello, World!" as alert in browser.
- Line 1 declares msg variable and assigns a string value to it.
- Lines 2–4 declare sayHi variable and assign a value to it that’s of function type.
- Line 6 calls this sayHi function.
Two Examples
Here are too examples of IFFE's
// Variation 1
(function() {
alert("I am an IIFE!");
}());
// Variation 2
(function() {
alert("I am an IIFE, too!");
})();
- In Variation 1, on line 4, parentheses () for invoking the function expression is contained inside the outer parentheses. The outer parentheses are needed to make a function expression out of that function.
- In Variation 2, on line 9, parentheses () for invoking the function expression is outside the wrapping parentheses for the function expression.
Private Variables
Probably needs saying for people who use older javascript but the parameters are private inside an IFFE
(function IIFE_initGame() {
// Private variables that no one has access to outside this IIFE
var lives;
var weapons;
init();
// Private function that no one has access to outside this IIFE
function init() {
lives = 5;
weapons = 10;
}
}());
IFEs with a return value
We can return values like any other function with an IFFE
var result = (function() {
return "From IIFE";
}());
alert(result); // alerts "From IIFE"
Finally we can Pass Parameters
Not only IIFEs can return values, but IIFEs can also take arguments while they are invoked.
(function IIFE(msg, times) {
for (var i = 1; i <= times; i++) {
console.log(msg);
}
}("Hello!", 5));
react functions and state
Normal function
function logRandom() {
console.log(Math.random());
}
function Button() {
const [count, setCounter] = useState(0);
return <button onClick={logRandom}>{counter}</button>;
}
inline function
function Button() {
const [count, setCounter] = useState(0);
return <button onClick={
function logRandom() {
console.log(Math.random());
}
}>{counter}</button>;
}
inline arrow function definition
function Button() {
// React useState hook
const [count, setCounter] = useState(0);
return <button
onClick={
() = > console.log(Math.random())
}
>{counter}</button>;
}
Passing Props
function Button(props) {
const handleClick = () => props.onClickFunction(props.increment);
return (
<button onClick={handleClick}>
+{props.increment}
</button>
);
}
function Display(props) {
return (
<div>{props.message}</div>
);
}
function App() {
const [counter, setCounter] = useState(0);
const incrementCounter = (incrementValue) => setCounter(counter+incrementValue);
return (
<div>
<Button onClickFunction={incrementCounter} increment={1} />
<Button onClickFunction={incrementCounter} increment={5} />
<Button onClickFunction={incrementCounter} increment={10} />
<Button onClickFunction={incrementCounter} increment={100} />
<Display message={counter}/>
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('mountNode'),
);
Console
This is a couple of bit did not know
Group
Outputs messages together
console.group('Group Name')
console.log('Hello 1')
console.log('Hello 1')
console.log('Hello 2')
console.groupEnd('Group Name')
Time
Outputs the time taken
for(var i = 0; i < 2000;i++) {
console.log('Fun stuff')
}
CreateObjectURL and RevokeObjectURL
This allows you to create a local URL to be used for reference. An example would be a binary image stored in a blob.
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id = 'btnLoad'>Load</button>
<button id = 'btnUnload'>Unload</button>
<img src = "x" id = 'img1'>
<img src = "x" id = 'img2'>
<img src = "x" id = 'img3'>
<img src = "x" id = 'img4'>
<script>
const btnLoad = document.getElementById("btnLoad")
const btnUnload = document.getElementById("btnUnload")
const img1 = document.getElementById("img1")
const img2 = document.getElementById("img2")
const img3 = document.getElementById("img3")
const img4 = document.getElementById("img4")
const imgs = []
imgs.push(img1)
imgs.push(img2)
imgs.push(img3)
imgs.push(img4)
let objUrl = null;
imgs.forEach(i => i.addEventListener("click", e => e.target.src = objUrl))
btnUnload.addEventListener("click", e => URL.revokeObjectURL(objUrl))
btnLoad.addEventListener("click", async e => {
const result = await fetch("http://localhost:8080/test.png")
const blob = await result.blob()
objUrl = URL.createObjectURL(blob)
alert(`object url created locally ${objUrl}`)
})
</script>
</body>
</html>
One Liners
Get count from Object
cart.map(item => item.quantity).reduce(previous, next) => previous + next,0) : 0}