SlideShare une entreprise Scribd logo
1  sur  155
What the JavaScript
Grzegorz Rozdzialik
2
About me
https://github.com/Gelio/tslint-react-hooks
Grzegorz Rozdzialik
Senior Frontend Engineer @ CodiLime
Gelio
https://github.com/Gelio/tslint-import-group-ordering
Open source:
3
Agenda
● Various JavaScript (and not only JS) quirks
○ Numbers
○ RegExps
○ Variable declarations
○ Operators (void, ||, comma)
○ try … catch
○ Objects
○ Coercion
○ Functions
○ Prototypal inheritance
Various JavaScript (and not only JS) quirks
5
Inspiration/additional resources
dotJS 2012 - Brian Leroux - WTFJS What the... JavaScript? - Kyle Simpsons
https://github.com/denysdovhan/wtfjs
6
Agenda
● Various JavaScript (and not only JS) quirks
○ Numbers
○ RegExps
○ Variable declarations
○ Operators (void, ||, comma)
○ try … catch
○ Objects
○ Coercion
○ Functions
○ Prototypal inheritance
Various JavaScript (and not only JS) quirks
Numbers
8
Working with decimals
const result = 0.1 + 0.2;
console.log(result === 0.3);
9
Working with decimals
const result = 0.1 + 0.2;
console.log(result === 0.3); // false
10
Working with decimals
const result = 0.1 + 0.2;
console.log(result === 0.3); // false
11
Numbers in JavaScript
● Follow the IEEE 754 standard (floating point
numbers)
● The same as in other programming languages (float,
double, e.g. in C, C++, C#, Rust, go)
● Non-power-of-2 fractions have limited precision
12
Numbers in JavaScript
● Follow the IEEE 754 standard (floating point
numbers)
● The same as in other programming languages (float,
double, e.g. in C, C++, C#, Rust, go)
● Non-power-of-2 fractions have limited precision
13
Numbers in JavaScript
● Follow the IEEE 754 standard (floating point
numbers)
● The same as in other programming languages (float,
double, e.g. in C, C++, C#, Rust, go)
● Non-power-of-2 fractions have limited precision
0.25 = ¼ - power of 2
14
Numbers in JavaScript
● Follow the IEEE 754 standard (floating point
numbers)
● The same as in other programming languages (float,
double, e.g. in C, C++, C#, Rust, go)
● Non-power-of-2 fractions have limited precision
● Same behavior as in other languages
15
Doubles in C++
int main()
{
cout << 0.1 + 0.2; // 0.3
return 0;
}
int main()
{
printf("%f", 0.1 + 0.2); // 0.300000
return 0;
}
16
Doubles in C++
int main()
{
double result = 0.1 + 0.2;
cout << (result == 0.3); // 0
return 0;
}
int main()
{
printf("%.17f", 0.1 + 0.2);
// 0.30000000000000004
return 0;
}
17
Special IEEE 754 values
● Non-number values have their own representation
○ NaN (Not a Number) - invalid operation, e.g. converting an object to a number
○ Positive/negative infinity - division by 0 or the value was too large
● Present in the specification
● https://en.wikipedia.org/wiki/IEEE_754-1985#Representation_of_non-numbers
● Consistent across all languages that use IEEE 754
18
Infinities
console.log(1 / 0);
console.log(-1 / 0);
console.log(Number.MAX_VALUE * 2);
19
NaNs
console.log(Math.sqrt(-5)); // NaN
console.log(Number('abc')); // NaN
20
NaN type
console.log(typeof NaN);
21
NaN type
console.log(typeof NaN); // 'number'
22
NaN type
console.log(typeof NaN); // 'number'
23
NaN type
console.log(typeof NaN); // 'number'
NaN is a specific
number (as mentioned
in IEEE 754)
24
Comparing NaNs
console.log(NaN === NaN);
console.log(NaN == NaN);
25
Comparing NaNs
console.log(NaN === NaN); // false
console.log(NaN == NaN); // false
26
Comparing NaNs
console.log(NaN === NaN); // false
console.log(NaN == NaN); // false
27
Comparing NaNs in C++
int main()
{
double result = sqrt(-5);
cout << (result == result); // false
return 0;
}
Always false (not only
in JS)
Specified in IEEE 754
28
Checking if a value is NaN
console.log(isNaN(NaN));
console.log(isNaN({}));
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
29
Checking if a value is NaN
console.log(isNaN(NaN)); // true
console.log(isNaN({}));
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
30
Checking if a value is NaN
console.log(isNaN(NaN)); // true
console.log(isNaN({})); // true
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
31
Checking if a value is NaN
console.log(isNaN(NaN)); // true
console.log(isNaN({})); // true
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
32
Checking if a value is precisely NaN
console.log(Number.isNaN({})); // false
// isNaN(x) = Number.isNaN(Number(x))
console.log(isNaN({})); // true
Number.isNaN (ES6)
https://developer.mozilla.org/
en-US/docs/Web/JavaScript/
Reference/Global_Objects/Nu
mber/isNaN
http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan
33
Agenda
● Various JavaScript (and not only JS) quirks
○ Numbers
○ RegExps
○ Variable declarations
○ Operators (void, ||, comma)
○ try … catch
○ Objects
○ Coercion
○ Functions
○ Prototypal inheritance
Various JavaScript (and not only JS) quirks
RegExps
35
Matching multiple times
const pattern = /a+b+/g;
const text =
'aabbababaaaaaaabbbbbb' ;
while (true) {
const match = pattern.exec(text);
if (match === null) {
break;
}
console.log(match[0]);
}
36
Matching multiple times
const pattern = /a+b+/g;
const text =
'aabbababaaaaaaabbbbbb' ;
while (true) {
const match = pattern.exec(text);
if (match === null) {
break;
}
console.log(match[0]);
}
37
State saved in `lastIndex`
const pattern = /a+b+/g;
const text =
'aabbababaaaaaaabbbbbb' ;
while (true) {
const match = pattern.exec(text);
if (match === null) {
break;
}
console.log(match[0], pattern.lastIndex);
}
https://developer.mozilla.org/en-U
S/docs/Web/JavaScript/Reference
/Global_Objects/RegExp/lastIndex
38
State saved in `lastIndex`
const pattern = /a+b+/g;
const text =
'aabbababaaaaaaabbbbbb' ;
while (true) {
const match = pattern.exec(text);
if (match === null) {
break;
}
console.log(match[0], pattern.lastIndex);
}
39
Change from where matching starts
const pattern = /a+b+/gi;
const text = 'aabbabABaaaaaaabbbbbb';
// 0123456789
pattern.lastIndex = 5;
40
Change from where matching starts
const pattern = /a+b+/gi;
const text = 'aabbabABaaaaaaabbbbbb';
// 0123456789
pattern.lastIndex = 5;
console.log(pattern.exec(text)[0], pattern.lastIndex); // AB, 8
41
Be careful with the global flag
const pattern = /Java/g;
const text1 = 'JavaScript is the best programming language';
pattern.exec(text1);
const text2 = 'Java is the best programming language';
pattern.exec(text2);
42
Be careful with the global flag
const pattern = /Java/g;
const text1 = 'JavaScript is the best programming language';
pattern.exec(text1);
const text2 = 'Java is the best programming language';
pattern.exec(text2);
43
Agenda
● Various JavaScript (and not only JS) quirks
○ Numbers
○ RegExps
○ Variable declarations
○ Operators (void, ||, comma)
○ try … catch
○ Objects
○ Coercion
○ Functions
○ Prototypal inheritance
Various JavaScript (and not only JS) quirks
Variable declarations
45
Variable scope - const, let
function foo() {
if (true) {
const a = 1;
let b = 2;
}
console.log(a, b);
}
foo();
46
Variable scope - const, let
function foo() {
if (true) {
const a = 1;
let b = 2;
}
console.log(a, b); // ReferenceError: a is not defined
}
foo();
47
Variable scope - var
function foo() {
if (true) {
var a = 10;
}
console.log(a);
}
foo();
48
Variable scope - var
function foo() {
if (true) {
var a = 10;
}
console.log(a); // 10
}
foo();
49
Variable scope - var
function foo() {
if (true) {
var a = 10;
}
console.log(a); // 10
}
foo();
50
Hoisting
function foo() {
console.log(a);
var a = 0;
console.log(a);
}
foo();
51
Hoisting
function foo() {
console.log(a); // undefined
var a = 0;
console.log(a); // 0
}
foo();
52
Hoisting
function foo() {
console.log(a); // undefined
var a = 0;
console.log(a); // 0
}
foo();
53
Hoisting explained
function foo() {
var a;
console.log(a);
a = 0;
console.log(a);
}
foo();
https://developer.mozilla.org/en-US/docs
/Glossary/Hoisting
function foo() {
console.log(a);
var a = 0;
console.log(a);
}
foo();
54
Hoisting explained
function foo() {
var a;
console.log(a); // undefined
a = 0;
console.log(a); // 0
}
foo();
https://developer.mozilla.org/en-US/docs
/Glossary/Hoisting
function foo() {
console.log(a);
var a = 0;
console.log(a);
}
foo();
55
Do not do this at home
function foo() {
a = 1;
console.log(a); // 1
var a = 0;
console.log(a); // 0
}
foo();
56
`var` scope
var foo = 1;
console.log(window.foo);
57
`var` scope
var foo = 1;
console.log(window.foo); // 1
58
`var` scope
var foo = 1;
console.log(window.foo); // 1
59
IIFE to the rescue
IIFE - Immediately Invoked Function Expression
(function() {
var bar = 1;
console.log(window.bar); // undefined
})();
https://developer.mozilla.org/en-US
/docs/Glossary/IIFE
60
… or use `let` and `const`
const baz = 1;
let abc = 2;
console.log(window.baz);
console.log(window.abc);
61
Agenda
● Various JavaScript (and not only JS) quirks
○ Numbers
○ RegExps
○ Variable declarations
○ Operators (void, ||, comma)
○ try … catch
○ Objects
○ Coercion
○ Functions
○ Prototypal inheritance
Various JavaScript (and not only JS) quirks
Operators
63
`void` operator
console.log(void 0, void true, void undefined, void 'anything');
https://developer.mozilla.org/en-U
S/docs/Web/JavaScript/Reference
/Operators/void
64
`void` operator
console.log(void 0, void true, void undefined, void 'anything');
// undefined, undefined, undefined, undefined
https://developer.mozilla.org/en-U
S/docs/Web/JavaScript/Reference
/Operators/void
65
`void`’s usefulness
class Foo {
counter = 0;
setCounter = x => (this.counter = x);
}
const foo = new Foo();
console.log(foo.setCounter(50));
66
`void`’s usefulness
class Foo {
counter = 0;
setCounter = x => (this.counter = x);
}
const foo = new Foo();
console.log(foo.setCounter(50)); // 50
67
`void`’s usefulness
class Foo {
counter = 0;
setCounter = x => (this.counter = x);
safeSetCounter = x => {
this.counter = x;
}
}
const foo = new Foo();
foo.setCounter(50);
foo.safeSetCounter (50);
68
`void`’s usefulness
class Foo {
counter = 0;
setCounter = x => (this.counter = x);
safeSetCounter = x =>
void (this.counter = x);
}
const foo = new Foo();
foo.setCounter(50);
foo.safeSetCounter (50);
69
Overwriting undefined
function example1(undefined) {
undefined = true;
if (undefined) {
console.log('Surprised?');
}
}
70
Overwriting undefined
function example1(undefined) {
undefined = true;
if (undefined) {
console.log('Surprised?');
}
}
71
Overwriting undefined
function example1(undefined) {
undefined = true;
if (undefined) {
console.log('Surprised?');
}
}
72
Restoring undefined with void operator
function example3(undefined) {
undefined = true;
console.log({ undefined }); // { undefined: true }
undefined = void 0;
console.log({ undefined }); // { undefined: undefined }
}
73
Usage in TypeScript compiler
TypeScript compiler uses void 0 instead of undefined directly
74
Or (||) operator
Operands (and return type)
can be boolean...
75
Or (||) operator
… but do not have to be
Operands (and return type)
can be boolean...
76
Falsy values
Boolean(0);
Boolean('');
Boolean(undefined);
Boolean(null);
Boolean(NaN);
Boolean(false);
77
Or (||) operator - lazy evaluation
function getValue() {
console.log('This will not run, because 5 is truthy');
return 10;
}
console.log(5 || getValue());
Operands are evaluated lazily
78
Or (||) operator - default function parameter
function foo(arg) {
arg = arg || 10;
console.log(arg);
}
foo(1);
foo(5);
foo();
foo(0);
79
Or (||) operator - default function parameter
function foo(arg) {
arg = arg || 10;
console.log(arg);
}
foo(1); // 1
foo(5); // 5
foo(); // 10
foo(0);
80
Or (||) operator - default function parameter
function foo(arg) {
arg = arg || 10;
console.log(arg);
}
foo(1); // 1
foo(5); // 5
foo(); // 10
foo(0); // 10 (?)
81
Or (||) operator - default function parameter
function foo(arg) {
arg = arg || 10;
console.log(arg);
}
foo(1); // 1
foo(5); // 5
foo(); // 10
foo(0); // 10 (?)
82
A safe way to have default parameters
function safeFoo(arg = 10) {
console.log(arg);
}
safeFoo(0); // 0
Introduced in ES6
83
Fun fact - any param can have a default value
function safeFoo(arg = 10, arg2) {
console.log(arg, arg2);
}
safeFoo(undefined, 20);
84
Nullish coalescing operator
https://github.com/tc39/proposal-nullish-coalescing (stage 4)
Similar to ||,
but works with null and undefined only
function safeFoo2(arg) {
arg = arg ?? 10;
console.log(arg);
}
safeFoo2(0);
85
Tuples in JS?
const tuple = (1, 2, 3);
console.log(tuple);
86
Tuples in JS?
const tuple = (1, 2, 3);
console.log(tuple); // 3
87
Tuples in JS?
const tuple = (1, 2, 3);
console.log(tuple); // 3
88
Tuples in JS?
const tuple = (1, 2, 3);
console.log(tuple); // 3
Similar behavior in other
languages, e.g. C, C++
89
Comma operator in C
int main()
{
int x = 10, y = 15;
printf("%d", (x, y)); // 15
return 0;
}
90
Comma operator
const doMultipleThings = (service) =>
(
service.doA(),
service.doB(),
service.doC()
);
Evaluates the expression on the left, returns the expression on the right
const boringDoMultipleThings =
(service) => {
service.doA();
service.doB();
return service.doC();
}
91
A side note on ASI
What happens if you don’t like semicolons?
const boringDoMultipleThings =
(service) => {
service.doA();
return service.doC();
}
92
A side note on ASI
What happens if you don’t like semicolons?
const boringDoMultipleThings =
(service) => {
service.doA();
return service.doC();
}
93
A side note on ASI
What happens if you do not like semicolons?
const boringDoMultipleThings =
(service) => {
service.doA()
return service.doC()
}
94
A side note on ASI
const boringDoMultipleThings =
(service) => {
service.doA()
return
service.doC()
}
What happens if you don’t like semicolons?
95
A side note on ASI
const boringDoMultipleThings =
(service) => {
service.doA()
return
service.doC()
}
boringDoMultipleThings()
What happens if you don’t like semicolons?
96
A side note on ASI
const boringDoMultipleThings =
(service) => {
service.doA()
return
service.doC()
}
boringDoMultipleThings()
Not executed
What happens if you don’t like semicolons?
97
A side note on ASI
ASI - Automatic Semicolon Insertion
const boringDoMultipleThings =
(service) => {
service.doA()
return
service.doC()
}
boringDoMultipleThings()
const boringDoMultipleThings =
(service) => {
service.doA();
return;
service.doC();
}
boringDoMultipleThings();
98
A side note on ASI
ASI - Automatic Semicolon Insertion
const boringDoMultipleThings =
(service) => {
service.doA()
return
service.doC()
}
boringDoMultipleThings()
const boringDoMultipleThings =
(service) => {
service.doA();
return;
service.doC();
}
boringDoMultipleThings();
Use a linter
99
Agenda
● Various JavaScript (and not only JS) quirks
○ Numbers
○ RegExps
○ Variable declarations
○ Operators (void, ||, comma)
○ try … catch
○ Objects
○ Coercion
○ Functions
○ Prototypal inheritance
Various JavaScript (and not only JS) quirks
try … catch
101
try … finally without catch
function throwWithNoReturn() {
try {
throw new Error();
} finally {
}
}
throwWithNoReturn();
102
try … finally without catch
function throwWithNoReturn() {
try {
throw new Error();
} finally {
}
}
throwWithNoReturn();
103
try … finally - return in finally
function throwAndReturnInFinally() {
try {
throw new Error();
} finally {
return 'I will be returned';
}
}
throwAndReturnInFinally();
104
try … finally - return in finally
function throwAndReturnInFinally() {
try {
throw new Error();
} finally {
return 'I will be returned';
}
}
throwAndReturnInFinally();
105
try … finally - return in finally
function throwAndReturnInFinally() {
try {
throw new Error();
} finally {
return 'I will be returned';
}
}
throwAndReturnInFinally();
Where is the error?
106
try … finally - returning
function returnsInTryAndFinally() {
try {
return 'I want to be returned';
} finally {
return "No, you won't";
}
}
returnsInTryAndFinally();
107
try … finally - returning
function returnsInTryAndFinally() {
try {
return 'I want to be returned';
} finally {
return "No, you won't";
}
}
returnsInTryAndFinally();
108
try … finally - returning
function returnsInTryAndFinally() {
try {
return 'I want to be returned';
} finally {
return "No, you won't";
}
}
returnsInTryAndFinally();
109
Agenda
● Various JavaScript (and not only JS) quirks
○ Numbers
○ RegExps
○ Variable declarations
○ Operators (void, ||, comma)
○ try … catch
○ Objects
○ Coercion
○ Functions
○ Prototypal inheritance
Various JavaScript (and not only JS) quirks
Objects
111
Type of null
console.log(typeof null);
112
Type of null
console.log(typeof null); // 'object'
113
Type of null
console.log(typeof null); // 'object'
114
Type of null - explanation
https://v8.dev/blog/react-cliff
Similar to NaN for numbers
Source: v8.dev/blog/react-cliff
115
toJSON with JSON.stringify
const obj = {
a: 1,
b: 2,
toJSON: function() {
return 'definitely not an object';
}
};
console.log(JSON.stringify(obj));
116
toJSON with JSON.stringify
const obj = {
a: 1,
b: 2,
toJSON: function() {
return 'definitely not an object';
}
};
console.log(JSON.stringify(obj));
117
toJSON with JSON.stringify
const obj = {
a: 1,
b: 2,
toJSON: function() {
return 'definitely not an object';
}
};
console.log(JSON.stringify(obj));
118
Agenda
● Various JavaScript (and not only JS) quirks
○ Numbers
○ RegExps
○ Variable declarations
○ Operators (void, ||, comma)
○ try … catch
○ Objects
○ Coercion
○ Functions
○ Prototypal inheritance
Various JavaScript (and not only JS) quirks
Coercion
120
Objects and == (for numbers)
console.log(foo == 1);
console.log(foo == 2);
console.log(foo == 3);
console.log(Number(foo));
console.log(Number(foo));
121
Objects and == (for numbers)
const foo = {
counter: 0,
valueOf: function() {
return ++this.counter;
}
};
console.log(foo == 1);
console.log(foo == 2);
console.log(foo == 3);
console.log(Number(foo));
console.log(Number(foo));
122
Agenda
● Various JavaScript (and not only JS) quirks
○ Numbers
○ RegExps
○ Variable declarations
○ Operators (void, ||, comma)
○ try … catch
○ Objects
○ Coercion
○ Functions
○ Prototypal inheritance
Various JavaScript (and not only JS) quirks
Functions
124
Variadic functions
Variadic - take an arbitrary number of arguments (e.g. console.log)
sum(1, 2); // 3
sum(1, 2, 3, 4, 5, 6, 7); // 28
125
Variadic functions in ES6 (rest syntax)
function es6Sum(...args) {
return args.reduce((sum, x) => sum + x, 0);
}
126
Variadic functions in ES5
function es5Sum() {
let result = 0;
for (let i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
}
127
arguments - not a valid array
function invalidUse() {
arguments.forEach(x => {
// ...
});
}
128
arguments + Array.from = <3
function invalidUse() {
Array.from(arguments).forEach(x => {
// ...
});
}
129
Agenda
● Various JavaScript (and not only JS) quirks
○ Numbers
○ RegExps
○ Variable declarations
○ Operators (void, ||, comma)
○ try … catch
○ Objects
○ Coercion
○ Functions
○ Prototypal inheritance
Various JavaScript (and not only JS) quirks
Prototypal inheritance
131
“Inheritance” in JavaScript
● Prototypal inheritance (not classical inheritance)
● Each object has a [[Prototype]] (another object or null)
● Prototype chain - multiple objects connected via prototype
● During property lookup, either:
○ Property exists on the object itself
○ The prototype chain is traversed to find the property
● Can be confusing for programmers of other languages
● Dynamic - can be manipulated at runtime
Animal.prototype
Object.prototype
null
cat dog
132
Custom merge
function merge(dest, src) {
for (let property in src) {
if (
typeof dest[property] === 'object' &&
typeof src[property] === 'object'
) {
merge(dest[property], src[property]);
} else {
dest[property] = src[property];
}
}
}
133
Custom merge - happy scenario
const options = {
// default options
fetchNestedData: true,
pageSize: 10
};
const additionalOptions = JSON.parse(
'{ "fetchNestedData": false }' );
merge(options, additionalOptions );
134
Custom merge - prototype pollution
const options = {
fetchNestedData: true,
pageSize: 10
};
const additionalOptions = JSON.parse('{ "__proto__": { "isAdmin":
true }}');
merge(options, additionalOptions);
135
Custom merge - prototype pollution
const options = {
fetchNestedData: true,
pageSize: 10
};
const additionalOptions = JSON.parse('{ "__proto__": { "isAdmin":
true }}');
merge(options, additionalOptions);
136
Custom merge - prototype pollution
const options = {
fetchNestedData: true,
pageSize: 10
};
const additionalOptions = JSON.parse('{ "__proto__": { "isAdmin":
true }}');
merge(options, additionalOptions);
More information:
https://codeburst.io/what-is-prototype-pollution-49482fc4b638
https://snyk.io/vuln/SNYK-JS-LODASH-450202
137
Monkey patching
console.log('test before patching' );
const originalLog = console.log;
console.log = function(...args) {
return originalLog.call(this, 'patched log', ...args);
};
console.log('test after patching' );
138
Monkey patching
console.log('test before patching' );
const originalLog = console.log;
console.log = function(...args) {
return originalLog.call(this, 'patched log', ...args);
};
console.log('test after patching' );
139
Monkey patching - polyfilling
Array.prototype.flat = function() {
return this.reduce((arr, element) => arr.concat(element), []);
};
[1, [2], [3]].flat();
140
Monkey patching - polyfilling
Array.prototype.flat = function() {
return this.reduce((arr, element) => arr.concat(element), []);
};
[1, [2], [3]].flat();
Careful
MooTools monkey-patched Array.prototype.flatten
https://mootools.net/core/docs/1.5.2/Types/Array#Array:flatten
https://github.com/mootools/mootools-core/blob/master/Source/Types/Array.js
#L132-L140
Result:
https://developers.google.com/web/updates/2018/03/smooshgate
141
Shortening property access
Source: https://www.omnicalculator.com/math/law-of-cosines
function calculateSideLength (a, b, alpha) {
return Math.sqrt(
Math.pow(a, 2) + Math.pow(b, 2) - 2 * a * b *
Math.cos(alpha)
);
}
142
with statement
Source: https://www.omnicalculator.com/math/law-of-cosines
function calculateSideLength2 (a, b, alpha) {
with (Math) {
return sqrt(pow(a, 2) + pow(b, 2) -
2 * a * b * cos(alpha));
}
}
143
with statement
function extractValuesFromSubarrays (array, indexOf) {
with (array) {
return map(subArray => subArray[indexOf]);
}
}
const array = [[1, 2, 3], [4, 5]];
extractValuesFromSubarrays (array, 1); // [2, 5] ?
144
with statement
function extractValuesFromSubarrays (array, indexOf) {
with (array) {
return map(subArray => subArray[indexOf]);
}
}
const array = [[1, 2, 3], [4, 5]];
extractValuesFromSubarrays (array, 1); // [undefined, undefined]
145
with statement
function extractValuesFromSubarrays (array, indexOf) {
with (array) {
return map(subArray => subArray[indexOf]);
}
}
const array = [[1, 2, 3], [4, 5]];
extractValuesFromSubarrays (array, 1); // [undefined, undefined]
Array.prototype.indexOf,
not the indexOf parameter
146
with statement
● Cannot be optimized by the compiler (depends on the runtime value)
● Not recommended
● Will throw an error in strict mode
More information:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Sta
tements/with
147
with statement
function extractValuesFromSubarrays (array, find) {
with (array) {
return map(subArray => subArray[find]);
}
}
const array = [[1, 2, 3], [4, 5]];
extractValuesFromSubarrays (array, 1);
148
with statement
function extractValuesFromSubarrays (array, find) {
with (array) {
return map(subArray => subArray[find]);
}
}
const array = [[1, 2, 3], [4, 5]];
extractValuesFromSubarrays (array, 1);
149
with statement
function extractValuesFromSubarrays (array, find) {
with (array) {
return map(subArray => subArray[find]);
}
}
const array = [[1, 2, 3], [4, 5]];
extractValuesFromSubarrays (array, 1);
150
with + Symbol.unscopables
https://developer.mozilla.org/en-U
S/docs/Web/JavaScript/Reference
/Global_Objects/Symbol/unscopabl
es
Symbol.unscopables - points
to an object with property names
that should not be scoped by the
with statement
Introduced in ES6
151
with + Symbol.unscopables
https://developer.mozilla.org/en-U
S/docs/Web/JavaScript/Reference
/Global_Objects/Symbol/unscopabl
es
find is not scoped,
but indexOf is
Symbol.unscopables - points
to an object with property names
that should not be scoped by the
with statement
Introduced in ES6
152
Other fun symbols
Well-known symbols:
● Symbol.iterator (used by for...of)
● Symbol.asyncIterator (used by for await...of)
● Symbol.hasInstance (used by instanceof)
● Symbol.toPrimitive
https://developer.mozilla.org/en-US/docs/Web/JavaScript
/Reference/Global_Objects/Symbol
Introduced in ES6
Summary
154
Summary
● Not all quirks are JavaScript-only (comma operator, IEEE 754)
● New features make it easier to avoid pitfalls (arrow functions, const,
let)
● Some features are very different than in other languages (prototypal
inheritance), so watch out
Thank you
Krancowa 5
02-493, Warsaw
Poland
+48 22 389 51 00
contact@codilime.com

Contenu connexe

Tendances

C++ Programming - 2nd Study
C++ Programming - 2nd StudyC++ Programming - 2nd Study
C++ Programming - 2nd StudyChris Ohk
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...Andrey Karpov
 
Basic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python ProgrammersBasic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python ProgrammersAppier
 
Data Structure - 2nd Study
Data Structure - 2nd StudyData Structure - 2nd Study
Data Structure - 2nd StudyChris Ohk
 
Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >Sergey Platonov
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CSteffen Wenz
 
Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。Mr. Vengineer
 
Diving into HHVM Extensions (Brno PHP Conference 2015)
Diving into HHVM Extensions (Brno PHP Conference 2015)Diving into HHVM Extensions (Brno PHP Conference 2015)
Diving into HHVM Extensions (Brno PHP Conference 2015)James Titcumb
 
Let's talks about string operations in C++17
Let's talks about string operations in C++17Let's talks about string operations in C++17
Let's talks about string operations in C++17Bartlomiej Filipek
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 FeaturesJan Rüegg
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Anton Bikineev
 
[C++ korea] effective modern c++ study item 3 understand decltype +이동우
[C++ korea] effective modern c++ study   item 3 understand decltype +이동우[C++ korea] effective modern c++ study   item 3 understand decltype +이동우
[C++ korea] effective modern c++ study item 3 understand decltype +이동우Seok-joon Yun
 
Why my Go program is slow?
Why my Go program is slow?Why my Go program is slow?
Why my Go program is slow?Inada Naoki
 
Network lab manual
Network lab manualNetwork lab manual
Network lab manualPrabhu D
 
The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184Mahmoud Samir Fayed
 

Tendances (20)

C++ Programming - 2nd Study
C++ Programming - 2nd StudyC++ Programming - 2nd Study
C++ Programming - 2nd Study
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
C++ via C#
C++ via C#C++ via C#
C++ via C#
 
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...
 
Basic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python ProgrammersBasic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python Programmers
 
Data Structure - 2nd Study
Data Structure - 2nd StudyData Structure - 2nd Study
Data Structure - 2nd Study
 
Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in C
 
Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。
 
Lecture05
Lecture05Lecture05
Lecture05
 
Diving into HHVM Extensions (Brno PHP Conference 2015)
Diving into HHVM Extensions (Brno PHP Conference 2015)Diving into HHVM Extensions (Brno PHP Conference 2015)
Diving into HHVM Extensions (Brno PHP Conference 2015)
 
Constructor,destructors cpp
Constructor,destructors cppConstructor,destructors cpp
Constructor,destructors cpp
 
Let's talks about string operations in C++17
Let's talks about string operations in C++17Let's talks about string operations in C++17
Let's talks about string operations in C++17
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
 
[C++ korea] effective modern c++ study item 3 understand decltype +이동우
[C++ korea] effective modern c++ study   item 3 understand decltype +이동우[C++ korea] effective modern c++ study   item 3 understand decltype +이동우
[C++ korea] effective modern c++ study item 3 understand decltype +이동우
 
Why my Go program is slow?
Why my Go program is slow?Why my Go program is slow?
Why my Go program is slow?
 
Network lab manual
Network lab manualNetwork lab manual
Network lab manual
 
The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184
 

Similaire à CodiLime Tech Talk - Grzegorz Rozdzialik: What the java script

EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
NetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf EditionNetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf EditionPaulo Morgado
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityGeorgePeterBanyard
 
JavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersJavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersRick Beerendonk
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptxGuy Komari
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervosoLuis Vendrame
 
Halide tutorial 2019
Halide tutorial 2019Halide tutorial 2019
Halide tutorial 2019Champ Yen
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoRodolfo Carvalho
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...
Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...
Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...Igalia
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)
개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)
개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)changehee lee
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 

