SlideShare a Scribd company logo
1 of 47
Download to read offline
!// The hidden and new parts of JS
@ritz078
let/const
function varTest() {
var x = 1;
if (true) {
var x = 2; !// same variable!
console.log(x); !// 2
}
console.log(x); !// 2
}
function letTest() {
let x = 1;
if (true) {
let x = 2; !// different variable
console.log(x); !// 2
}
console.log(x); !// 1
}
Scope
letvar
!// SyntaxError: Missing initializer in const declaration
const a;
const
const b = [1, 2, 3];
!// Modification without changing reference allowed.
b.push(4); !// b = [1, 2, 3, 4]
!// throws an error. reassigning not allowed.
b = [2, 3];
console.log(a); !// undefined
var a = 5;
console.log(b); !// ReferenceError: b is not defined
const b = 5;
console.log(c); !// ReferenceError: c is not defined
let c = 5;
Hoisting
https://stackoverflow.com/a/31222689/3366126
{
"plugins": [
["transform-es2015-block-scoping", {"tdz": true}]
]
}
for (var i = 0; i < 10; i!++) {
setTimeout(function() {
console.log(i)
}, 5)
}
var i;
for (i = 0; i < 10; i!++) {
setTimeout(function() {
console.log(i)
}, 5)
}
!// 10 is printed 10 times.
😢
for (let i = 0; i < 10; i!++) {
setTimeout(function() {
console.log(i)
}, 5)
}
!// Prints number from 1 to 10
🤔 Why ?
!// A closure is created.
!// Now i is a value and not
!// a reference.
var _loop = function _loop(i) {
setTimeout(function () {
console.log(i);
}, 5);
};
for (var i = 0; i < 10; i!++) {
_loop(i);
}
for (let i = 0; i < 10; i!++) {
setTimeout(function() {
console.log(i)
}, 5)
}
!// Prints number from 1 to 10
😌
{
"plugins": [
["transform-es2015-block-scoping", {
"throwIfClosureRequired": true
}]
]
}
Array
Array.isArray(Array.prototype); !// true
.sort( )
const arr = [10, 3, 100]
const sortedArray = arr.sort();
!// it doesn't correctly sort an array of numbers. 🤔
console.log(sortedArray) !// [10, 100, 3]
!// also sorting changes the original array
console.log(arr) !// [10, 100, 3]
The default sort order is according to string Unicode code points.
const arr = [10, 3, 100]
!// passing a comparator function
const sortedArray = arr.sort((a, b) !=> a - b);
console.log(sortedArray) !// [3, 10 100]
~N !!=== -(N + 1)
Tilde (~)
!// equivalent to someStr.indexOf("a") !>= 0
if (~someStr.indexOf("a")) {
    !// Found it
} else {
    !// Not Found
}
.includes ()
const arr = [1, 2, 3, NaN];
arr.includes(3) !// true
!// uses same value zero comparison
!// just like map and set.
arr.includes(NaN) !// true
!// uses Strict Equality Comparison "!!==="
arr.indexOf(NaN) !// -1
Array-like objects
!// !|> Indexed access to elements
!// !|> Has length property
!// !|> Does not have array methods such as push, 
!// forEach and indexOf
const arrayLikeObject = {
0: "hello",
1: "world",
length: 2
}
console.log(arrayLikeObject[1]) !// hello
!// throws error
console.log(arrayLikeObject.indexOf("hello"))
!// Arguments are array like objects
function a () {
console.log(Array.isArray(arguments)) !// false
console.log(arguments[0]) !// 1
console.log(arguments.length) !// 3
}
a(1, 2, 3)
!// elements is a HTMLCollection
!// They are array like objects
const elements = document.getElementsByTagName("div")
console.log(Array.isArray(elements)) !// false
Converting array like objects to an array
!// Can convert array like objects and string into
!// an array.
Array.from(arguments);
!// Borrowing a method from Array
Array.prototype.slice.call(arguments);
!// Node treats arguments and array like objects differently.
!// Anyways, you shouldn't be spreading arguments, it's going
!// to cause an engine to deoptimize the entire function.
!// https:!//github.com/petkaantonov/bluebird/wiki/Optimization-
killers#3-managing-arguments
[!!...arguments]
Object
length
!// array-like-object
const a = {
0: 1,
1: 2,
2: 3,
length: 3
}
console.log(Object.keys(a))
!// ["0", "1", "2", "length"]
function a () {
arguments.length !// 3
Object.keys(arguments)
!// ["0", "1", “2"]
}
a(1,2,3)
no length
.defineProperty()
const a = {
0: 1,
1: 2,
2: 3
}
Object.defineProperty(a, "length", {
enumerable: false,
writable: true, !// can value be modified ?
configurable: true, !// can property be deleted ?
value: 3
})
console.log(a.length) !// 3
console.log(Object.keys(a)) !// ["0", "1", "2"]
Function
function sum (a, b, c) {
!// the number of arguments actually passed.
console.log(arguments.length) !// 2
return a + b + c;
}
sum(1, 2)
!// the number of arguments that the function accepts.
console.log(sum.length) !// 3
.length ()
function sum (a, b, c=3) {
return a + b + c;
}
sum(1, 2)
!// the number of arguments that the function accepts.
console.log(sum.length) !// ?
Gotcha
!// There is no c here. Now sum.length makes better sense. 😀
function sum(a, b) {
var c = arguments.length > 2 !&& arguments[2] !!!== undefined ?
arguments[2] : 3;
return a + b + c;
}
sum(1, 2)
console.log(sum.length) !// 2
Dependency Injection
var app = angular.module('myApp', []);
!// works as expected
app.controller('myCtrl', function($scope, $timeout) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
!// works as expected
app.controller('myCtrl', function($timeout, $scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
In this case, position of argument doesn’t matter but name does.
🤔
function a($scope, $timeout) {
!// your code here
}
const code = a.toString()
!// "function a($scope, $timeout) {
!// !// your logic here
!// }"
const match = code
.match(/^functions{0,}[a-zA-Zd_]{0,}(([^)]+))/)[1];
console.log(match.split(", ")) !// ["$scope", "$timeout"]
.toString()
If the argument name changes after minification, this fails.
async/await
async function () {
let response = await fetch("https:!//random-api/v1");
let user = await response.json();
return user;
}
!// syntax error in top-level code
let response = await fetch("https:!//random-api/v1");
let user = await response.json();
class Thenable {
constructor (num) {
this.num = num;
}
then (resolve, reject) {
setTimeout(() !=> resolve(this.num * 2), 1000);
}
}
async function () {
let result = await new Thenable(2)
alert(result)
}
a()
const data = [
fetch("/a"),
fetch("/b"),
fetch("/c")
]
for await (const x of data) {
console.log(x)
}
ES2018: async-for-of
Async for-of statements are only allowed within async functions and
async generator functions.
new Map ()
> const map = new Map();
> map.set('foo', 123);
> map.get('foo') !// 123
> map.has('foo') !// true
> map.delete('foo') !// true
> map.has('foo') !// false
> map.size !// 1
> map.clear()
length is for data structures that are indexable – like arrays. 
size is for collections that are unordered like maps and sets.
!// Any value can be a key.
const KEY1 = {};
map.set(KEY1, 'hello');
console.log(map.get(KEY1)); !// hello
const KEY2 = {};
map.set(KEY2, 'world');
console.log(map.get(KEY2)); !// world
Object vs Map
Object vs Map
const map = new Map ();
!// typeof keys is preserved
map.set(1, "hello")
console.log([!!...map.keys()]) !// [1]
const obj = {}
!// typeof keys is string
obj[1] = "world"
console.log(Object.keys(obj)) !// ["1"]
Object vs Map
!// Map
const map = new Map ();
!// Doesn't override prototype methods
map.set("get", "world")
console.log(map.get) !// function get() { [native code] }
!// Object
const obj = {}
!// overrides prototype methods
obj['toString'] = "override"
console.log(obj.toString) !// "override"
new Set ()
Array vs Set
const arr = [1, 2, "3", 3, 3];
const set = new Set(arr);
!// O(1) lookup
set.has(3)
!// only unique values are present.
!// They are unique by both type
!// and value.
set.size !// 4
Array.from(set.values())
!// [1, 2, "3", 3]
const arr = [1, 2, "3", 3, 3];
!// O(n) lookup
arr.indexOf(3)
!// all elements preserved
arr.length !// 5
ES2018
Rest operator in object destructuring
const obj = {foo: 1, bar: 2, baz: 3};
const {foo, !!...rest} = obj;
!// Same as:
!// const foo = 1;
!// const rest = {bar: 2, baz: 3};
RegExp capture groups
const RE_DATE = /(?<year>[0-9]{4})-(?<month>[0-9]
{2})-(?<day>[0-9]{2})/;
const matchObj = RE_DATE.exec('1999-12-31');
const year = matchObj.groups.year; !// 1999
const month = matchObj.groups.month; !// 12
const day = matchObj.groups.day; !// 31
promise
.then(result !=> {···})
.catch(error !=> {···})
.finally(() !=> {···});
Promise.prototype.finally()
Thank You
@ritz078

More Related Content

What's hot

Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...Zyxware Technologies
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generatorsRamesh Nair
 
Short intro to ES6 Features
Short intro to ES6 FeaturesShort intro to ES6 Features
Short intro to ES6 FeaturesNaing Lin Aung
 
Workshop on command line tools - day 2
Workshop on command line tools - day 2Workshop on command line tools - day 2
Workshop on command line tools - day 2Leandro Lima
 
Nouveau document texte
Nouveau document texteNouveau document texte
Nouveau document texteSai Ef
 
Yy
YyYy
Yyyygh
 
Cis 216 – shell scripting
Cis 216 – shell scriptingCis 216 – shell scripting
Cis 216 – shell scriptingDan Morrill
 
Workshop on command line tools - day 1
Workshop on command line tools - day 1Workshop on command line tools - day 1
Workshop on command line tools - day 1Leandro Lima
 
Process monitoring in UNIX shell scripting
Process monitoring in UNIX shell scriptingProcess monitoring in UNIX shell scripting
Process monitoring in UNIX shell scriptingDan Morrill
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python TricksBryan Helmig
 
ECMAScript 6 new features
ECMAScript 6 new featuresECMAScript 6 new features
ECMAScript 6 new featuresGephenSG
 
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveThe Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveEleanor McHugh
 
Ignite es6
Ignite es6Ignite es6
Ignite es6jstack
 
"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014Henning Jacobs
 

What's hot (20)

Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 redux
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generators
 
Short intro to ES6 Features
Short intro to ES6 FeaturesShort intro to ES6 Features
Short intro to ES6 Features
 
Workshop on command line tools - day 2
Workshop on command line tools - day 2Workshop on command line tools - day 2
Workshop on command line tools - day 2
 
Nouveau document texte
Nouveau document texteNouveau document texte
Nouveau document texte
 
Yy
YyYy
Yy
 
Cis 216 – shell scripting
Cis 216 – shell scriptingCis 216 – shell scripting
Cis 216 – shell scripting
 
Workshop on command line tools - day 1
Workshop on command line tools - day 1Workshop on command line tools - day 1
Workshop on command line tools - day 1
 
Php&redis presentation
Php&redis presentationPhp&redis presentation
Php&redis presentation
 
Process monitoring in UNIX shell scripting
Process monitoring in UNIX shell scriptingProcess monitoring in UNIX shell scripting
Process monitoring in UNIX shell scripting
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python Tricks
 
ECMAScript 6 new features
ECMAScript 6 new featuresECMAScript 6 new features
ECMAScript 6 new features
 
C99.php
C99.phpC99.php
C99.php
 
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveThe Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's Perspective
 
Ignite es6
Ignite es6Ignite es6
Ignite es6
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014
 
C99
C99C99
C99
 
Cod
CodCod
Cod
 

Similar to The hidden and new parts of JS

Coscup2021-rust-toturial
Coscup2021-rust-toturialCoscup2021-rust-toturial
Coscup2021-rust-toturialWayne Tsai
 
Swift - the future of iOS app development
Swift - the future of iOS app developmentSwift - the future of iOS app development
Swift - the future of iOS app developmentopenak
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoThe Software House
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to ScalaTim Underwood
 
golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdfSpam92
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinAndrey Breslav
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)David Atchley
 
write the TODO part of the program.docx
write the TODO part of the program.docxwrite the TODO part of the program.docx
write the TODO part of the program.docxannetnash8266
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is hereSebastiano Armeli
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1Ke Wei Louis
 

Similar to The hidden and new parts of JS (20)

Javascript
JavascriptJavascript
Javascript
 
ES6: The future is now
ES6: The future is nowES6: The future is now
ES6: The future is now
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
Coscup2021-rust-toturial
Coscup2021-rust-toturialCoscup2021-rust-toturial
Coscup2021-rust-toturial
 
Swift - the future of iOS app development
Swift - the future of iOS app developmentSwift - the future of iOS app development
Swift - the future of iOS app development
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdf
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in Kotlin
 
Scope and closures
Scope and closuresScope and closures
Scope and closures
 
Internal workshop es6_2015
Internal workshop es6_2015Internal workshop es6_2015
Internal workshop es6_2015
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Es6 to es5
Es6 to es5Es6 to es5
Es6 to es5
 
write the TODO part of the program.docx
write the TODO part of the program.docxwrite the TODO part of the program.docx
write the TODO part of the program.docx
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
 

Recently uploaded

Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 

Recently uploaded (20)

Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 

The hidden and new parts of JS

  • 1. !// The hidden and new parts of JS @ritz078
  • 3. function varTest() { var x = 1; if (true) { var x = 2; !// same variable! console.log(x); !// 2 } console.log(x); !// 2 } function letTest() { let x = 1; if (true) { let x = 2; !// different variable console.log(x); !// 2 } console.log(x); !// 1 } Scope letvar
  • 4. !// SyntaxError: Missing initializer in const declaration const a; const const b = [1, 2, 3]; !// Modification without changing reference allowed. b.push(4); !// b = [1, 2, 3, 4] !// throws an error. reassigning not allowed. b = [2, 3];
  • 5. console.log(a); !// undefined var a = 5; console.log(b); !// ReferenceError: b is not defined const b = 5; console.log(c); !// ReferenceError: c is not defined let c = 5; Hoisting https://stackoverflow.com/a/31222689/3366126
  • 7. for (var i = 0; i < 10; i!++) { setTimeout(function() { console.log(i) }, 5) } var i; for (i = 0; i < 10; i!++) { setTimeout(function() { console.log(i) }, 5) } !// 10 is printed 10 times. 😢
  • 8. for (let i = 0; i < 10; i!++) { setTimeout(function() { console.log(i) }, 5) } !// Prints number from 1 to 10 🤔 Why ?
  • 9. !// A closure is created. !// Now i is a value and not !// a reference. var _loop = function _loop(i) { setTimeout(function () { console.log(i); }, 5); }; for (var i = 0; i < 10; i!++) { _loop(i); } for (let i = 0; i < 10; i!++) { setTimeout(function() { console.log(i) }, 5) } !// Prints number from 1 to 10 😌
  • 11. Array
  • 13. .sort( ) const arr = [10, 3, 100] const sortedArray = arr.sort(); !// it doesn't correctly sort an array of numbers. 🤔 console.log(sortedArray) !// [10, 100, 3] !// also sorting changes the original array console.log(arr) !// [10, 100, 3] The default sort order is according to string Unicode code points.
  • 14. const arr = [10, 3, 100] !// passing a comparator function const sortedArray = arr.sort((a, b) !=> a - b); console.log(sortedArray) !// [3, 10 100]
  • 15. ~N !!=== -(N + 1) Tilde (~) !// equivalent to someStr.indexOf("a") !>= 0 if (~someStr.indexOf("a")) {     !// Found it } else {     !// Not Found }
  • 16. .includes () const arr = [1, 2, 3, NaN]; arr.includes(3) !// true !// uses same value zero comparison !// just like map and set. arr.includes(NaN) !// true !// uses Strict Equality Comparison "!!===" arr.indexOf(NaN) !// -1
  • 18. !// !|> Indexed access to elements !// !|> Has length property !// !|> Does not have array methods such as push,  !// forEach and indexOf const arrayLikeObject = { 0: "hello", 1: "world", length: 2 } console.log(arrayLikeObject[1]) !// hello !// throws error console.log(arrayLikeObject.indexOf("hello"))
  • 19. !// Arguments are array like objects function a () { console.log(Array.isArray(arguments)) !// false console.log(arguments[0]) !// 1 console.log(arguments.length) !// 3 } a(1, 2, 3)
  • 20. !// elements is a HTMLCollection !// They are array like objects const elements = document.getElementsByTagName("div") console.log(Array.isArray(elements)) !// false
  • 21. Converting array like objects to an array !// Can convert array like objects and string into !// an array. Array.from(arguments); !// Borrowing a method from Array Array.prototype.slice.call(arguments); !// Node treats arguments and array like objects differently. !// Anyways, you shouldn't be spreading arguments, it's going !// to cause an engine to deoptimize the entire function. !// https:!//github.com/petkaantonov/bluebird/wiki/Optimization- killers#3-managing-arguments [!!...arguments]
  • 23. length !// array-like-object const a = { 0: 1, 1: 2, 2: 3, length: 3 } console.log(Object.keys(a)) !// ["0", "1", "2", "length"]
  • 24. function a () { arguments.length !// 3 Object.keys(arguments) !// ["0", "1", “2"] } a(1,2,3) no length
  • 25. .defineProperty() const a = { 0: 1, 1: 2, 2: 3 } Object.defineProperty(a, "length", { enumerable: false, writable: true, !// can value be modified ? configurable: true, !// can property be deleted ? value: 3 }) console.log(a.length) !// 3 console.log(Object.keys(a)) !// ["0", "1", "2"]
  • 27. function sum (a, b, c) { !// the number of arguments actually passed. console.log(arguments.length) !// 2 return a + b + c; } sum(1, 2) !// the number of arguments that the function accepts. console.log(sum.length) !// 3 .length ()
  • 28. function sum (a, b, c=3) { return a + b + c; } sum(1, 2) !// the number of arguments that the function accepts. console.log(sum.length) !// ? Gotcha
  • 29. !// There is no c here. Now sum.length makes better sense. 😀 function sum(a, b) { var c = arguments.length > 2 !&& arguments[2] !!!== undefined ? arguments[2] : 3; return a + b + c; } sum(1, 2) console.log(sum.length) !// 2
  • 30. Dependency Injection var app = angular.module('myApp', []); !// works as expected app.controller('myCtrl', function($scope, $timeout) { $scope.firstName = "John"; $scope.lastName = "Doe"; }); !// works as expected app.controller('myCtrl', function($timeout, $scope) { $scope.firstName = "John"; $scope.lastName = "Doe"; }); In this case, position of argument doesn’t matter but name does. 🤔
  • 31. function a($scope, $timeout) { !// your code here } const code = a.toString() !// "function a($scope, $timeout) { !// !// your logic here !// }" const match = code .match(/^functions{0,}[a-zA-Zd_]{0,}(([^)]+))/)[1]; console.log(match.split(", ")) !// ["$scope", "$timeout"] .toString() If the argument name changes after minification, this fails.
  • 33. async function () { let response = await fetch("https:!//random-api/v1"); let user = await response.json(); return user; } !// syntax error in top-level code let response = await fetch("https:!//random-api/v1"); let user = await response.json();
  • 34. class Thenable { constructor (num) { this.num = num; } then (resolve, reject) { setTimeout(() !=> resolve(this.num * 2), 1000); } } async function () { let result = await new Thenable(2) alert(result) } a()
  • 35. const data = [ fetch("/a"), fetch("/b"), fetch("/c") ] for await (const x of data) { console.log(x) } ES2018: async-for-of Async for-of statements are only allowed within async functions and async generator functions.
  • 37. > const map = new Map(); > map.set('foo', 123); > map.get('foo') !// 123 > map.has('foo') !// true > map.delete('foo') !// true > map.has('foo') !// false > map.size !// 1 > map.clear() length is for data structures that are indexable – like arrays.  size is for collections that are unordered like maps and sets.
  • 38. !// Any value can be a key. const KEY1 = {}; map.set(KEY1, 'hello'); console.log(map.get(KEY1)); !// hello const KEY2 = {}; map.set(KEY2, 'world'); console.log(map.get(KEY2)); !// world Object vs Map
  • 39. Object vs Map const map = new Map (); !// typeof keys is preserved map.set(1, "hello") console.log([!!...map.keys()]) !// [1] const obj = {} !// typeof keys is string obj[1] = "world" console.log(Object.keys(obj)) !// ["1"]
  • 40. Object vs Map !// Map const map = new Map (); !// Doesn't override prototype methods map.set("get", "world") console.log(map.get) !// function get() { [native code] } !// Object const obj = {} !// overrides prototype methods obj['toString'] = "override" console.log(obj.toString) !// "override"
  • 42. Array vs Set const arr = [1, 2, "3", 3, 3]; const set = new Set(arr); !// O(1) lookup set.has(3) !// only unique values are present. !// They are unique by both type !// and value. set.size !// 4 Array.from(set.values()) !// [1, 2, "3", 3] const arr = [1, 2, "3", 3, 3]; !// O(n) lookup arr.indexOf(3) !// all elements preserved arr.length !// 5
  • 44. Rest operator in object destructuring const obj = {foo: 1, bar: 2, baz: 3}; const {foo, !!...rest} = obj; !// Same as: !// const foo = 1; !// const rest = {bar: 2, baz: 3};
  • 45. RegExp capture groups const RE_DATE = /(?<year>[0-9]{4})-(?<month>[0-9] {2})-(?<day>[0-9]{2})/; const matchObj = RE_DATE.exec('1999-12-31'); const year = matchObj.groups.year; !// 1999 const month = matchObj.groups.month; !// 12 const day = matchObj.groups.day; !// 31
  • 46. promise .then(result !=> {···}) .catch(error !=> {···}) .finally(() !=> {···}); Promise.prototype.finally()