Similaire à CodiLime Tech Talk - Grzegorz Rozdzialik: What the java script (20)

EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
NetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf EditionNetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf Edition
 
C Programming Homework Help
C Programming Homework HelpC Programming Homework Help
C Programming Homework Help
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
JavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersJavaScript 2016 for C# Developers
JavaScript 2016 for C# Developers
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
Day 1
Day 1Day 1
Day 1
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
 
Halide tutorial 2019
Halide tutorial 2019Halide tutorial 2019
Halide tutorial 2019
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...
Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...
Community-driven Language Design at TC39 on the JavaScript Pipeline Operator ...
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)
개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)
개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
dojo.Patterns
dojo.Patternsdojo.Patterns
dojo.Patterns
 

Plus de CodiLime

CodiLime Tech Talk - Dawid Trzebiatowski i Wojciech Urbański: Opening the Flo...
CodiLime Tech Talk - Dawid Trzebiatowski i Wojciech Urbański: Opening the Flo...CodiLime Tech Talk - Dawid Trzebiatowski i Wojciech Urbański: Opening the Flo...
CodiLime Tech Talk - Dawid Trzebiatowski i Wojciech Urbański: Opening the Flo...CodiLime
 
Rapid help for current networking challenges
Rapid help for current networking challengesRapid help for current networking challenges
Rapid help for current networking challengesCodiLime
 
CodiLime Tech Talk - Mateusz Psujek: Keep calm and stay motivated
CodiLime Tech Talk - Mateusz Psujek: Keep calm and stay motivatedCodiLime Tech Talk - Mateusz Psujek: Keep calm and stay motivated
CodiLime Tech Talk - Mateusz Psujek: Keep calm and stay motivatedCodiLime
 
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...CodiLime
 
CodiLime Tech Talk - Wojciech Urbański: Cloud Native
CodiLime Tech Talk - Wojciech Urbański: Cloud NativeCodiLime Tech Talk - Wojciech Urbański: Cloud Native
CodiLime Tech Talk - Wojciech Urbański: Cloud NativeCodiLime
 
CodiLime Tech Talk - Łukasz Maksymczuk: Monitoring: Prometheus and Influx
CodiLime Tech Talk - Łukasz Maksymczuk: Monitoring: Prometheus and InfluxCodiLime Tech Talk - Łukasz Maksymczuk: Monitoring: Prometheus and Influx
CodiLime Tech Talk - Łukasz Maksymczuk: Monitoring: Prometheus and InfluxCodiLime
 
CodiLime Tech Talk - Michał Sochoń: Configuration management hell
CodiLime Tech Talk - Michał Sochoń: Configuration management hellCodiLime Tech Talk - Michał Sochoń: Configuration management hell
CodiLime Tech Talk - Michał Sochoń: Configuration management hellCodiLime
 
CodiLime Tech Talk - Adam Kułagowski: IPv6 - introduction
CodiLime Tech Talk - Adam Kułagowski: IPv6 - introductionCodiLime Tech Talk - Adam Kułagowski: IPv6 - introduction
CodiLime Tech Talk - Adam Kułagowski: IPv6 - introductionCodiLime
 
Tech Talk - Konrad Gawda : P4 programming language
Tech Talk - Konrad Gawda : P4 programming languageTech Talk - Konrad Gawda : P4 programming language
Tech Talk - Konrad Gawda : P4 programming languageCodiLime
 
CodiLime Tech Talk - Michał Pawluk: Our production deployment in AWS (HashiCo...
CodiLime Tech Talk - Michał Pawluk: Our production deployment in AWS (HashiCo...CodiLime Tech Talk - Michał Pawluk: Our production deployment in AWS (HashiCo...
CodiLime Tech Talk - Michał Pawluk: Our production deployment in AWS (HashiCo...CodiLime
 
CodiLime Tech Talk - Michał Cłapiński, Mateusz Jabłoński: Debugging faultily ...
CodiLime Tech Talk - Michał Cłapiński, Mateusz Jabłoński: Debugging faultily ...CodiLime Tech Talk - Michał Cłapiński, Mateusz Jabłoński: Debugging faultily ...
CodiLime Tech Talk - Michał Cłapiński, Mateusz Jabłoński: Debugging faultily ...CodiLime
 
CodiLime Tech Talk - Michał Pawluk: Our deployment of HashiCorp Vault
CodiLime Tech Talk - Michał Pawluk: Our deployment of HashiCorp VaultCodiLime Tech Talk - Michał Pawluk: Our deployment of HashiCorp Vault
CodiLime Tech Talk - Michał Pawluk: Our deployment of HashiCorp VaultCodiLime
 
CodiLime Tech Talk - Jan Kanty Milczek: Basic Recommender Systems – SVDon't
CodiLime Tech Talk - Jan Kanty Milczek: Basic Recommender Systems – SVDon'tCodiLime Tech Talk - Jan Kanty Milczek: Basic Recommender Systems – SVDon't
CodiLime Tech Talk - Jan Kanty Milczek: Basic Recommender Systems – SVDon'tCodiLime
 
CodiLime Tech Talk - Michał Sochoń: Sphinx, reST & Ansible
CodiLime Tech Talk - Michał Sochoń: Sphinx, reST & AnsibleCodiLime Tech Talk - Michał Sochoń: Sphinx, reST & Ansible
CodiLime Tech Talk - Michał Sochoń: Sphinx, reST & AnsibleCodiLime
 
CodiLime Tech Talk - Maciej Sawicki: Streamline application deployments with ...
CodiLime Tech Talk - Maciej Sawicki: Streamline application deployments with ...CodiLime Tech Talk - Maciej Sawicki: Streamline application deployments with ...
CodiLime Tech Talk - Maciej Sawicki: Streamline application deployments with ...CodiLime
 
CodiLime Tech Talk - Jarek Łukow: You need a cloud to test a cloud: using Ope...
CodiLime Tech Talk - Jarek Łukow: You need a cloud to test a cloud: using Ope...CodiLime Tech Talk - Jarek Łukow: You need a cloud to test a cloud: using Ope...
CodiLime Tech Talk - Jarek Łukow: You need a cloud to test a cloud: using Ope...CodiLime
 

Plus de CodiLime (16)

CodiLime Tech Talk - Dawid Trzebiatowski i Wojciech Urbański: Opening the Flo...
CodiLime Tech Talk - Dawid Trzebiatowski i Wojciech Urbański: Opening the Flo...CodiLime Tech Talk - Dawid Trzebiatowski i Wojciech Urbański: Opening the Flo...
CodiLime Tech Talk - Dawid Trzebiatowski i Wojciech Urbański: Opening the Flo...
 
Rapid help for current networking challenges
Rapid help for current networking challengesRapid help for current networking challenges
Rapid help for current networking challenges
 
CodiLime Tech Talk - Mateusz Psujek: Keep calm and stay motivated
CodiLime Tech Talk - Mateusz Psujek: Keep calm and stay motivatedCodiLime Tech Talk - Mateusz Psujek: Keep calm and stay motivated
CodiLime Tech Talk - Mateusz Psujek: Keep calm and stay motivated
 
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...
CodiLime Tech Talk - Katarzyna Ziomek-Zdanowicz: RxJS main concepts and real ...
 
CodiLime Tech Talk - Wojciech Urbański: Cloud Native
CodiLime Tech Talk - Wojciech Urbański: Cloud NativeCodiLime Tech Talk - Wojciech Urbański: Cloud Native
CodiLime Tech Talk - Wojciech Urbański: Cloud Native
 
CodiLime Tech Talk - Łukasz Maksymczuk: Monitoring: Prometheus and Influx
CodiLime Tech Talk - Łukasz Maksymczuk: Monitoring: Prometheus and InfluxCodiLime Tech Talk - Łukasz Maksymczuk: Monitoring: Prometheus and Influx
CodiLime Tech Talk - Łukasz Maksymczuk: Monitoring: Prometheus and Influx
 
CodiLime Tech Talk - Michał Sochoń: Configuration management hell
CodiLime Tech Talk - Michał Sochoń: Configuration management hellCodiLime Tech Talk - Michał Sochoń: Configuration management hell
CodiLime Tech Talk - Michał Sochoń: Configuration management hell
 
CodiLime Tech Talk - Adam Kułagowski: IPv6 - introduction
CodiLime Tech Talk - Adam Kułagowski: IPv6 - introductionCodiLime Tech Talk - Adam Kułagowski: IPv6 - introduction
CodiLime Tech Talk - Adam Kułagowski: IPv6 - introduction
 
Tech Talk - Konrad Gawda : P4 programming language
Tech Talk - Konrad Gawda : P4 programming languageTech Talk - Konrad Gawda : P4 programming language
Tech Talk - Konrad Gawda : P4 programming language
 
CodiLime Tech Talk - Michał Pawluk: Our production deployment in AWS (HashiCo...
CodiLime Tech Talk - Michał Pawluk: Our production deployment in AWS (HashiCo...CodiLime Tech Talk - Michał Pawluk: Our production deployment in AWS (HashiCo...
CodiLime Tech Talk - Michał Pawluk: Our production deployment in AWS (HashiCo...
 
CodiLime Tech Talk - Michał Cłapiński, Mateusz Jabłoński: Debugging faultily ...
CodiLime Tech Talk - Michał Cłapiński, Mateusz Jabłoński: Debugging faultily ...CodiLime Tech Talk - Michał Cłapiński, Mateusz Jabłoński: Debugging faultily ...
CodiLime Tech Talk - Michał Cłapiński, Mateusz Jabłoński: Debugging faultily ...
 
CodiLime Tech Talk - Michał Pawluk: Our deployment of HashiCorp Vault
CodiLime Tech Talk - Michał Pawluk: Our deployment of HashiCorp VaultCodiLime Tech Talk - Michał Pawluk: Our deployment of HashiCorp Vault
CodiLime Tech Talk - Michał Pawluk: Our deployment of HashiCorp Vault
 
CodiLime Tech Talk - Jan Kanty Milczek: Basic Recommender Systems – SVDon't
CodiLime Tech Talk - Jan Kanty Milczek: Basic Recommender Systems – SVDon'tCodiLime Tech Talk - Jan Kanty Milczek: Basic Recommender Systems – SVDon't
CodiLime Tech Talk - Jan Kanty Milczek: Basic Recommender Systems – SVDon't
 
CodiLime Tech Talk - Michał Sochoń: Sphinx, reST & Ansible
CodiLime Tech Talk - Michał Sochoń: Sphinx, reST & AnsibleCodiLime Tech Talk - Michał Sochoń: Sphinx, reST & Ansible
CodiLime Tech Talk - Michał Sochoń: Sphinx, reST & Ansible
 
CodiLime Tech Talk - Maciej Sawicki: Streamline application deployments with ...
CodiLime Tech Talk - Maciej Sawicki: Streamline application deployments with ...CodiLime Tech Talk - Maciej Sawicki: Streamline application deployments with ...
CodiLime Tech Talk - Maciej Sawicki: Streamline application deployments with ...
 
CodiLime Tech Talk - Jarek Łukow: You need a cloud to test a cloud: using Ope...
CodiLime Tech Talk - Jarek Łukow: You need a cloud to test a cloud: using Ope...CodiLime Tech Talk - Jarek Łukow: You need a cloud to test a cloud: using Ope...
CodiLime Tech Talk - Jarek Łukow: You need a cloud to test a cloud: using Ope...
 

Dernier

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Dernier (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

CodiLime Tech Talk - Grzegorz Rozdzialik: What the java script

  • 2. 2 About me https://github.com/Gelio/tslint-react-hooks Grzegorz Rozdzialik Senior Frontend Engineer @ CodiLime Gelio https://github.com/Gelio/tslint-import-group-ordering Open source:
  • 3. 3 Agenda ● Various JavaScript (and not only JS) quirks ○ Numbers ○ RegExps ○ Variable declarations ○ Operators (void, ||, comma) ○ try … catch ○ Objects ○ Coercion ○ Functions ○ Prototypal inheritance
  • 4. Various JavaScript (and not only JS) quirks
  • 5. 5 Inspiration/additional resources dotJS 2012 - Brian Leroux - WTFJS What the... JavaScript? - Kyle Simpsons https://github.com/denysdovhan/wtfjs
  • 6. 6 Agenda ● Various JavaScript (and not only JS) quirks ○ Numbers ○ RegExps ○ Variable declarations ○ Operators (void, ||, comma) ○ try … catch ○ Objects ○ Coercion ○ Functions ○ Prototypal inheritance
  • 7. Various JavaScript (and not only JS) quirks Numbers
  • 8. 8 Working with decimals const result = 0.1 + 0.2; console.log(result === 0.3);
  • 9. 9 Working with decimals const result = 0.1 + 0.2; console.log(result === 0.3); // false
  • 10. 10 Working with decimals const result = 0.1 + 0.2; console.log(result === 0.3); // false
  • 11. 11 Numbers in JavaScript ● Follow the IEEE 754 standard (floating point numbers) ● The same as in other programming languages (float, double, e.g. in C, C++, C#, Rust, go) ● Non-power-of-2 fractions have limited precision
  • 12. 12 Numbers in JavaScript ● Follow the IEEE 754 standard (floating point numbers) ● The same as in other programming languages (float, double, e.g. in C, C++, C#, Rust, go) ● Non-power-of-2 fractions have limited precision
  • 13. 13 Numbers in JavaScript ● Follow the IEEE 754 standard (floating point numbers) ● The same as in other programming languages (float, double, e.g. in C, C++, C#, Rust, go) ● Non-power-of-2 fractions have limited precision 0.25 = ¼ - power of 2
  • 14. 14 Numbers in JavaScript ● Follow the IEEE 754 standard (floating point numbers) ● The same as in other programming languages (float, double, e.g. in C, C++, C#, Rust, go) ● Non-power-of-2 fractions have limited precision ● Same behavior as in other languages
  • 15. 15 Doubles in C++ int main() { cout << 0.1 + 0.2; // 0.3 return 0; } int main() { printf("%f", 0.1 + 0.2); // 0.300000 return 0; }
  • 16. 16 Doubles in C++ int main() { double result = 0.1 + 0.2; cout << (result == 0.3); // 0 return 0; } int main() { printf("%.17f", 0.1 + 0.2); // 0.30000000000000004 return 0; }
  • 17. 17 Special IEEE 754 values ● Non-number values have their own representation ○ NaN (Not a Number) - invalid operation, e.g. converting an object to a number ○ Positive/negative infinity - division by 0 or the value was too large ● Present in the specification ● https://en.wikipedia.org/wiki/IEEE_754-1985#Representation_of_non-numbers ● Consistent across all languages that use IEEE 754
  • 18. 18 Infinities console.log(1 / 0); console.log(-1 / 0); console.log(Number.MAX_VALUE * 2);
  • 23. 23 NaN type console.log(typeof NaN); // 'number' NaN is a specific number (as mentioned in IEEE 754)
  • 24. 24 Comparing NaNs console.log(NaN === NaN); console.log(NaN == NaN);
  • 25. 25 Comparing NaNs console.log(NaN === NaN); // false console.log(NaN == NaN); // false
  • 26. 26 Comparing NaNs console.log(NaN === NaN); // false console.log(NaN == NaN); // false
  • 27. 27 Comparing NaNs in C++ int main() { double result = sqrt(-5); cout << (result == result); // false return 0; } Always false (not only in JS) Specified in IEEE 754
  • 28. 28 Checking if a value is NaN console.log(isNaN(NaN)); console.log(isNaN({})); https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
  • 29. 29 Checking if a value is NaN console.log(isNaN(NaN)); // true console.log(isNaN({})); https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
  • 30. 30 Checking if a value is NaN console.log(isNaN(NaN)); // true console.log(isNaN({})); // true https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
  • 31. 31 Checking if a value is NaN console.log(isNaN(NaN)); // true console.log(isNaN({})); // true https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
  • 32. 32 Checking if a value is precisely NaN console.log(Number.isNaN({})); // false // isNaN(x) = Number.isNaN(Number(x)) console.log(isNaN({})); // true Number.isNaN (ES6) https://developer.mozilla.org/ en-US/docs/Web/JavaScript/ Reference/Global_Objects/Nu mber/isNaN http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan
  • 33. 33 Agenda ● Various JavaScript (and not only JS) quirks ○ Numbers ○ RegExps ○ Variable declarations ○ Operators (void, ||, comma) ○ try … catch ○ Objects ○ Coercion ○ Functions ○ Prototypal inheritance
  • 34. Various JavaScript (and not only JS) quirks RegExps
  • 35. 35 Matching multiple times const pattern = /a+b+/g; const text = 'aabbababaaaaaaabbbbbb' ; while (true) { const match = pattern.exec(text); if (match === null) { break; } console.log(match[0]); }
  • 36. 36 Matching multiple times const pattern = /a+b+/g; const text = 'aabbababaaaaaaabbbbbb' ; while (true) { const match = pattern.exec(text); if (match === null) { break; } console.log(match[0]); }
  • 37. 37 State saved in `lastIndex` const pattern = /a+b+/g; const text = 'aabbababaaaaaaabbbbbb' ; while (true) { const match = pattern.exec(text); if (match === null) { break; } console.log(match[0], pattern.lastIndex); } https://developer.mozilla.org/en-U S/docs/Web/JavaScript/Reference /Global_Objects/RegExp/lastIndex
  • 38. 38 State saved in `lastIndex` const pattern = /a+b+/g; const text = 'aabbababaaaaaaabbbbbb' ; while (true) { const match = pattern.exec(text); if (match === null) { break; } console.log(match[0], pattern.lastIndex); }
  • 39. 39 Change from where matching starts const pattern = /a+b+/gi; const text = 'aabbabABaaaaaaabbbbbb'; // 0123456789 pattern.lastIndex = 5;
  • 40. 40 Change from where matching starts const pattern = /a+b+/gi; const text = 'aabbabABaaaaaaabbbbbb'; // 0123456789 pattern.lastIndex = 5; console.log(pattern.exec(text)[0], pattern.lastIndex); // AB, 8
  • 41. 41 Be careful with the global flag const pattern = /Java/g; const text1 = 'JavaScript is the best programming language'; pattern.exec(text1); const text2 = 'Java is the best programming language'; pattern.exec(text2);
  • 42. 42 Be careful with the global flag const pattern = /Java/g; const text1 = 'JavaScript is the best programming language'; pattern.exec(text1); const text2 = 'Java is the best programming language'; pattern.exec(text2);
  • 43. 43 Agenda ● Various JavaScript (and not only JS) quirks ○ Numbers ○ RegExps ○ Variable declarations ○ Operators (void, ||, comma) ○ try … catch ○ Objects ○ Coercion ○ Functions ○ Prototypal inheritance
  • 44. Various JavaScript (and not only JS) quirks Variable declarations
  • 45. 45 Variable scope - const, let function foo() { if (true) { const a = 1; let b = 2; } console.log(a, b); } foo();
  • 46. 46 Variable scope - const, let function foo() { if (true) { const a = 1; let b = 2; } console.log(a, b); // ReferenceError: a is not defined } foo();
  • 47. 47 Variable scope - var function foo() { if (true) { var a = 10; } console.log(a); } foo();
  • 48. 48 Variable scope - var function foo() { if (true) { var a = 10; } console.log(a); // 10 } foo();
  • 49. 49 Variable scope - var function foo() { if (true) { var a = 10; } console.log(a); // 10 } foo();
  • 50. 50 Hoisting function foo() { console.log(a); var a = 0; console.log(a); } foo();
  • 51. 51 Hoisting function foo() { console.log(a); // undefined var a = 0; console.log(a); // 0 } foo();
  • 52. 52 Hoisting function foo() { console.log(a); // undefined var a = 0; console.log(a); // 0 } foo();
  • 53. 53 Hoisting explained function foo() { var a; console.log(a); a = 0; console.log(a); } foo(); https://developer.mozilla.org/en-US/docs /Glossary/Hoisting function foo() { console.log(a); var a = 0; console.log(a); } foo();
  • 54. 54 Hoisting explained function foo() { var a; console.log(a); // undefined a = 0; console.log(a); // 0 } foo(); https://developer.mozilla.org/en-US/docs /Glossary/Hoisting function foo() { console.log(a); var a = 0; console.log(a); } foo();
  • 55. 55 Do not do this at home function foo() { a = 1; console.log(a); // 1 var a = 0; console.log(a); // 0 } foo();
  • 56. 56 `var` scope var foo = 1; console.log(window.foo);
  • 57. 57 `var` scope var foo = 1; console.log(window.foo); // 1
  • 58. 58 `var` scope var foo = 1; console.log(window.foo); // 1
  • 59. 59 IIFE to the rescue IIFE - Immediately Invoked Function Expression (function() { var bar = 1; console.log(window.bar); // undefined })(); https://developer.mozilla.org/en-US /docs/Glossary/IIFE
  • 60. 60 … or use `let` and `const` const baz = 1; let abc = 2; console.log(window.baz); console.log(window.abc);
  • 61. 61 Agenda ● Various JavaScript (and not only JS) quirks ○ Numbers ○ RegExps ○ Variable declarations ○ Operators (void, ||, comma) ○ try … catch ○ Objects ○ Coercion ○ Functions ○ Prototypal inheritance
  • 62. Various JavaScript (and not only JS) quirks Operators
  • 63. 63 `void` operator console.log(void 0, void true, void undefined, void 'anything'); https://developer.mozilla.org/en-U S/docs/Web/JavaScript/Reference /Operators/void
  • 64. 64 `void` operator console.log(void 0, void true, void undefined, void 'anything'); // undefined, undefined, undefined, undefined https://developer.mozilla.org/en-U S/docs/Web/JavaScript/Reference /Operators/void
  • 65. 65 `void`’s usefulness class Foo { counter = 0; setCounter = x => (this.counter = x); } const foo = new Foo(); console.log(foo.setCounter(50));
  • 66. 66 `void`’s usefulness class Foo { counter = 0; setCounter = x => (this.counter = x); } const foo = new Foo(); console.log(foo.setCounter(50)); // 50
  • 67. 67 `void`’s usefulness class Foo { counter = 0; setCounter = x => (this.counter = x); safeSetCounter = x => { this.counter = x; } } const foo = new Foo(); foo.setCounter(50); foo.safeSetCounter (50);
  • 68. 68 `void`’s usefulness class Foo { counter = 0; setCounter = x => (this.counter = x); safeSetCounter = x => void (this.counter = x); } const foo = new Foo(); foo.setCounter(50); foo.safeSetCounter (50);
  • 69. 69 Overwriting undefined function example1(undefined) { undefined = true; if (undefined) { console.log('Surprised?'); } }
  • 70. 70 Overwriting undefined function example1(undefined) { undefined = true; if (undefined) { console.log('Surprised?'); } }
  • 71. 71 Overwriting undefined function example1(undefined) { undefined = true; if (undefined) { console.log('Surprised?'); } }
  • 72. 72 Restoring undefined with void operator function example3(undefined) { undefined = true; console.log({ undefined }); // { undefined: true } undefined = void 0; console.log({ undefined }); // { undefined: undefined } }
  • 73. 73 Usage in TypeScript compiler TypeScript compiler uses void 0 instead of undefined directly
  • 74. 74 Or (||) operator Operands (and return type) can be boolean...
  • 75. 75 Or (||) operator … but do not have to be Operands (and return type) can be boolean...
  • 77. 77 Or (||) operator - lazy evaluation function getValue() { console.log('This will not run, because 5 is truthy'); return 10; } console.log(5 || getValue()); Operands are evaluated lazily
  • 78. 78 Or (||) operator - default function parameter function foo(arg) { arg = arg || 10; console.log(arg); } foo(1); foo(5); foo(); foo(0);
  • 79. 79 Or (||) operator - default function parameter function foo(arg) { arg = arg || 10; console.log(arg); } foo(1); // 1 foo(5); // 5 foo(); // 10 foo(0);
  • 80. 80 Or (||) operator - default function parameter function foo(arg) { arg = arg || 10; console.log(arg); } foo(1); // 1 foo(5); // 5 foo(); // 10 foo(0); // 10 (?)
  • 81. 81 Or (||) operator - default function parameter function foo(arg) { arg = arg || 10; console.log(arg); } foo(1); // 1 foo(5); // 5 foo(); // 10 foo(0); // 10 (?)
  • 82. 82 A safe way to have default parameters function safeFoo(arg = 10) { console.log(arg); } safeFoo(0); // 0 Introduced in ES6
  • 83. 83 Fun fact - any param can have a default value function safeFoo(arg = 10, arg2) { console.log(arg, arg2); } safeFoo(undefined, 20);
  • 84. 84 Nullish coalescing operator https://github.com/tc39/proposal-nullish-coalescing (stage 4) Similar to ||, but works with null and undefined only function safeFoo2(arg) { arg = arg ?? 10; console.log(arg); } safeFoo2(0);
  • 85. 85 Tuples in JS? const tuple = (1, 2, 3); console.log(tuple);
  • 86. 86 Tuples in JS? const tuple = (1, 2, 3); console.log(tuple); // 3
  • 87. 87 Tuples in JS? const tuple = (1, 2, 3); console.log(tuple); // 3
  • 88. 88 Tuples in JS? const tuple = (1, 2, 3); console.log(tuple); // 3 Similar behavior in other languages, e.g. C, C++
  • 89. 89 Comma operator in C int main() { int x = 10, y = 15; printf("%d", (x, y)); // 15 return 0; }
  • 90. 90 Comma operator const doMultipleThings = (service) => ( service.doA(), service.doB(), service.doC() ); Evaluates the expression on the left, returns the expression on the right const boringDoMultipleThings = (service) => { service.doA(); service.doB(); return service.doC(); }
  • 91. 91 A side note on ASI What happens if you don’t like semicolons? const boringDoMultipleThings = (service) => { service.doA(); return service.doC(); }
  • 92. 92 A side note on ASI What happens if you don’t like semicolons? const boringDoMultipleThings = (service) => { service.doA(); return service.doC(); }
  • 93. 93 A side note on ASI What happens if you do not like semicolons? const boringDoMultipleThings = (service) => { service.doA() return service.doC() }
  • 94. 94 A side note on ASI const boringDoMultipleThings = (service) => { service.doA() return service.doC() } What happens if you don’t like semicolons?
  • 95. 95 A side note on ASI const boringDoMultipleThings = (service) => { service.doA() return service.doC() } boringDoMultipleThings() What happens if you don’t like semicolons?
  • 96. 96 A side note on ASI const boringDoMultipleThings = (service) => { service.doA() return service.doC() } boringDoMultipleThings() Not executed What happens if you don’t like semicolons?
  • 97. 97 A side note on ASI ASI - Automatic Semicolon Insertion const boringDoMultipleThings = (service) => { service.doA() return service.doC() } boringDoMultipleThings() const boringDoMultipleThings = (service) => { service.doA(); return; service.doC(); } boringDoMultipleThings();
  • 98. 98 A side note on ASI ASI - Automatic Semicolon Insertion const boringDoMultipleThings = (service) => { service.doA() return service.doC() } boringDoMultipleThings() const boringDoMultipleThings = (service) => { service.doA(); return; service.doC(); } boringDoMultipleThings(); Use a linter
  • 99. 99 Agenda ● Various JavaScript (and not only JS) quirks ○ Numbers ○ RegExps ○ Variable declarations ○ Operators (void, ||, comma) ○ try … catch ○ Objects ○ Coercion ○ Functions ○ Prototypal inheritance
  • 100. Various JavaScript (and not only JS) quirks try … catch
  • 101. 101 try … finally without catch function throwWithNoReturn() { try { throw new Error(); } finally { } } throwWithNoReturn();
  • 102. 102 try … finally without catch function throwWithNoReturn() { try { throw new Error(); } finally { } } throwWithNoReturn();
  • 103. 103 try … finally - return in finally function throwAndReturnInFinally() { try { throw new Error(); } finally { return 'I will be returned'; } } throwAndReturnInFinally();
  • 104. 104 try … finally - return in finally function throwAndReturnInFinally() { try { throw new Error(); } finally { return 'I will be returned'; } } throwAndReturnInFinally();
  • 105. 105 try … finally - return in finally function throwAndReturnInFinally() { try { throw new Error(); } finally { return 'I will be returned'; } } throwAndReturnInFinally(); Where is the error?
  • 106. 106 try … finally - returning function returnsInTryAndFinally() { try { return 'I want to be returned'; } finally { return "No, you won't"; } } returnsInTryAndFinally();
  • 107. 107 try … finally - returning function returnsInTryAndFinally() { try { return 'I want to be returned'; } finally { return "No, you won't"; } } returnsInTryAndFinally();
  • 108. 108 try … finally - returning function returnsInTryAndFinally() { try { return 'I want to be returned'; } finally { return "No, you won't"; } } returnsInTryAndFinally();
  • 109. 109 Agenda ● Various JavaScript (and not only JS) quirks ○ Numbers ○ RegExps ○ Variable declarations ○ Operators (void, ||, comma) ○ try … catch ○ Objects ○ Coercion ○ Functions ○ Prototypal inheritance
  • 110. Various JavaScript (and not only JS) quirks Objects
  • 112. 112 Type of null console.log(typeof null); // 'object'
  • 113. 113 Type of null console.log(typeof null); // 'object'
  • 114. 114 Type of null - explanation https://v8.dev/blog/react-cliff Similar to NaN for numbers Source: v8.dev/blog/react-cliff
  • 115. 115 toJSON with JSON.stringify const obj = { a: 1, b: 2, toJSON: function() { return 'definitely not an object'; } }; console.log(JSON.stringify(obj));
  • 116. 116 toJSON with JSON.stringify const obj = { a: 1, b: 2, toJSON: function() { return 'definitely not an object'; } }; console.log(JSON.stringify(obj));
  • 117. 117 toJSON with JSON.stringify const obj = { a: 1, b: 2, toJSON: function() { return 'definitely not an object'; } }; console.log(JSON.stringify(obj));
  • 118. 118 Agenda ● Various JavaScript (and not only JS) quirks ○ Numbers ○ RegExps ○ Variable declarations ○ Operators (void, ||, comma) ○ try … catch ○ Objects ○ Coercion ○ Functions ○ Prototypal inheritance
  • 119. Various JavaScript (and not only JS) quirks Coercion
  • 120. 120 Objects and == (for numbers) console.log(foo == 1); console.log(foo == 2); console.log(foo == 3); console.log(Number(foo)); console.log(Number(foo));
  • 121. 121 Objects and == (for numbers) const foo = { counter: 0, valueOf: function() { return ++this.counter; } }; console.log(foo == 1); console.log(foo == 2); console.log(foo == 3); console.log(Number(foo)); console.log(Number(foo));
  • 122. 122 Agenda ● Various JavaScript (and not only JS) quirks ○ Numbers ○ RegExps ○ Variable declarations ○ Operators (void, ||, comma) ○ try … catch ○ Objects ○ Coercion ○ Functions ○ Prototypal inheritance
  • 123. Various JavaScript (and not only JS) quirks Functions
  • 124. 124 Variadic functions Variadic - take an arbitrary number of arguments (e.g. console.log) sum(1, 2); // 3 sum(1, 2, 3, 4, 5, 6, 7); // 28
  • 125. 125 Variadic functions in ES6 (rest syntax) function es6Sum(...args) { return args.reduce((sum, x) => sum + x, 0); }
  • 126. 126 Variadic functions in ES5 function es5Sum() { let result = 0; for (let i = 0; i < arguments.length; i++) { result += arguments[i]; } return result; }
  • 127. 127 arguments - not a valid array function invalidUse() { arguments.forEach(x => { // ... }); }
  • 128. 128 arguments + Array.from = <3 function invalidUse() { Array.from(arguments).forEach(x => { // ... }); }
  • 129. 129 Agenda ● Various JavaScript (and not only JS) quirks ○ Numbers ○ RegExps ○ Variable declarations ○ Operators (void, ||, comma) ○ try … catch ○ Objects ○ Coercion ○ Functions ○ Prototypal inheritance
  • 130. Various JavaScript (and not only JS) quirks Prototypal inheritance
  • 131. 131 “Inheritance” in JavaScript ● Prototypal inheritance (not classical inheritance) ● Each object has a [[Prototype]] (another object or null) ● Prototype chain - multiple objects connected via prototype ● During property lookup, either: ○ Property exists on the object itself ○ The prototype chain is traversed to find the property ● Can be confusing for programmers of other languages ● Dynamic - can be manipulated at runtime Animal.prototype Object.prototype null cat dog
  • 132. 132 Custom merge function merge(dest, src) { for (let property in src) { if ( typeof dest[property] === 'object' && typeof src[property] === 'object' ) { merge(dest[property], src[property]); } else { dest[property] = src[property]; } } }
  • 133. 133 Custom merge - happy scenario const options = { // default options fetchNestedData: true, pageSize: 10 }; const additionalOptions = JSON.parse( '{ "fetchNestedData": false }' ); merge(options, additionalOptions );
  • 134. 134 Custom merge - prototype pollution const options = { fetchNestedData: true, pageSize: 10 }; const additionalOptions = JSON.parse('{ "__proto__": { "isAdmin": true }}'); merge(options, additionalOptions);
  • 135. 135 Custom merge - prototype pollution const options = { fetchNestedData: true, pageSize: 10 }; const additionalOptions = JSON.parse('{ "__proto__": { "isAdmin": true }}'); merge(options, additionalOptions);
  • 136. 136 Custom merge - prototype pollution const options = { fetchNestedData: true, pageSize: 10 }; const additionalOptions = JSON.parse('{ "__proto__": { "isAdmin": true }}'); merge(options, additionalOptions); More information: https://codeburst.io/what-is-prototype-pollution-49482fc4b638 https://snyk.io/vuln/SNYK-JS-LODASH-450202
  • 137. 137 Monkey patching console.log('test before patching' ); const originalLog = console.log; console.log = function(...args) { return originalLog.call(this, 'patched log', ...args); }; console.log('test after patching' );
  • 138. 138 Monkey patching console.log('test before patching' ); const originalLog = console.log; console.log = function(...args) { return originalLog.call(this, 'patched log', ...args); }; console.log('test after patching' );
  • 139. 139 Monkey patching - polyfilling Array.prototype.flat = function() { return this.reduce((arr, element) => arr.concat(element), []); }; [1, [2], [3]].flat();
  • 140. 140 Monkey patching - polyfilling Array.prototype.flat = function() { return this.reduce((arr, element) => arr.concat(element), []); }; [1, [2], [3]].flat(); Careful MooTools monkey-patched Array.prototype.flatten https://mootools.net/core/docs/1.5.2/Types/Array#Array:flatten https://github.com/mootools/mootools-core/blob/master/Source/Types/Array.js #L132-L140 Result: https://developers.google.com/web/updates/2018/03/smooshgate
  • 141. 141 Shortening property access Source: https://www.omnicalculator.com/math/law-of-cosines function calculateSideLength (a, b, alpha) { return Math.sqrt( Math.pow(a, 2) + Math.pow(b, 2) - 2 * a * b * Math.cos(alpha) ); }
  • 142. 142 with statement Source: https://www.omnicalculator.com/math/law-of-cosines function calculateSideLength2 (a, b, alpha) { with (Math) { return sqrt(pow(a, 2) + pow(b, 2) - 2 * a * b * cos(alpha)); } }
  • 143. 143 with statement function extractValuesFromSubarrays (array, indexOf) { with (array) { return map(subArray => subArray[indexOf]); } } const array = [[1, 2, 3], [4, 5]]; extractValuesFromSubarrays (array, 1); // [2, 5] ?
  • 144. 144 with statement function extractValuesFromSubarrays (array, indexOf) { with (array) { return map(subArray => subArray[indexOf]); } } const array = [[1, 2, 3], [4, 5]]; extractValuesFromSubarrays (array, 1); // [undefined, undefined]
  • 145. 145 with statement function extractValuesFromSubarrays (array, indexOf) { with (array) { return map(subArray => subArray[indexOf]); } } const array = [[1, 2, 3], [4, 5]]; extractValuesFromSubarrays (array, 1); // [undefined, undefined] Array.prototype.indexOf, not the indexOf parameter
  • 146. 146 with statement ● Cannot be optimized by the compiler (depends on the runtime value) ● Not recommended ● Will throw an error in strict mode More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Sta tements/with
  • 147. 147 with statement function extractValuesFromSubarrays (array, find) { with (array) { return map(subArray => subArray[find]); } } const array = [[1, 2, 3], [4, 5]]; extractValuesFromSubarrays (array, 1);
  • 148. 148 with statement function extractValuesFromSubarrays (array, find) { with (array) { return map(subArray => subArray[find]); } } const array = [[1, 2, 3], [4, 5]]; extractValuesFromSubarrays (array, 1);
  • 149. 149 with statement function extractValuesFromSubarrays (array, find) { with (array) { return map(subArray => subArray[find]); } } const array = [[1, 2, 3], [4, 5]]; extractValuesFromSubarrays (array, 1);
  • 150. 150 with + Symbol.unscopables https://developer.mozilla.org/en-U S/docs/Web/JavaScript/Reference /Global_Objects/Symbol/unscopabl es Symbol.unscopables - points to an object with property names that should not be scoped by the with statement Introduced in ES6
  • 151. 151 with + Symbol.unscopables https://developer.mozilla.org/en-U S/docs/Web/JavaScript/Reference /Global_Objects/Symbol/unscopabl es find is not scoped, but indexOf is Symbol.unscopables - points to an object with property names that should not be scoped by the with statement Introduced in ES6
  • 152. 152 Other fun symbols Well-known symbols: ● Symbol.iterator (used by for...of) ● Symbol.asyncIterator (used by for await...of) ● Symbol.hasInstance (used by instanceof) ● Symbol.toPrimitive https://developer.mozilla.org/en-US/docs/Web/JavaScript /Reference/Global_Objects/Symbol Introduced in ES6
  • 154. 154 Summary ● Not all quirks are JavaScript-only (comma operator, IEEE 754) ● New features make it easier to avoid pitfalls (arrow functions, const, let) ● Some features are very different than in other languages (prototypal inheritance), so watch out
  • 155. Thank you Krancowa 5 02-493, Warsaw Poland +48 22 389 51 00 contact@codilime.com