JavaScript
JavaScript
2022/06/29 (增加連結)
JavaScript basics
JavaScript雖然有個Java,可是在很多方面與Java都不一樣,例如:變數的使用方式,JavaScript是動態資料型態,也就是同一個變數的資料型態可以是不一樣的。
The Websites I Use to Learn Modern JavaScript
The Mozilla Developer Network
Honorable mentions
Top 5 Github Repositories Every Web Developer Should Know
JavaScript Algorithms and Data Structures
List of (Advanced) JavaScript Questions
List of Free Learning Resources
Awesome
Clean Code in JavaScript
Over 20 Resources to Advance Your JavaScript Skills
Courses
Advanced JavaScript from Tyler McGinnis ($40/month)
Advanced JavaScript Concepts from Andrei Neagoie (on Udemy NT$4,290)
JavaScript Visualized from Lydia Hallie
JavaScript: the Hard Parts from Will Sentance ($39/month)
JavaScript Core Concepts You Should Not Skip
Dynamic Type
Primitive Types
Variable declaration — var, let, and const
Function Declaration and Function Expression
JavaScript for absolute beginners
Values
Variables
Arithmetic
Data Structures
Equality
Conditionals
Functions
7 JavaScript Fundamentals Every Web Developer Should Know **
Functions Are Independent Units of Behavior
Objects Are Dynamic Collections of Props
Objects Inherit From Other Objects
Functions Are Values
Functions Can Become Closures
Primitives Are Treated as Objects
JavaScript Is a Single-Threaded Language
14 Fundamental JavaScript Concepts Explained Simply
Code Structure
“use strict”
variables
data types
type conversion
operators
comparisons
alert, prompt, confirm
conditionals
loops
switch statements
functions
function expressions
arrow functions
10 JavaScript Cheat Sheets That Will Boost Your Productivity
Why You Should Learn JavaScript Principles First (Not the Hottest Frameworks)
JavaScript Engine, Execution Context, and Call Stack
Scope
Closures
An array list of more JavaScript core concepts
You should be able to understand how JavaScript engine treats asynchrony since, as you know, JS is a singled-thread programming language. In addition, other core concepts we need to be familiar with and confident of include prototype, inheritance, callbacks, promises, functional programming concepts, and function composition.
How Does JavaScript Actually Work Under the Hood? : An overview of the JavaScript engine, event loop, callback queue, and Web APIs.
3 Foundational JavaScript Ideas You Need to Upgrade to Pro Status
Scope
There are two types of scopes — a local scope and a global scope.
Quick notes on let and var
let is only available inside the scope where it’s declared. var defines a variable globally, or locally to an entire function regardless of block scope.
Where you declare matters
The Conditionals
if else statements can be fun and easy to write — until they get a bit out of hand.
Switch
Loops
There are five different kinds of loops — for, for/in, for/of, while, and do/while.
Promises
Learn these JavaScript fundamentals and become a better developer
Primitives
Objects
Variables
Array
Functions
Dynamic Typing
A Single Thread
Exceptions
Prototype Patterns
Functional Patterns
JavaScript Features You Probably Haven’t Used
Tagged Template Literals
Comma Operator
with
in
Let / Const
避免使用var
Template literals
Arrow functions
Default parameters
Property shorthands
ES6 Pop Quiz: Shorthand Method & Property Names
Concise Methods / concise objects
Quick ES6 Development Guide — Part 1: Scoping, looping, data structures, and more
The Eight Best JavaScript Features of the Last Four Years (ES2018-ES2021)
Events
What’s the difference between Event Handlers & addEventListener in JS?
For a given element, you can only have one event handler per event type, but you can have multiple event listeners.
Events: Your First Lesson in JavaScript
Three rules of JavaScript syntax
Code statements
Comments
Blocks and functions
Connecting an event
An embarrassingly simple event example
Playing with JavaScript Events
Events: The big picture
Six essential JavaScript events
onclick
onload
oninput
mouseenter
mouseleave
mousemove
Playing in “The Basement”
Using Event Handlers in JavaScript
Event Handling
Inline Event Handlers
Handling Events in Script Tag
addEventListener
Stop Event Propagation
A modern guide to Events in JavaScript
Event propagation
How to stop events from propagating?
Dispatching events manually
When we might want to use custom events?
JavaScript Event Delegation Explained
Background Knowledge: Event Capturing & Bubbling
Event Delegation
Explanation
You Need To Understand Event Bubbling and Capturing in JavaScript
Functions of JavaScript Event Listener : Learn the basic concepts and methods of addEventListener() in JavaScript.
Matt’s Lambda Minute: An Intro to JavaScript Variables, Objects, and Arrays
Stop Making These 5 Javascript Style Mistakes
Using Array Destructuring For Functions With Multiple Return Values
Instead, we can use object destructuring. **文章的回應認為不一定都要使用object destructuring
Not Using Object Destructuring For Function Parameters
Copying Arrays Without Using the Spread Operator
Using Var
Using const guarantees a variable cannot be reassigned. This reduces bugs in our code and makes it easier to understand.
If you really need to reassign a variable, always prefer let over var .
Not Using Template Literals
More JavaScript Mistakes — Objects, Async Code, and Event Listeners
Confusing Object Keys and Array Indexes
Not Understanding Asynchronous Code
Adding Too Many Event Listeners
Good Parts of JavaScript — Arrays
Array Literals
Length
Delete
Enumeration
Good Parts of JavaScript — Currying, Memoization, and Inheritance
範例裡有些語法上的錯誤
Refactoring JavaScript — 5 Common Problems to Look Out for and How to Fix Them
Magic values
Abusing primitive values
Duplicated code
Callback hell or unending promise chains
Spread responsibility
JavaScript Best Practices for Readable and Maintainable Code
JavaScript Best Practices — Browser Differences, Performance, and More
JavaScript Best Practices: More Things to Avoid: We look at the misuse of the for…in loop, the == operator, the arguments object, and “this”
Misusing the For…in Loop
Messing With this
The == Operator
The arguments Object
JavaScript Best Practices — DOM Manipulation and Functions
Avoid DOM Manipulation
We can easily put a lot of styling code in our CSS instead of manipulating it directly with JavaScript.
Using Shortcuts
object literal
array literal
ternary operator
One Function Per Task
Generally, a function should only do one thing. This makes each function short and easy to read.
JavaScript Best Practices — Whitespaces, Underscores, and Useless Ternary
JavaScript Best Practices — Useless Catch, Concatenation, Escape, Return and More
JavaScript Best Practices — With, Promise Errors, Regex Issues
JavaScript Best Practices — Classes and Modules ** updated
Add a toString Method
We can Skip the constructor Method if we Don’t Want to Put Anything in it
No Duplicate Class Members
Class Methods Should use this or be Made into a Static Method
Always Use Standard Modules
No Wildcard Imports
Don’t Export Directly from an Import
Import a Path only in one Place
Don’t Export Mutable Variables
JavaScript Best Practices — Objects and Useless Constructors
JavaScript Best Practices : Returns, scopes, and if statements
JavaScript Best Practices — Event Listeners, Arrays, and null
JavaScript Best Practices— Currying and Partial Applications
JavaScript Best Practices — Imports, Symbols, and Constructors
JavaScript Best Practices — Function Layout and Documentation
JavaScript Refactoring Tips — Arrays, Class Names, and Conditionals
JavaScript: 6 practices to be aware of
Did you know that you can calculate with strings in JavaScript?
Blocking the event loop
Strange scoping rules
0.1 + 0.2 is 0.3? Well yes, but actually no.
Clean up an Array in JavaScript? There are a few ways, but just 2 proper ways
Dangerous inaccuracy when passing parameters
9 JavaScript Features That Can Make Any Java Developer Scream
What the f*ck JavaScript? ** 以下文章大部分都參考了這邊的內容 **
Magical JavaScript behaviors I
True is equal to False
MIN_VALUE is bigger than zero
NaN is not a NaN
Summing magically numbers
Comparison of numbers
Unexpected return value on Try-catch-finally
Arrow functions
Mysterious return
Null with Relational Operators
Batman!
Magical JavaScript behaviors II
baNaNa
Truthy but not true
Adding arrays
Undefined and Number
Undefined can be defined
Undefined always is undefined
Lexicographic sorting
a null is an object, but undefined is undefined
9 Examples Showing How JavaScript Sometimes Behaves Illogically
Null is an Object
NaN is a number
[] not equal []
Adding arrays
true is not equal ![], but not equal [] too
baNaNa
UNDEFINED CAN BE DEFINED
Funny math
Strings aren’t instances of String
‘BANANA’ with JavaScript : Understanding WTF moments of JavaScript
Moment 1 — BANANA
Moment 2 — Adding arrays
Moment 3 — parseInt( ) function
Moment 4 — floating point precision
Taking advantage of the language’s implicit type coercion rules
Using var in 2021
Not understanding the differences between normal functions and arrow functions
Not understanding THIS by now
Misusing closures and causing (unwanted) memory leaks
JavaScript Best Practices — Things to Avoid
Avoid Declaring Global Variables
Never Pass a String to setInterval or setTimeout
Don’t Use the “with” Statement
var Keyword
Small ECMAScript features that are a big help
Exponentiation or power ** Operator — ES7
Array.prototype.includes — ES7
Object.entries — ES8
Object.values — ES8
String Padding — ES8
15 Simple Coding Techniques to Get Your Tasks Done with Shorter Code in JavaScript
5 Must-know Javascript Tips & Tricks
Create an array with unique values using the “Set” object
Shorten your “if” statements
Shorten an array using its length property
Using the spread operator to combine objects
Using the window.location object
5 Useful Tricks JavaScript has been Hiding from You
The + Operator
The debugger Statement
The comma Operator
The Set Object
The Navigator & Performance API’s
Ultimate Guide to Tips, Tricks, and JavaScript Features You Should Know!
Let and Const variable initializers
Default function parameters
Template literals (embedded expressions and multi-line strings)
Destructuring
Array helper functions (forEach, map, filter, reduce, includes, flat, reverse)
5 JavaScript Tricks That Are Good To Know
Every and some
Conditionally setting a variable
Casting values in Arrays
Object destructuring
Better debugging using performance
setTimeout() / setInterval
10 Simple and useful tricks with JavaScript
Fill an array with values
Get Array Unique Values
Replace all occurrences of a word in a JavaScript String
Get a random value with an X probability
Generate a unique universal identifier UUID
Object destructuring for array items
Creating pure objects
Formatting JSON code
Flattening multidimensional arrays
Merge objects
Constants
if used for objects or array, those constant are still mutable, as we can change their internal properties.
Object Immutability
Object.freeze() makes first-level properties of objects immutable: You can’t change them, but if such property is an object, then you can change a property of that child object.
Cloning
One solution to overcome this problem is to convert the object to a JSON string and then parse it back into an object. This is one of the simplest and most effective solutions to completely clone an object without any reference of the original one — i.e. deep cloning.
Class
Classes are nothing but functions with some dressing.
Data Type of Variables
Tips and Tricks for Modern JavaScript
How to stop ‘const’ from mutation?
How to convert functions to an arrow function?
Write default Parameters in JavaScript function?
How ‘Rest Operator’ helps to optimize your code?
How ‘Spread Operator’ helps to add value in array without destroying it?
How to use destructuring assignments to assign variables?
Import and Export
9 Tricks for Kickass JavaScript Developers in 2019
async / await
async control flow
Destructuring & default values
Truthy & falsy values
Logical and ternary operators
Optional chaining
Class properties & binding
Use parcel
Write more code yourself
Some cool and awesome JavaScript tricks
Removing duplicates from an array
4 JavaScript Tricks You Should Know
Destructuring Assignments
Short Circuit Conditionals
Null Coalescing Operator For Default Values (ES2020)
Truncating Arrays
How I improve my JavaScript Coding Skill every day
Editor: VS Code
Love ESLint at first sight
The optimal directory structure
Console.log wherever It’s “smell”
Comment on time
Use ES6,7,8,9 standards
Skip Promise / Callback and switch to Async / Await now
Improve code quality with Typescript
CI/CD — Code -> Test->Deploy
JavaScript Best Practice — Replacing Old with New
Replace Then with Async / Await
Replacing Dictionary Objects with Maps
Replace Apply with Spread
Replace Constructor Functions with Classes
What Are JavaScript Constructor Functions?
In JavaScript, functions can be used as templates for creating other objects. These functions are called constructor functions and have special properties that are different from regular functions.
5 Key Concepts to Level Up Your JavaScript Skills
Destructuring
Spread Syntax
Rest Syntax
Array methods
Value vs. Reference Variable Assignment
The 7 Most-Used JavaScript Topics You Should Know
Promises
Async/Await
Fetch
Classes & Objects
import/export
How 'this’ works
Events & Event Listeners
How Does It Work?
Function Execution Context
Global Execution Context
Execution Stack
Event Queue
Function Execution Context Steps
Scope and Scope Chain
Closures
The Value of this
Arrow Functions
Function Declarations
Hoisting
9 JavaScript Tricks To Code Like A Pro!
Arrow Functions
Spread Operator
Rest Operator
Fill Arrays
Computed object property names
Good ways to console.log()
Object destructuring
Use reduce() map() and filter() instead of regular for loops
Conditional Operator
More Tricks That Will Supercharge Your JavaScript Skills
Concatenating arrays
Unique values
Counting values
Template literals
Understanding static in Javascript (in react)
Javascript: The Hidden Parts (Implicit and Automatic)
Automatic Semicolon Insertion
Implicit Coercion
Implicit Coercion in JavaScript
What is Type Coercion?
Explicit Coercion
Implicit Coercion
Primitive Coercion
Primitive to boolean
if (123 && "hello"){ //true
alert(123 && "hello"); //"hello"
}
Primitive to string
Primitive to number
Object Coercion
Symbol Coercion
Implicit Return
Implicit Function Params
10 JavaScript Code Snippets You Can Use Right Now
Reverse a String
Calculate a Number’s Factorial
Convert a Number to an Array of Digits
Check if a Number Is a Power of Two
Create an Array of Key-Value Pairs From an Object
Return [Number] Maximum Elements From an Array
Check if All Elements in an Array Are Equal
Return the Average of Two Numbers
Return the Sum of Two or More Numbers
Return the Powerset of an Array of Numbers
18 Useful JavaScript Snippets for Common Tasks You Can Use From Today ** 注意,範例裡有bug **
Weird Parts of JavaScript — Comparisons and Arithmetic
Comparing 3 Numbers
Funny Arithmetic
Lesser Known Facts About JavaScript
Why 0.1 + 0.2 ≠ 0.3 in JavaScript : JavaScript floating point math is a little off sometimes. Here’s why 0.1 + 0.2 ≠ 0.3 and what you can do if you need accuracy.
Why is 0.1 + 0.2 Not Equal to 0.3 in Most Programming Languages?
JavaScript’s Magical Tips Every Developer Should Remember
Use “var” when creating a new variable.
Always use “===” as comparator instead of “==” (Strict equal)
Stop Using === Everywhere: An unpopular opinion, let’s take a look
Here are two use cases where it’s better to use == to illustrate the point.
Testing for Empty Values
Reading Input From a User
‘undefined, null, 0, false, NaN, ‘’ (empty string)’ are all false conditions.
How to check for NaN in JavaScript
The typeof NaN is “number”
NaN is unequal to every other value in JavaScript
A word about Number.isNan()
How to check for null in JavaScript
null is falsy
Falsy equality using ==
Strict equality using ===
Use typeof anyway with falsy power
What is the difference between Null and Undefined JavaScript?
Null is one of JavaScript’s primitive values.
Null is an object with a valid value, no properties, is non-mutable, and only a single instance of the same exists in the system at all times.
The data type of null is an object, where as undefined is of type undefined.
null !== undefined but null == undefined.
What are truthy values in JavaScript?: Truthy values evaluate to true when coerced by JavaScript’s typing engine into a boolean value. Most values are truthy in JavaScript, including the empty array [] and the empty object {}.
Is Negative Zero (-0) a Number in JavaScript?
Are positive and negative zero equal?
What’s the difference between +0 and -0?
What if you need to differentiate +0 from -0?
How to Know If an Object is Empty or Not
Using Object.keys
Using JSON.stringify
Using for in
Empty an array
Rounding number to N decimal places
Verify that your computation will produce finite result or not.
Use a switch/case statement instead of a series of if/else
Use of “use strict” inside your file
Use && and || to create magic
7 JavaScript Utility Functions to Improve Your Efficiency
Detect Browser
Detect Function Type
Convert hyp-hens to camelCase
Delete HTML tag in string
Reverse a String
Format a number to a string with comma
Convert byte units to reasonable units
11 Extremely Useful JavaScript Tips
Converting to Boolean Using the !! Operator
Converting to Number Using the + Operator
Short-Circuit Conditionals
Default Values Using the || Operator
6 Ways To Set Default Values in JavaScript : The OR operators, the nullish operators, function defaults, and more
Caching the array.length in the Loop
Getting the Last Item in the Array
Truncating Array
Replace All
Stop Using String Replace in JavaScript: Why you should use replaceAll when replacing multiple instances of a substring
Converting NodeList to Arrays
Merging Arrays
Shuffling an Array’s Elements
JavaScript Caveats That Can Fool You
Improper reference to ‘this’
Block Level Scope
Strange Type Coercion Behaviour
Concatenation or Addition?
Equality checking
Not handling errors properly (or null and undefined)
Some more weirdness
NaN is weird
JavaScript Can Be A Little Weird At Times
NaN is not a number
[] and null are objects
Math.max() is less than Math.min()
Comparing null to 0
[] is truthy, but not true
10 things to learn on the way to becoming a JavaScript Master
Control Flow
Error handling
Data Models
Asynchronity
DOM Manipulation
Node.js / Express
Functional Approach
Object Oriented Approach
Frontend Framework
React.js, Angular and Vue.js
Bundling / Transpilation
babel, webpack, and parcel
36 JavaScript Concepts You Need to Master to Become an Expert
Divide and conquer
Make things embarrassingly obvious
Resolve magic numbers and strings
Fight nesting
Configure hard
Frameworks are there to help
React
Angular / VueJS / Ember
jQuery / lodash / or similar
Vanilla / No framework
Unless it is a prototype — write tests
Use version control
Manage state responsibly
Question trends
Learning How to Learn JavaScript
Get comfortable with asynchronous JavaScript
Learn the basics of TypeScript
Understand why JavaScript frameworks exist
Learn two similar frameworks simultaneously
Demystify the build process
The JavaScript landscape in 2020
Consolidation
Package Managers: NPM
Testing: Jest
JavaScript Flavors: TypeScript
UI frameworks: React & Vue
Challengers
Package Managers: PNPM
Testing: Cypress and Puppeteer
JavaScript Flavors: PureScript
UI frameworks: Svelte
Should I upgrade my web app to modern Javascript frameworks?
Node.js–Javascript runtime.
Babel.js–compiler for modern Javascript.
Webpack — module bundler.
React–Javascript UI library.
TypeScript–Typed superscript language.
Stylus–CSS preprocessor.
MobX–application state management.
Top 10 Github Apps on Marketplace to Use as Junior JavaScript Developers in 2020
Top JavaScript Frameworks and Topics to Learn in 2020 and the New Decade
React Dominated 2019, and Will Probably Dominate 2020
TypeScript vs JavaScript
Data Management
Redux still has a strong lead in the state manager race, but GraphQL and Apollo are gaining in satisfaction and interest.
Back End
Express is the dominant Node framework, with very high satisfaction and no serious challengers going into 2020, but with the rise of serverless, I expect to see Express dominance slip as the new decade unfolds.
Testing
Jest and Cypress are most popular for unit and functional testing, respectively
Functional Tools
Lodash, Ramda, Immer, Redux, and RxJS are the functional tools I frequently use.
SPAC
5 Javascript Libraries That Are a Great Fit for Any Front-End Project
Immer
Lodash
Jest
Storybook
Moment.js
The 6 tools that changed JavaScript for me
TypeScript
Visual Studio Code
React
Ramda
FP-TS
XState
Top 10 JavaScript Open Source Projects On GitHub
React — a JavaScript open source library by Facebook
TensorFlow.js
Build Speech Recognition in JavaScript : Learn how to build Speech Recognition using TensorFlow.js.
Node.js
AngularJS
jQuery
npm
Vue.js
Ember.js
Ember is a JavaScript open source framework which allows developers to create scalable single-page web applications, similar to AngularJS. Ember.js focuses on productivity, easy enhancement and developer-friendliness.
MeteorJS
Meteor is a cross-platform open-source platform for web, mobile and desktop. Meteor integrates with various other JavaScript frameworks seamlessly. MeteorJS focuses on optimizing code size, cross-platform compatibility, and integration into other libraries.
Polymer
Polymer is a JavaScript open source library for building applications using what are called “Web Components”.
Top JavaScript Open Source Projects On GitHub — Part 2
Math.js
Jest
Prettier
Chance
Chartify
localForage
Tone.js
draw.io
Mermaid
Spacetime
Best JavaScript Frameworks and Libraries: what to use in 2020
Front-end frameworks
React
Angular
Vue.js
Svelte
Data layer frameworks
Redux
GraphQL
Back-end Frameworks
Express
Koa
Next.js
What’s the Best JS Framework for Lightning-Fast Applications?
React vs. Preact vs. Inferno
Lightweight Alternatives to React
Vanilla JS
Preact
Svelte
Top 5 In-Demand JavaScript Frameworks for Front-End Development in 2020
React
Vue.js
Angular
Ember.js
Svelte
What Will Be the Best JavaScript Framework in 2021?
Based on the above observations, we can conclude that React will be the best framework to learn in 2021, followed by Vue. But there is a high chance of Angular defending second place since it has been there for a longer period of time than Vue, and surely 2021 is not the end of that. So if you are an Angular developer, I suggest you learn React in the upcoming days.
I created the exact same app in React and Vue. Here are the differences. [2020 Edition]
Top JavaScript Libraries You Should Know About
Algolia Places
TensorFlow.js
Animate CSS
Chart.js
Cleave.js
Voca
Slick
Socket.IO
MathJAX
10 Awesome JavaScript Libraries for Front-End Developers in 2020
Ramda
Lodash
Moment
Highlight.js
D3
Three.js
Voca
Immutable.js
Hammer.js
Leaflet
Lesser-Known Yet Still Popular JavaScript Frameworks for Front-End Developers: Options that aren’t React, Angular, or Vue.js
Svelte
Ember
Preact
Riot
Aurelia
Mithril
3 Underrated JavaScript Frameworks : A look at Svelte, Ember, and Preact
3 awesome but small JavaScript Libraries you need to try
Basket.js
Pill
JS-cookie
3 more awesome but small JavaScript Libraries you need to try
Reliable data validation with xtype.js
Handling keyboard shortcuts in the Browser with Mousetrap.js
Analyzing user input with Countable.js
Two JavaScript Coding Patterns That Give You Away as a Junior Developer
Overuse of “if” and “else” Statements
Using Functional Programming in a Nonfunctional Way
How to make your code better with intention-revealing function names
Conventions
Use Strict
How JavaScript still hasn’t broken the Internet just yet: even in its sloppy and strict states
Why Do We Need Strict Mode in JavaScript?
Changes in Strict Mode
Converting Mistakes to Errors
Prohibiting Invalid Syntax
Performance Optimizations
Security Fixes
An Intro to Javascript for Experienced Programmers Who Could Use a Strong Dose of Fundamentals
Get started with Next-Gen Javascript
First things first, forget “var” start using “let” and “const”
Arrow Functions
Export and Import
Classes
Rest and Spread operators
Destructuring
JavaScript Methods That Every Beginner and Pro Should Use
Arrays
find()
findIndex()
filter()
includes()
Spread operator
String
startsWith()
endsWith()
includes()
Object
Creating and copying objects
Javascript engine
JavaScript Execution in a Nutshell
Part 1: What is a JavaScript Engine?
Part 2: How is my JavaScript executed?
Part 3: Code Execution Breakdown
JavaScript Engines: An Overview : Understand the basics of a JavaScript Engine and get an introduction into Chrome’s V8 Engine
8 Habits For Beginning and Mid Level JavaScript Developers That Sabotage Your Future
Using jQuery
Not Exercising
Socially Isolating Yourself
Not Writing Tests
Learning Frameworks Before JavaScript
Not Learning Clean Code Practices Earlier
Starting on Big Projects Too Soon
Not Learning Data Structures And Algorithms
Why Developers Hate JavaScript, and Why They’ve Got It All Wrong
JavaScript is only suited for the web, making it a one trick pony.
With the introduction of the runtime environment Node in 2012, (and younger brother Deno more recently), JavaScript escaped the captivity of the browser long ago. You can find it on web servers, Raspberry Pis, robots and running machine learning algorithms.
JavaScript is still the only language that runs in a web browser.
JavaScript is bloated and slow.
What may surprise those developers who complain about JavaScript’s speed is that Node will often outperform other dynamic languages in its class, like Python and Ruby.
JavaScript’s type coercion makes code unpredictable.
JavaScript can’t handle Object Oriented Programming
With the language features introduced in ECMAScript 6, JavaScript has clean syntax to support classes, encapsulation and inheritance. While it may operate differently than other OOP languages under the hood, (like using prototypal inheritance and using closures for private variables), the functionality is very much supported in the language.
JavaScript is useless without depending on heavy libraries like React.
The ability to quickly import these packages is an asset that saves time and keeps code DRY. It’s up to us, as developers, to add only the packages we need and to balance, as we always have, coding efficiency with program efficiency.
Should You Use Dependency Injection in JavaScript?
Testing scenario
Poor Mans DI
Defaulting Behavior
Dependency Injection in JavaScript — the Best Tool You’re Not Using for your Tests
How You Should Not Write Code - JavaScript
Dependency Injection (DON'T)
DI makes take code readable and maintainable. However, this is not a valid case for JavaScript. JavaScript is a dynamic language. You can modify the context of the object or constructor on runtime.
Underscore (_) for private variable (DON'T)
If you really care about the private variable. You can use Symbol with ES2015 or the latest.
Explicitly assign null to a variable (DON'T)
this could lead to a big issue and can become a code smell
Basic use of iterator methods[forEach, map, reduce, etc.] (DO)
we should leverage the power of Array methods
Try-Catch Hell (DON'T)
you can simplify catching in the call .catch method and reuse function
A long path for import directory (DON'T)
The Comprehensive Guide to Operators, Expressions, and Statements in JavaScript
Semicolons
You Might Need Those Semicolons in Your JavaScript After All: Leaving them out looks pretty, but it could break things
Whatever camp you fall into, it’s important to understand that omitting semicolons can bite you from time to time, and you might not expect it. IIFEs, for example, can be a problematic pattern for sans-semicolon users.
JS: Underrated features: Javascript functions and features not widely used
Set
.some()
.freeze()
.querySelector(), .querySelectorAll()
Pretty console.log
Browser modules
Variables
Navigating Equality Comparitors and Sameness Checks in JavaScript
JavaScript Best Practices — Variables
Avoid Global Variables
Always Declare Local Variables
Putting Variables and Constant Declarations on Top
Initialize Variables When Declaring Them
Stop Using ‘var’ to Declare Variables in JavaScript
Declaring True Constants (const)
Fixing JavaScript’s Quirky Scope
Here is a summary of the JS scope oddities:
could use var twice with a variable (redeclaration)
top-level variables were global by default (global object)
variables could be used before being declared (hoisting)
variables in loops reused the same reference (closures)
A Comprehensively Short Guide to let, var and this
if a variable is declared at the root level, it becomes a global variable and accessible by everything
var is scoped to the nearest function block, meaning the closest { } pair that’s attached to a function.
let is scoped to the nearest closing block, meaning the closest { } pair, regardless of what it is.
this lets you access variables that are outside the closing block and function scopes. Depending on what you used (i.e. let or var), it can change the way results are returned.
How JavaScript Variables Should Be Named
Case-Sensitive
Self-Descriptive
Boolean naming convention
Constant naming convention
Essential differences in variable declarations in JavaScript
Data Types
Understanding JavaScript’s Data Types
Value Types vs Reference Types
Programmatically Getting The Type
Value Types
Reference Types
3 TypeScript-ish Solutions For Your Type Checking Needs in JavaScript : For those times you need to type-check but you just refuse to use TypeScript
TypeCheck
Typify
TypeOnly
Type Safe JavaScript with JSDoc
Types are Good
Benefits of Types
Early detection of type errors
Better code analysis
Improved IDE support
Promotes dependable refactoring
Improves code readability
Provides useful IntelliSense while coding
Getting Types Right is Hard
Be Proactive
JSDoc for Types
Set Up Visual Studio Code
Alternative Ways to Turn Type Checking On and Off
Setting Up Live Type Linting
JSDoc Comments
Defining Types with JSDoc
Default Types
null
undefined
boolean
number
string
Array or []
Object or {}
Custom type
Properties
Method or Function
Optional Parameters
Expando Properties
Defining Object Types
Verbosity vs Simplicity
Generics
Type Casting
Importing Types
Batch Imports
Avoid Type Any
Checking Types During Build
JSDoc Comments = Type Information++
Type Safety at Runtime
How to Type-check Your JavaScript Without TypeScript : How to use JSDoc to type your JavaScript code
What are Primitive and Reference Types in JavaScript?
First up: Primitive types
Next: Reference Types
Explaining it with a chore metaphor
Code that copies a value is where it counts
Solving the reference problem
One of the first things to understand in JavaScript — Immutability
Learn immutability with JavaScript
Primitives
Const
Freezing objects
The differences between Object.freeze() vs Const in JavaScript
const behaves like let. The only difference is, it defines a variable that cannot be reassigned. Variables declared by const are block scoped and not function scoped like variables declared with var
Object.freeze() takes an object as an argument and returns the same object as an immutable object. This implies that no properties of the object can be added, removed, or changed.
Prevent Object Properties From Being Modified With JavaScript’s Freeze Function
Object.freeze()
Object.Seal
Working with immutable objects
Working with array as immutable
Immutable Library
How To Check Data Types in JavaScript using typeof
undefined
How to Check for Undefined in JavaScript
The typeof keyword returning "undefined" can mean one of two things: the variable is the primitive undefined, or the variable has not been declared at all. Here’s how to tell the difference.
object (meaning null)
boolean
number
bigint
string
symbol
function
object (meaning array or object)
Why ['1', '7', '11'].map(parseInt) returns [1, NaN, 3] in Javascript
正確的寫法
['1', '7', '11'].map(numStr => parseInt(numStr));
Number
The Ultimate Guide for Manipulating Numbers in JavaScript
Rounding Numbers
Exponentiation
The newest way is the exponentiation operator **, available with ES2016 or higher.
We can also use the Math.pow function
Formatting Numbers in JavaScript with the NumberFormat Constructor
Intl.NumberFormat
Beginner’s Guide to Numeral.Js: A library for easy number formatting
How to Round a Number to Two Decimals : Quick start with the toFixed method, Math.round utility and the Intl.NumberFormat object
boolean
2 Ways to Convert Values to Boolean in JavaScript
Convert Values to Boolean
String
Number
Falsy Values
How the !! works
String
How to Manipulate Strings in JavaScript Like a Professional Developer : 10 Top key methods to keep in mind for manipulating strings in JS
5 Ways to Convert a Value to String in JavaScript
Concat Empty String
Template String
JSON.stringify()
toString()
String()
How to pad a string in JavaScript: ES2017 added the padStart() and padEnd() methods, which add whitespace or other characters to a string until it reaches a specific length.
How to check for a string in JavaScript: When checking for strings, typeof works great unless someone uses a primitive object wrapper, which is considered bad code.
How to Repeat a String in JavaScript: The JavaScript method .repeat() returns a string repeated as many times as needed.
JavaScript: The fastest way to replace Strings
Single quotes string buildup: 0.028 seconds
Template String: 0.303 seconds
String replace: 7.35 seconds
Stop Using String Replace in JavaScript: Why you should use replaceAll when replacing multiple instances of a substring
JavaScript: String.replaceAll has Landed in All Major Browsers
Effectively Overriding JavaScript’s toString() Method
Overriding the toString() method directly in your object (method 1)
Overriding Object. prototype.toString with your own function.
2 Fun Ways To Use `toString()` in JavaScript
Change Integers from Base-10 to Binary
Convert Colors from RGB to Hexadecimal
How to Select a Range from a String (a Substring) in JavaScript: There’s no handy shortcut here. To get a substring, use the built-in method String.prototype.substring(startIndex, endIndex).
5 JavaScript Strings Tricks You Should Know
Multi-line strings and embedded expressions
Check if a substring exists in an array of strings
JSON pretty formatting and parsing
Normalizing Strings
Split Strings By One Or More Separators
10 Common JavaScript String Manipulation Methods You Should Commit to Memory
Conditional Statement / Operators
How to Make Your Conditional Statements Easier to Read in JavaScript
The Basics of JavaScript Conditionals
Best Practices Using Conditionals
Stop Putting So Many If Statements in Your JavaScript: 4 other ways of handling conditional logic in your code
Ternary Operators
Switch Statements
Logical Operators (&& and ||)
Lookup Maps
Avoiding If Statements in Our JavaScript Code
Ternary Operator
Short Circuit
Avoid Use of Switch Statements
How to Shorten JavaScript Conditionals with Short-Circuiting
5 Alternatives to ‘If’ Statements for Conditional Branching
The Ternary Operator
The Switch Statement
The Jump Table
The Dynamic Dispatch
‘try' and 'catch' statements
Pattern Matching
6 Tips to Improve Your Conditional Statements for Better Readability (文後的回覆提醒,雖然程式會比較簡潔,要注意效能問題,不少的array函數的效能是不好的,如果資料量大的時候,要避免使用)
Returning Early Instead of if…else
Using Array.includes
Using Default Function Parameters
Using Array.every
Using Array.some
Using Indexing Instead of switch…case
Clean up your code by removing ‘if-else’ statements (文章的後的很多回應是認為這樣的寫法會降低程式碼可讀性)
if/else
switch
Unary judgment: stored in Object
Unary judgment: save to Map
Multiple judgment: concatenate the condition into a string and save it in Object
Multiple judgment: concatenate the condition into a string and store it in a Map
Multiple judgment: save condition as an object in Map
Multiple judgment: save condition as a regular expression in Map
Stop Using If-Else Statements (文章的後的很多回應質疑這樣的寫法)
Little Unknown Way To Get Rid Of Switch Statements
範例寫得不好,重點是有時候可以利用object、map或array來簡化if或switch,尤其是這些條件是動態的時候,就一定沒辦法使用if或switch
How to Add Conditional Elements to Array and Object Literals
Switch
Introducing the JavaScript Switch Statement
Defining Switch Statements
Putting Default Between Cases
Multi-Criteria Case
Chained Expressions
Block-Scope Variable in Switch Statements
Ternary operators
What does the ? question mark mean in JavaScript code?: The question mark ? is an alternative to an if statement best used in the case where one of two values will be assigned to a variable based on a conditional statement.
Refactor Code By Using the Ternary Operator in JavaScript: Learn how the ternary operator works and how to use it to remove complicated “if” statements in your code
Replace Your JavaScript If/Else Statements with the Ternary Operator
Operators
6 Useful JavaScript Operators that You Should Know
Assignment Operators
Comparison Operators
Equality Operators
Arithmetic Operators
Logical Operators
Conditional (ternary) operator
A List of Interesting Operators in JavaScript
Exclamation Mark (!)— Logical NOT
Double Exclamation Mark (!!) — Double Logical NOT
Double Asterisks (**) — Exponentiation
Tilde(~) — Bitwise NOT
Double Tilde(~~) — Math.floor & Math.trunc
Double Period(..) With toString
IIFE With Operators
The Dangers of the ‘+’ Operator in JavaScript: How simple addition can misfire and break JavaScript applications in ways you might not expect
Conditional Statement
Immediately Invoked Function Expressions
Non-leaking Arrow Functions
Asynchronous Calls with void
Abstraction
JavaScript: Abstraction, Data Types, and Expressions
Control abstraction
higher-order functions
Data abstraction
In JavaScript, prototypes and closures can help us accomplish data abstraction.
Functions (詳參: Functions)
Objects
JavaScript Best Practices: Objects: Traps we can fall into when we define objects
Use Literals for Primitive Values
The best ways are to set the literals directly
Use Literals to Declare Objects Whenever They Exist
Automatic Type Conversions
9 Ways to Work With Objects in JavaScript in 2020
How To Truly Create an Empty Object
Merging Objects Variation #1 (Object.assign)
Merging Objects Variation #2 (Spread Syntax)
Checking Existent Properties in 2020
Invoke Objects by Overriding .toString()
Destructuring
Renaming Destructured Properties
Iterating Over an Object’s Keys (for in)
Iterating Over an Object’s Keys Variation #2 (Object.keys)
Six things you should know about Objects in JavaScript
Object methods & this
Prototypes
Constructors
Overriding Derived Properties
Prototype Interference
Prototype-less objects
3 Tips for Better Objects in JavaScript
Do not call Object.prototype methods directly
Objects with dynamic property names
Property value shorthand
Javascript Tips That Will Save Your Days — Part 1: Object Reference
Comparing Objects in JavaScript: What works, what doesn’t and why.
it is comparing the references to the objects, not the value of the objects.
A Practical Use Case for JavaScript’s Object.assign(): Assigning a Database recordset Object to a JavaScript Class Object
ES6: Object.is() vs. === in JavaScript: ES6 (ECMAScript 2015) added a helper function called Object.is() that is slightly different from the === operator
The 2 differences between === and Object.is()
Negative Zero
NaN
Proxy
Using a JavaScript Proxy Object to Control Object Operations
Haskell-like composition in JavaScript
In JS, the Proxy object is a metaprogramming tool that gives us an ability to override fundamental JS operations.
Best of Modern JavaScript — Handler Methods
We can control many object operations with proxy handler methods.
Improve Both App Performance and Code Quality: Combining HTTP Requests by Proxy Pattern
How To Do Common JavaScript Object Operations
Define New Object Literal
Define Object with Constructor
Get Keys of Object
Get Entries of an Object
Merge Two Objects
Prevent Modification to an Existing Object
Check If an Object Can Be Modified
Clone Objects
Using JavaScript’s Object Constructor — Part 1
Object.assign()
Object.create()
Object.defineProperty()
Object.defineProperties()
Object.entries()
Object.freeze()
JavaScript’s Object Constructor: Preventing Changes and Getting Entries
Object.isSealed()
Object.keys()
Object.preventExtensions()
Object.seal()
Object.setPrototypeOf()
Object.values()
JavaScript — Iterate Over Object Properties
The result shows Object.keys is the fastest method to iterate over an object with 100,000 properties, twice as much then Object.entities and Object.values.
In the second place will be the for…in method available since the ES 1.
JavaScript Fundamentals: Mastering Objects
Creating an Object
Dot notation
Deleting Properties
Square Brackets
Updating object members
What is “this”?
The Guide I Wish I Had for JavaScript Object Creation Patterns
Object Factories
Object Factories With Mix-Ins
Constructor Pattern
Constructors With Prototypes (Pseudo-Classical Pattern)
Inheritance With the Pseudo-Classical Pattern
Another Way to Set the Inheritance Chain
Objects Linking to Other Objects (OLOO)
4 Ways to Create Objects in JavaScript **
Object literals, prototypes, classes, factory functions, and more
The 3 ways to create a JavaScript object (without class)
Using object literals
built-in constructor
but it is an anti-pattern
custom constructor functions
Supporting Multiple Constructors in JavaScript : 3 patterns for object creation
Optional parameters with defaults
A single object literal
Static factory methods
Learning JavaScript: Working with Objects — this, getters, and setters
This Trick Changed the Way I Access Nested Objects in JavaScript
optional chaining
Remove A Property From An Object In JavaScript With This Little Trick : Using JavaScript spread syntax in your reducers
How To Check if a Property Exists on a JavaScript Object : Three methods for three different use cases
3 Ways to Work with Properties in a Dynamic Way : Object literal syntax, destructuring assignment, bracket notation, and more
Did You Know That Almost Everything Is an Object in JavaScript?
Functions and arrays are objects, but not everything in JavaScript is an object.
Primitives are not objects, but overall JavaScript tries to make them look as such and keep the illusion that everything is an object. There are two exceptions to this approach: null and undefined.
Class /OOP
Understanding the Object-Oriented Programming Style in JavaScript : Get to know the classic programming paradigm that’s still relevant today
programming with objects
Why You Should Not Use Classes in JavaScript
JavaScript is not an Object-Oriented Language
It is actually a prototype-oriented language.
Binding
Inheritance is bad
Encapsulation
While it is possible to create private functions inside of a class by using the ‘#’ character, we can not make variables private in JavaScript.
JavaScript Fundamentals: Mastering Classes
Class declarations
Class expressions
Constructors
Instance properties
Field declarations
Child classes using 'extends'
Species
The ‘Super’ keyword
Mix-ins
An overview of classes in JavaScript
Classes Highlight
Hoisting
Subclassing / Inheritance
Mixins
Getters and Setters
5 Reasons Why You Should Collate Your Functions Into a Class
Organized functions are more functional
Everything is an object
Protection against mutations
containerized modularity
JavaScript is object-oriented
JavaScript Classes, Inheritance, and prototype chaining (ES5 and ES6 way)
A JavaScript class (ES6)
Classes in ES5
Objects created with classes (ES6) vs Objects created with constructor functions (ES5)
Inheritance
The ES6 way — classes
Inheritance — The ES5 way
Dot notation vs Bracket notation
Dot Notation’s Limitation
Issue working with Identifiers
Issue working with Variables
Use the Dot Notation. But if you’re dealing with invalid identifier or variables, use the Bracket notation.
Dot vs Bracket Notation in Accessing JavaScript Object.
If the property name is not a valid identifier , then we cannot access its value using . notation.
The bracket notation is used when the property name is an invalid identifier(starts with a number, contains symbols).
Javascript: About Classes, Binds & Arrows
ES6 Classes & Constructor Functions
The Bind
Arrow Functions
JavaScript Classes: An In-Depth look (Part 1)
Creating a basic class.
Creating objects from the class.
Putting the objects in an array.
Converting the array of our Objects to a Json string.
Coverting a Json string to our Object.
JavaScript Classes: An In-Depth look (Part 2)
Learn some additional terminology.
Use the getter and setter methods, get() and set() to add functionality and better encapsulation.
Understand and use the backing field prefix “_”.
Create methods in our class to give the class functionality.
JavaScript Classes: An In-Depth look (Part 3)
Continue with additional methods and code for external consumption.
Add methods for consumption inside the class.
Use other classes in our classes.
Please stop using Classes in JavaScript and become a better developer
JavaScript Private and Public Class Fields (private field is available in ES2020)
Symbols
Sets (ES6)
Let's learn about Set and its unique functionality in JavaScript
JavaScript: Sets vs. Arrays: Introducing Sets, the ES6 data type you didn’t know you needed
A set is designed to represent a collection of unique items whereas an array is a bit more general purpose.
Using Sets to Remove Duplicates From an Array
The New Way To Remove Duplicates From An Array In JavaScript
Let’s use Set instead.
How to Know If an Array Has Duplicates in JavaScript : Set collections, equality on objects, the map array method, and more
Using JavaScript Sets: A useful data structure that models the properties of mathematical sets
Should You Stop Using Objects and Arrays to Store Data? : ES6 has other ways of handling data structures and values in the form of Set and Map
How to Find Unique Values by Property in an Array of Objects in JavaScript
Using Set for Unique Object Properties
Unique Values for a Given Property among Objects
How to Select Specific Properties From an Array of Objects in JavaScript
How to Find Unique Objects in an Array in JavaScript by Object Reference or Key-Value Pairs
Maps (ES6)
Introduction to Map Object in JavaScript
How to Use Map Object?
Size and Iterating
Should we use Map Object?
How JavaScript Maps Can Make Your Code Faster
How are Maps different to Objects?
Unrestricted Keys
Direct Iteration
How are Maps different to Sets?
Type Conversion
Storing Key-Value Pairs With JavaScript Maps: What’s the difference between a Map and an Object?
How Maps work in JavaScript: Map is one of the data structures that comes with the ECMAScript 6.
Initializing Map
Methods
Properties
Iterating Map Object
For..of loop
foreach loop
Turn JavaScript Objects in Maps for Predictability: No more errors with undefined properties
Stop Using Objects as Hash Maps in JavaScript
More Key Types
Better Size Determination
Better Performance
Direct Iteration
Key Order
No Key Overriding
When and why you should use a Map instead of an Object in JavaScript
Should You Stop Using Objects and Arrays to Store Data? : ES6 has other ways of handling data structures and values in the form of Set and Map
Why Should We Stop Using Objects As Maps in JavaScript?: It’s time to use Maps instead of regular objects for key-value data storage
Maps, Sets
How to build reliable objects with factory functions in JavaScript
OOP
An introduction to Object-Oriented Programming in JavaScript
Introduction to Object-Oriented Programming in JavaScript
Functional Instantiation
Functional-Shared Instantiation
Prototypal Instantiation
Pseudoclassical Instantiation
Object-Oriented Programming with Javascript
Encapsulation
S.O.L.I.D the First 5 Principles of Object-Oriented Design with JavaScript
Different ways to achieve encapsulation in JavaScript(ES6)
Factory functions and closures
Weak maps and namespaces
Using Symbols (kind of encapsulated)
Storing Data Efficiently or Privately with JavaScript WeakMaps
Prototypes
Understanding JavaScript Prototypes for Beginners
What is JavaScript prototype
How does it work
__proto__ and prototype
Examples
What is the difference between using a prototype and no prototype
Performance issues
How I met your JavaScript Prototypes: Or why JavaScript Prototypes impact your code execution time…
moving method instantiation to prototype property helped us to improve the app speed.
Prototype Chaining
Inheritance
JavaScript Inheritance with “Object.create”
Can we access those property using new Object ?
Accessing Method of the Prototypal Chain
Overriding the values of Prototype Chain
What Is the Prototype in JavaScript?
What Is a Constructor in JavaScript?
The Constructor function in JavaScript is a function that returns a reference to the object that created the instance object.
What is a Prototype?
A prototype is a shared property amongst all the instances of a function object.
JavaScript Constructor Functions and Prototypes. 盡量使用prototype
Understanding __proto__ in JavaScript
__proto__ was never part of the initial ECMAScript spec, it was just added by browsers and got popularised over the years, so it was eventually added to 2015 ECMAScript spec. But it was still discouraged to use it, it is advisable to use Object.setPrototypeOf and Object.getPrototypeOf instead.
Array
Array Basics
Common Methods
An Introduction to JavaScript Arrays
JavaScript arrays
How to create an array?
Accessing the elements of an array
Getting the size of an array
Looping an array
The Essentials of JavaScript Arrays
The Essential Methods
Map
Reduce
Filter
Sort
Reverse
Use `for…of` to Loop Through Your JavaScript Arrays: A simpler way to iterate over arrays
Array Intersection, Difference, and Union with JavaScript ES7
Sorting Algorithms: the Basics with JavaScript implementation
8 Most Used Array Operations in JavaScript (ES6+)
Array length
Replacing elements of array
Filtering the array
Merging arrays
Duplicating arrays
Removing duplicates from arrays
Converting arrays
Iterating over arrays
Insanely Useful JavaScript Array Methods
Array.of
Array.from
Array.find
Array.findIndex
Array.filter
Array.fill
Array.forEach
Array.map
Array.every
Array.some
Array.reduce
The Fastest Way to Remove a Specific Item from an Array in JavaScript
.indexOf and .splice to remove just the first instance of a value
.filter to remove every instance of a value from an array
How To Remove a Value From an Array in JavaScript: There’s a better way than simply using delete: splice()
Some powerful JavaScript built-in array methods every beginner should know!
.map, .reduce, and .filter
Array Built-In Iterator Functions In JavaScript
forEach, map, filter, every, some, find and findIndex
How to Find Unique Values of a Specific Key in an Array of Objects
JavaScript Array Iteration Methods
Multiple ways of array iteration in JavaScript
Using loops (what beginners do)
Using forEach
Using for..of (how we iterate through an array)
Using for..in (The bad method)
3 JavaScript Array Methods Every Developer Should Know
join()
split()
sort()
How to Transform a String To and From an Array : The split string method and the array join method
JavaScript code recipe: filtering array with multiple values
What Is the Difference Between map() and forEach() in JavaScript?
map returns a new array of its original array. forEach, however, does not.
forEach doesn’t ensure the immutability of an array if you change values inside an array.
Dear for Loop Fans: Let Us Use Array Methods in Peace
There are many array methods, but the ones I’m talking about are the array iterators: forEach, map, filter, every, reduce and the like.
Comparing for Loop with ES6 forEach Method: Do you think the ES6 method forEach can replace for loop?
Why do people fall for forEach?
forEach is easy to write. Call back functions are used.
No index variable is required. callback functions can directly access values one by one.
Little cleaner than for loop.
Things they forget when moving to forEach
Performance. for loop is a native way by the engine whereas forEach is provided by Array object.
There’s no way to break a forEach. If you want to stop a forEach function, you need to throw an exception. And that’s not what exceptions are intended for.
Stop Using For Loops to Iterate Over Arrays: Start replacing your vanilla for loops with the .forEach() method
[…].forEach(saveFromZombies) does not always save people
We have looked at how this might lose context when we put a reference of a function as a callback to forEach.
The solutions are: (1) Explicitly call the function, (2) Pass thisArg as an argument, and (3) Use bind.
You Simply Cannot Do These Things in a forEach Loop in JavaScript
“return” Statement Simply Doesn’t Stop the Loop
在回應中,有人指出將loop的觀念及語法用在forEach就是錯的,以這邊舉的例子而言,應該使用filter而不是forEach。
“break” Statements Don’t Work
“continue” Statements Would Not Work As Well
You Cannot async-await
3 bad use cases of Javascripts forEach loop
If you want to short circuit or break out of the loop
As an example, searching for an element is therefore not a good use case for a forEach loop. Instead go for array methods ‘find’, ‘findIndex’ or a for loop which you can terminate.
When performance is critical
In the forEach loop, we are invoking the callback function on every iteration. This additional scope leads to slower speeds compared to the for loop.
When you want to transform an array
For transformations you can use map and filter which both returns a new array.
Let’s clear up the confusion around the slice( ), splice( ), & split( ) methods in JavaScript
Let’s explore Slice(), Splice() & Spread Syntax(…) in JavaScript (ES6)
Simplify your JavaScript – Use .map(), .reduce(), and .filter()
6 Array Methods to Simplify Your JavaScript: The lowdown on filter, find, map, reduce, every, and some
How to Use filter()
How to use find()
How to Use map()
How to Use reduce()
How to Use every()
How to Use some()
Manipulating JavaScript Arrays: Removing keys: My 6 ways to remove elements from arrays
Length
Shift
Pop
Splice
Delete operator
Adding method to Array.prototype
JavaScript’s Filter Function Explained By Applying To College
Fusion in JavaScript : Fusion is a technique of combining pure functions — taking advantage of composition and removing the intermediary copies of data on each layer.
Why ['1', '7', '11'].map(parseInt) returns [1, NaN, 3] in Javascript
正確的寫法
['1', '7', '11'].map(numStr => parseInt(numStr));
What is the difference between reduce and reduceRight in JavaScript?
4 Reasons to Avoid Using Array.reduce
Array.reduce Can Be Hard to Understand
The Search for the Optional Initial Value Parameter
Are You Reducing, Filtering, or Mapping?
You Can Always Write the Same Code in a More Readable Way
JavaScript has a Reduce Method. You Should Use It.
Reducing an array of values
Breaking down .reduce
Understanding the callback
Where it gets interesting
Making our own count function
Breaking down our count function
5 Use Cases for reduce() in JavaScript
Sum all the values of an array
Sum of values in an object array
Flatten an array of arrays
Grouping objects by a property
Remove duplicates in an array
Learn These Three JavaScript Functions and Become a Reduce Master!
Creating a Multi-Filter Function to Filter Out Multiple Attributes Using Javascript
Reverse an Array in JavaScript
.reverse() with .slice()
.reverse() with .spread()
.reduce() and .spread()
.reduceRight() and .spread()
Code Recipe: How to Reverse an Array in JavaScript
How to Reverse Array Without Mutating Original Array
Using slice and reverse
Using spread and reverse
Using reduce and spread
Using reduceRight and spread
Using push
Demystifying the Mysteries of sort() in JavaScript: when sort doesn’t sort
More JavaScript Array Tips: Replacing and mapping entries
Replacing Specific Value From an Array
Map Array Entries From One Value to Another
The Fastest Way to Find Minimum and Maximum Values in an Array in JavaScript
Function.prototype.apply()
With very large arrays, the for loop is fastest by far, with .apply() coming in second, .sort() and .reduce() tied for third, and spread dead last.
Chaining
Clone
How to Deep Copy Objects and Arrays in JavaScript
Deep copy with lodash
Deep copy with Ramda
Reduce
Speed Up JavaScript Array Processing
RxJS Transducers
Converting Object to an Array in JavaScript
Ancient times -- Loop
ES6 — Object.keys
ES2017
Object.values
Object.entries
Object.entries + Destructuring
Convert Iterables to Array using Spread in JavaScript
String
Set
Map
NodeList
Array.from vs Spread
5 Anti-Patterns to Avoid When Working With Collections in JavaScript
Prematurely Passing Functions as Direct Arguments
Relying on the Ordering of Iterator Functions Like .Map and .Filter
Optimizing Prematurely
Relying on State
Mutating Arguments
Destructuring
Destructuring Arrays in JavaScript
Grabbing the First Element
Grabbing All Of The Elements
Grabbing Non-Sequential/Out Of Order Elements
Using the Spread Operator
Array Destructuring from an Object
Array Destructing from a Function
Write Cleaner JavaScript with These Destructuring Techniques
Loop
Controlling Your JavaScript Program’s Workflow With Loops and Branches
For of
Use `for…of` to Loop Through Your JavaScript Arrays: A simpler way to iterate over arrays
For in
New Ways to Iterate Through Properties of an Object
Object.keys (ES5.1)
Object.values (ES2017)
Object.entries
Reflect.ownKeys (ES6)
3 Reasons Why You Shouldn’t Use “for…in” Array Iterations in JavaScript
Problem #1: Undefined Order
Problem #2: Extended Arrays
Problem #3: Custom Properties
For in vs. For of
RegExp (ES3)
Read This If You Don’t Know Enough About Regex: Learn the basics of one of the hardest things to learn as a programmer
A Practical Guide to Regular Expressions (RegEx) In JavaScript
The 3 Deadliest Sins of Form Validation: Why You Probably Shouldn’t Validate an Email Address with Regex and Other Deadly Sins
Email Addresses
validator.js
Passwords
Phone Numbers
JavaScript Form Validations Can Be a Nightmare for Users
Stop Throwing Errors When Your User Is Typing
Avoid Showing Consolidated Error Messages at the Top or Bottom of the Form
Show Error Messages Then and There
Remove Existing Error Message(s) When the User Starts Typing Again
Don’t Blame Your Users, Guide Them
Provide an Option to Clear or Reset Form Errors
Mastering custom validation in JavaScript : How to leverage RegExps for processing user inputs
6 Handy Regular Expressions Every Front-End Developer Should Know
The 3 Most Useful Regexes for Front End Developers
Valid Email Regex
Password Strength
Dates (YYYY-MM-dd)
Modern Regular Expression for Web Developers: 4 Techniques You Didn’t Know
How To Easily Understand Any Regular Expression In The World
Error Handling (ES3)
Let’s Clean Up: Ugly Try-Catches in JavaScript!
no-try
JavaScript Clean Code: Error Handling
Exceptions are Better than Return Codes
Write Try-Catch-Finally
Don’t Ignore Caught Errors
Don’t Ignore Rejected Promises
Providing Context with Exceptions
Guard Clauses
Stop Using Else in Your Programs: A practical introduction to guard clauses
Scope
Local scope
Global scope
What are the types of scope?
Global and Local
Lexical
Block
Public and Private
JavaScript’s Scope : Understanding Global and Local Scope & the Scope Chain
The Difference Between Function and Block Scope in JavaScript
The difference between var, let and const variables
Understanding scope
How Variable Declarations Can Determine the Life or Death of Cats in JavaScript: When scopes matter and Schrodinger’s theory doesn’t apply
Scoping in JavaScript For Loops: let vs. var inside your loop
Execution Context and Stack
Understanding Execution Context and Execution Stack in Javascript
What is the Execution Context & Stack in JavaScript?
What is the Execution Context?
Execution Context Stack
Execution Context in Detail
A Word On Hoisting
This
How to understand the keyword this and context in JavaScript
What Is “This”? — Using Call, Apply, and Bind Methods in JavaScript
A deep dive into this in JavaScript: why it’s critical to writing good code.
Removing JavaScript’s “this” keyword makes it a better language. Here’s why.
A Guide to ‘this’— One of the Least Understood Parts of JavaScript
Demystifying The Keyword This In JavaScript
Why does the keyword this exist in the first place?
Global Reference
How Was The Function Invoked?
Free Function Invocation
Method Invocation
Explicit Binding: apply/ call/ and bind
How and Why to Use Call, Apply, and Bind in JavaScript
Methods Hard-Coded Into Individual Objects
Execute Functions on Objects With “call”
Execute Functions on Objects With “apply”
Execute Functions on Objects With “bind”
JavaScript Under The Hood Pt. 4: Bind(), Call(), and Apply()
Understand JavaScript more deeply by writing a bind function
Function Borrowing in JavaScript
Function borrowing allows us to use the methods of one object on a different object without having to make a copy of that method and maintain it in two separate places.
It is accomplished through the use of .call(), .apply(), or .bind(), all of which exist to explicitly set this on the method we are borrowing.
Constructor Binding
JavaScript — The “this” key word in depth: Follow these 5 rules to determine what “this” is bound to
Is it an arrow function?
Was the function called with new?
Was the function called with call / apply or bind?
Was the function called as an object method?
Is strict mode on?
default case
The ‘this’ keyword: Illustrative JavaScript Doodle
How To Access “this” Inside a JavaScript Callback Function
The “self” pattern
Explicitly setting “this” (bind)
Arrow functions
The Keyword ‘this’ in JavaScript Explained With Examples **
In a method, this refers to the owner object.
In a function, this refers to the global object.
In a function, in strict mode, this is undefined.
Alone, this refers to the global object.
In an event, this refers to the element that received the event.
Methods like call(), and apply() can refer this to any object.
Let / Const (ES6, ES2015)
Understanding var, let & const in JavaScript — ES6
let instead of var
Const
Performance
How to improve JavaScript Performance
First comes Detecting Problems
Variables Scope
Code Light and Small
Avoid Unwanted Loops
Minimize DOM access
Asynchronous Programming
Event Delegation
Gzip compression
Boost performance by caching object
Limiting memory Usage
Delay loading of JavaScript
NO Memory Leaks
Use Various Optimizations
Do You Write Better JavaScript? : Being a Performance Conscious Developer
6 Potential Optimizations in Your JavaScript Project
Script Size
HTTP Roundtrips
DOM Access
Memory Leaks
Code Alternatives with Better Performance
Micro-optimizations
8 Tips to help you better optimize your JavaScript algorithms.
XOR的範例有bug
13 Tips to Write Faster, Better-Optimized JavaScript
Do It Less
Remove Unnecessary Features
Avoid Unnecessary Steps
Do It Less Often
Break Out of Loops As Early As Possible
Pre-Compute Once Wherever Possible
Order Code to Minimise the Number of Operations
Learn Big O Notation
Do It Faster
Prefer Built-In Methods
Use the Best Object for the Job
Don’t Forget About Memory
Use Monomorphic Forms Where Possible
Avoid the ‘Delete’ Keyword
Do It Later
Use Asynchronous Code to Prevent Thread Blocking
Use Code Splitting
3 JavaScript Performance Mistakes You Should Stop Doing
Looping Over an Array
the good old for loop (and also while) provides the best performance by far
Duplicating an Array
when duplicating 10k arrays of 10k random items, it is faster to use the old school solutions
Iterating Objects
How to increase your frontend app’s performance — 5 coding tips
Use objects/maps for lookups instead of arrays
Use “if” conditions instead of catching exceptions
Use as few loops as you can
Use basic for loops
Use built-in DOM functions
5 JavaScript Tips to Make You a Better Programmer
Use .map or .forEach instead of for Loops
Use const by Default
Avoid Nesting Closures
Avoid Nested ifs
Use Variables Instead of Complicated if Clauses;
7 Tips To Write Efficient and Performant JavaScript Code
Mind the LocalStorage and SessionStorage
Use the Observer Web APIs
Embrace the Return Early Pattern
Master Async and Defer
Defer Non-Essential Tasks
Optimize your Animations
Keep an Eye on Memory
minification
Google Closure Compiler
Improve Page Load Performance With These Different Script Loading Techniques
Problem With the Normal Way of Loading JavaScript
Place the script Tag at the Bottom of the Page
Add async Attribute Within the script Tag
Add defer Attribute Within the script Tag
Deep Dive into Page Lifecycle API
As the name suggests, the Page Lifecycle API exposes the web page lifecycle hooks to JavaScript. However, it isn’t an entirely new concept. Page Visibility API existed for some time, revealing some of the page visibility events to JavaScript.
GPU
Memoization
Understanding Memoization in JavaScript to Improve Performance
Optimize the hell out of your Javascript programs with Memoization.
Memoization: Speed up your code by storing expensive calculations.
Implementing a reusable memoization function in JavaScript.
Want To Build Faster Web Apps? Use JavaScript Memoization : with p-memoize library
A Beginner’s Guide to Memoization with JavaScript
Libraries for Memoization
Moize
Lodash
Underscore
Memoize Immutable and more.
Three Easy Ways to Improve Web Performance
Code Splitting, the PRPL pattern, and Lazy Loading
A lazy-load util function you will get addicted to
Lazy-load : a weapon to reduce the load time
Dynamic import with async/await
The Intersection Observer API
Spread syntax vs Object.assign()
For loop vs Reduce
For vs While vs Do while
JavaScript Best Practices — Performance
Reduce Access to Variables and Properties
Fastest Way to Loop Through Variables
Reduce DOM Access
Reduce DOM Size
Don’t Declare Unnecessary Variables
Defer the Loading of Scripts
8 Essential Tips To Make Your JavaScript Code Perform Faster
Minimize accessing the DOM
Remove unused code and dependencies
Call APIs Asynchronously
Avoid using Global Variables
Profile Your Code and Remove Memory Leaks
Utilize the power of Caching
Minify your code
Be cautious with Loops
Tips for improving JavaScript performance that your users will love
Use local variables
Use browser cache
Caching the DOM
Avoid recursive calls
Use XMLHttpRequest, Fetch or similar
Implement Event Delegation
Minimize and combine your code into modules
Use Top Level Await feature
Be cautious with adding unnecessary dependencies
Use web workers for intensive work
Use a Javascript file bundling tool
Tools to detect problems
Performant JavaScript Best Practices
Reduce DOM Manipulation With Host Object and User’s Browser
Minimize the Number of Dependencies Our App Uses
Poor Event Handling
The Secrets of JavaScript Object for Performance Optimization
Top JavaScript Code-Tuning Techniques
Stop Testing When We Know the Answer
Order Tests by Frequency
Substitute Table Lookups for Complicated Expressions
Unswitching
Jamming
Jamming is combining 2 loops that operate on the same elements.
Unrolling
Unrolling is separating the cases of the loop into their own code.
Minimizing the Work Inside Loops
If there’s less code inside the loop body, then it should perform faster.
Therefore, we should try to make our loops simple to make them perform faster. Simpler loops are also easier to read.
Template Literals / Backticks
String Template Literals: JavaScript ES6 Feature Series (Pt 5)
“Double Quotes” vs ‘Single Quotes’ vs `Backticks` in JavaScript
The real difference between single quotes (‘ ’) and double quotes (“ ”) in JavaScript
Backtick (` `) literals have 3 big advantages:
Easier string concatenation (“variable interpolation”)
"string "+variable becomes `string {variable}`
No need to escape (\) single or double quotes
"\"Hello World!\"" becomes `"Hello World"`
Multi-line code without new line character (\n)
"Hello\nWorld!" becomes `Hello
World`
Don’t forget about JSON
JavaScript Object Notation (JSON), the lightweight data storage format, only allows double quotes.
The 3 advantages of backtick literals (``) in JavaScript
String concatenation (aka variable interpolation)
Cleaner code, less escaping with \
Multi-line code
Are backticks (``) slower than other strings in JavaScript?
The speed of string literals in JavaScript
Does Babel Compile Backticks (``) to Quotes and Does That Make JavaScript Code Faster?
Template Literals in JavaScript: The Complete Guide
Expressions
Functions and parameters
Multiline strings
Tagged template literals
How to use Tail Call Optimizations in JavaScript
What is TCO optimization?
Algorithms & Data Structures
At a high level, there are basically three types of data structures.
Stacks and Queues are array-like structures that differ only in how items are inserted and removed.
Linked Lists, Trees, and Graphs are structures with nodes that keep references to other nodes.
Hash Tables depend on hash functions to save and locate data.
8 Common Data Structures in Javascript
Stack
Queue
Linked List
Set
Hash table
Tree
Trie (pronounced “try”)
JS: Implementing Auto-complete
A well-known data structure used for searching and matching strings is a Trie Tree.
Graph
Adjacency List
Adjacency Matrix
Here Are the Most Common JavaScript Algorithms and Data Structures
初學者學演算法|談什麼是演算法和時間複雜度 (not in Javascript)
[演算法] Big O Notation & Time Complexity (Javascript)
A Simplified Explanation of the Big O Notation (Javascript)
Introduction to Big O Notation (in JavaScript)
O(1): “Constant Time”
O(n): “Linear Time”
O(n²): “Quadratic Time”
O(log n): “Logarithmic Time”
Sorting
Optimising JavaScript Array Searches: Benchmarked
Here are the method times sorted by the fastest in seconds:
Index Search: 23.794
indexOf: 40.92
forLoop: 62.869
forEach: 178.479
If the loop was going to be used only once, then the indexOf method would be the fastest as the index build time would add to the search time.
Binary search
JavaScript Object Notation (JSON)
Understanding JSON in JavaScript (native Javascript, fetch & jQuery)
A Guide to JSON and How It’s Handled in JavaScript: An overview of JSON and the methods you can use to manipulate and transform it
JavaScript Fundamentals: An Introduction to REST APIs
What is a REST API?
RESTful Architecture
REST in action
Working with REST data
5 Secret features of JSON.stringify()
The second argument (Array)
The second argument (Function)
The third argument as Number
The third argument as String
The toJSON method
JSON — parse() and stringify() in JavaScript : A detailed guide to JSON, and the use of parse() and stringify() in JavaScript
URL
Dealing with URL query parameters in Javascript using URLSearchParams
Javascript URL Object : Stop writing error prone URL strings and level up with a Javascript object for manipulating URLs in code.
Clean code
7 JavaScript coding standards for readability & consistency
Use async-await over promises
Variables
Use const & let over var
Avoid using global variables
Naming variables
API Calls
Imports
Use named imports over default imports where possible
Try and order your imports alphabetically
Dom Manipulation
Query selecting
Use CSS classes over adding styles
Functions
Use ES6 arrow functions where possible
Naming functions
3 JavaScript Refactoring Techniques for Clean Code
Extract Function
Introduce Parameter Object
Combine Functions into a Class
Clean Code Applied to JavaScript (Part 1)
Introduction
Code smell and refactoring
Another interesting term is technical debt
Before You Start
Readable for humans
Develop in English
Teamwork
Clean Code Applied to JavaScript — Part 2: Variables
Use intention-revealing names.
Use pronounceable names.
Don’t use the variable’s type in the name.
Use the same vocabulary for the same variable’s type.
Don’t add unneeded context.
Don’t use magic numbers and strings.
Clean Code Applied to JavaScript — Part 3: Functions
Use default arguments instead of short circuiting or conditionals
Function arguments (two or fewer ideally)
Avoid side effects — global variables
Avoid side effects — objects mutables
Functions should do one thing
Functions should only be one level of abstraction
Favor functional programming over imperative programming
Clean Code Applied to JavaScript — Part 4:Comments
Only comment things that have business logic complexity
Don’t have journal comments
Avoid positional markers
Clean Code Applied to JavaScript — Part 5: Exceptions
Prefer exceptions in favor of returning error codes
Don’t ignore caught errors
Don’t ignore rejected promises
Use the exceptions hierarchy
Provide context with exceptions
4 Ways You Can Get Rid of Dirty Side Effects for Cleaner Code in JavaScript
Write More Robust JavaScript: 7 Best Practices
Use factory functions
Add methods on the .prototype when writing constructors
Use the conventional .type property when differentiating
Use TypeScript
Write tests
Keep functions as simple as possible
Always consider using try/catch when using JSON.parse or JSON.stringify
4 Key Principles to Writing Readable and Efficient JavaScript Code
Write code in the style of a strongly typed language
Reduce unnecessary scope lookups
Use ES6 features to simplify the code
Grammar style
Do This Not That, JavaScript Edition
Associative arrays (using Map object instead)
Old-fashioned concatenation (using template literals instead)
Comparing case without considering locales
Iterating over strings (using matchAll, map instead)
Timing performance with Date (using Performance API instead)
Testing strings for truthy values
Weak random numbers (using Crypto API instead)
JavaScript Best Practices for Writing More Robust Code — Clean Code
Keep Code Organized
Don’t Write Clever Code
Splitting Code in Ways That They Can Be Tested Easily
JavaScript Best Practices for Writing More Robust Code — Functions
JavaScript Best Practices for Writing More Robust Code — Value Checks
JavaScript Best Practices for Writing More Robust Code — Checking for Unexpected Values
JavaScript Best Practices — Naming, Style, and Comments
Easy, Short, and Readable Names for Variables, Functions, and Classes
Avoid Global Variables and Functions
Keep a Strict Coding Style
Comment When Needed
Adopting Better JavaScript Code Style — Basic Syntax and Async
Adopting Better JavaScript Code Style — Error Handling and Comparisons
Tools for Consistent JavaScript Code Style
Use Prettier to format your code on save.
ESLint will analyze your codebase for issues.
Husky will run these tasks before each commit.
JavaScript Code Styling Best Practices — If’s and Mixing Characters
JavaScript Clean Code — Functions
Small Functions
Blocks and Indent
Do As Little As Possible
One Level of Abstraction
JavaScript Clean Code — Function Parameters and Side Effects
JavaScript Clean Code — Vertical Formatting
Why do we Need to Format Code?
Vertical Formatting
Blank Lines
Vertical Density
Vertical Distance
Variable Declarations
Instance Variables
Dependent Functions
Related Code
Vertical Ordering
JavaScript Clean Code — Horizontal Formatting
Horizontal Formatting
Horizontal Openness and Density
Horizontal Alignment
Indentation
Breaking Indentation
Team Rules
All these things can be done automatically by programs like ESLint, JSLint, and Prettier. They can be used with the default rules or configured with other rules like the Airbnb linting rules for ESLint.
JavaScript Clean Code: Concurrency
Use Promises Instead of Callbacks
Async/Await Is a Cleaner Syntax for Chaining Promises
JavaScript Clean Code — Objects and Classes
Use Classes Over Constructor Functions
Using Getters and Setters
Keeping Members Private
Chaining Methods
Preferring Composition Over Inheritance
JavaScript Clean Code: Error Handling
Exceptions are Better than Return Codes
Write Try-Catch-Finally
Don’t Ignore Caught Errors
Don’t Ignore Rejected Promises
Providing Context with Exceptions
在文章的回應裡,有人認為try catch跟goto一樣,應該盡量避免
JavaScript Clean Code: Emergent Design: A look at the 4 principles of emergent design
Running all the tests.
Removing duplication.
Expressing the intent of the programmer.
Minimizing the number of classes and methods.
JavaScript Clean Code — Quick Best Practices
Strong type checks
Variables
Functions
Conditionals
ES Classes
Avoid Using Eval
Use JSLint
Avoid In General
19 simple JavaScript coding standards to keep your code clean
Clarity Is King When Writing Code
Naming
Commenting
Conditionals
Loops
Functions
Testing
5 Hacks to keep in mind for writing a clean JavaScript code
Make Code Readable
Use Meaningful names
Avoid Mental Mapping
Functions do one thing
Use Strong Type Checks (Use === instead of ==)
5 Best Practices for writing clean JavaScript
Principles
KISS
DRY
TED
SOLID
Naming Conventions
The Use of Conditionals
The Use of Functions
Don’t Overdo Comments, Use it Wisely
Who Else Wants to Write Clean JavaScript Code? : 7 Tips to Make Your Coworkers Fall in Love With Your Code.
JavaScript Best Practices — More Code That Shouldn’t be Added
No Implicit Global Variable Declaration
No Implied eval() Code
No this Keywords Outside of Classes or Class-Like Objects
Disallow Iterator
Disallow Labeled Statements
Stop using the ‘else’ keyword in your code
Use polymorphism to handle complex conditional cases, making the code more clear like State Pattern.
Code Smells in JavaScript Classes
Lazy or Freeloader Class
Excessive Use of Literals
Cyclomatic Complexity
Orphaned Variable or Constant Class
Data Clump
Look for Code Smells in JavaScript
Common Code Smells
Duplicate code
Code That’s Too Complex
Shotgun Surgery
Large Classes
JavaScript Code Smells — Functions
Too Many Parameters
Excessively Long Identifiers
Excessively Short Identifiers
Excessive Return of Data
Excessively Long Line of Code
Code Smells in JavaScript: We look at feature envy and intimate classes
Shorthand
JavaScript Shorthand Coding Techniques
Switch Case Statements
IF Checks Assignment
Short IF statements
If true … else case
Using Lookup Tables
For Loop
Empty Check, Undefined Checks, or Null Checks
Function Calling
Spread Operator
Using Arrow Functions
Combining of Arrays Into an Object Literal
Passing of Function arguments
Do More With Less JavaScript — Clean & Simple Shorthand: Let’s not overcomplicate things. Improve readability with shorthand alternatives to common JavaScript expressions.
Handy JavaScript Shorthands You May Have Missed
Ternary Operator
Setting Default Value
Shorthand for Declaring Multiple Variables
If Truthy Shorthand
For…Of Loop Shorthand
Array.forEach
Decimal Base Exponents
Digit Separators
Object Property Shorthand
Arrow Functions
Default Parameter Values
Even More JavaScript Shorthands
Object-Properties Assignment
IndexOf and findIndex
Object.entries()
Object.values()
Getting Characters of a String Literal
Compact Alternative to Switch
Replace ifs With indexOf or includes
JavaScript Shorthand Coding Techniques — Part 1
The Ternary Operator
Short-circuit Evaluation
Declaring Variables
If Presence
JavaScript For Loop
Short-circuit Evaluation
Decimal Base Exponents
Object Property
Arrow Functions
Implicit Return
Default Parameter Values
Template Literals
Destructuring Assignment Shorthand
JavaScript Shorthand Coding Techniques — Part 2
Multi-line String Shorthand
Spread Operator
Mandatory Parameter
Array.find
Object [key]
Double Bitwise NOT
Exponent Power
Converting a String into a Number
Object Property Assignment
Bitwise IndexOf
Object.entries()
Object.values()
JavaScript can do that? (shorthand techniques)
Convert a value to a boolean
Convert numeric strings and null to numbers
Convert a value to a string
Concatenation
Arrays & Objects with the Spread operator
IndexOf() or includes()
if() condition
Experimental and limited availability
30 Awesome JavaScript Shorthand Techniques That You Should Know
Stop Writing JavaScript Like This : 10 Ways To Write Better JavaScript Code
Advanced JavaScript
Deep Dive Into Javascript : Heap, Event Loop & Call Stack
Functional JS
Functional JavaScript — All the Important Concepts in One Article
Understanding the Philosophy of Functional Code
Securing your Data — Understanding Immutability
Focusing on What Matters — Pure Functions
Transforming Data — Map, Reduce and Filter
Swallowing Functions — High Order Functions
Looping the Functional Way — Recursion
Functions That Aren’t Mutating
Currying
Miscellaneous
More Tools for Functional JavaScript
Introduction to Functional Programming in JavaScript
Pure Functions
Limiting State Mutations (with Immutability)
Side Effects
Introduction to functional JavaScript programming
The main concepts
What object-oriented programming is about
What functional JavaScript programming is about
Pure functions
Built-in array functions
Map
Reduce
Function composition
Point-free notation
Compose
Currying
How to Add Functional Programming to any JavaScript Project
Curry
Compose and/or Pipe
Map
How to Start Thinking Functionally in JavaScript
Functional programming is a style of programming that requires thinking about your problems at a more abstract level.
Most of us learn to program at a procedural, imperative level so making the transition can be difficult when you’re just getting started.
Code written in a functional style is generally easier to reason about and easier to read.
Functional code can be easier to maintain and modify.
Taste of Functional Programming in JavaScript
Functional Programming (FP) is based on a simple idea of constructing programs using pure functions. A pure function returns the same value for the same arguments, its evaluation has no side effects.
An Introduction to Functional Programming Style in JavaScript
Functional programming paradigms in modern JavaScript: Partial Application
Discover Functional Programming in JavaScript with this thorough introduction
Functional Programing For Your Everyday JavaScript Developer
Lenses: Composable Getters and Setters for Functional Programming
Functional Programming in JavaScript: Introduction and Practical Examples: From pure functions and combinators to compose and containers
Concept 1. Pure Functions
Concept 2. Combinators
Why Do Functional Programmers Shy Away From Loops?
Why Are Pure Functions and Combinators Useful?
Introducing the compose Function
Building a compose Function
Debugging compose
The tap Function
The trace Function
Containers
Pure function
What Is a Pure Function in JavaScript?
Same inputs always return same outputs
No side-effects
filterMap in JavaScript, efficiency for functional programming
Function chaining
Function composition
Introduction to Algebraic Structures — Functional Programming for JavaScript Developers
Functional Programming Series(1): What Is a Semigroup?
Magma、Semigroup
The Single Most Important Feature of JavaScript: functions are objects
In JavaScript, functions are objects. And in JavaScript, objects have properties consisting of key-value pairs. As follows, JavaScript functions have properties that consist of key-value pairs.
Module
Use Modules to Build a Modular JavaScript App
Exports and Imports
Default Exports
Renaming Imports and Exports
Dynamic Module Loading
Understanding ES Modules in JavaScript
Existing Module Systems
CommonJS
Asynchronous Module Definition (AMD)
Universal Module Definition (UMD)
What are ES Modules
ES Modules Browser Compatibility
ESModules in JavaScript: 3 Minute Guide #04
Name Export/Import
Default Export/Import
Rename Export/Import
List + Rename Export/Import
Understanding ES6 Modules (Import / Export Syntax) in JavaScript
StyleSheet
How JavaScript works: Under the hood of CSS and JS animations + how to optimize their performance
All You Need To Know About CSS-in-JS
Most Popular CSS-in-JS Libaries
Styled Components
JSS-React
Glamorous
Radium (Caveat: Uses Inline Styles)
Aphrodite
Styletron
Write plain CSS while reaping the benefits of CSS-in-JS
Nyan CSS
Screen lock challenge for Web application made easy
Using pure JavaScript API designed for modern browsers.
Using complete CSS code.
giving user a message to use in portrait mode.
How to Make Your Website Themeable With CSS Variables: Give your website a completely new feel with themes
Dynamically Import CSS: Lazy load CSS with the help of dynamic import() demonstrated in a Stencil Web Components.
JavaScript dynamic import() .
A Really Cool New Exploration in CSS-in-JS That I’m Keeping My Eyes On
@compiled/css-in-js
Stop duplicating constants between JS and CSS
CSS Variables
Programmatically Generate Images with CSS Painting API : A JavaScript API for dynamic image creation coupled with CSS
Introducing Variabless — JS & CSS A Match Made in Heaven : ngneat/variabless
API / HTTP request
Here are the most popular ways to make an HTTP request in JavaScript
Ajax
jQuery methods
fetch
Axios
Angular HttpClient
Comparing different ways to make HTTP requests in Javascript in 2020
Fetch is the new standard and is supported by new versions of Chrome and Firefox without using any additional library.
It is recommended to dedicate some time to look at the characteristics of Axios, SuperAgent, or the rest of the libraries as they all have proper documentation, are easy to use, and their learning curve is not too large. For some instances, they offer features that do not have Fetch.
(In response) Axios use XMLHttpRequest under the hood and jQuery.ajax() wraps XMLHttpRequest too. The native way to do request is with Fetch or directly with XMLHttpRequest/XmlHttpRequest2.
JavaScript Fundamentals: Fetching Data from a server
AJAX
Fetch
An absolute Guide to JavaScript Http Requests : XHR() vs. Fetch() vs. Axios()
Axios
Avoiding Code Duplication by Adding an API Requests Definition Layer in JavaScript
Setting up Axios Interceptors for all HTTP calls in an application
Why JavaScript Developers Should Prefer Axios Over Fetch : Backward-compatibility, monitoring upload progress, and more
JavaScript Fundamentals: Understanding APIs
Browser APIs
Third Party APIs
** API 這部分需要重新整理 **
JavaScript Web API’s That Every Developer Should Know
There are three types of API’s Web API, Browser API, Server API. (錯誤! 應該是Web API包括Browser API及Server API)
There are 6 types of JavaScript Web API (Web APIs ) :
Form API
Web Form API or Javascript validation API allows to user validate inputs with different properties and two methods.
History API
Web History API helps manage your web page history
Fetch API
Fetch API helps to make the HTTP request to the webserver.
A practical ES6 guide on how to perform HTTP requests using the Fetch API
A “suggest-as-you-type” search widget in 57 lines of JavaScript code.
Fetch() This: How To Make Simple Fetch Requests More Efficient in JavaScript
That data looks so fetching on you: Understanding the JS Fetch API
Storage API
Geo Location API
Web Worker API
Web APIs that you should use for a Better UX: Simple and useful web APIs you should be using now
Map API
Top Maps API and Libraries in JavaScript
Leafletjs
Openlayers
Mapbox
Google Maps API
Datamaps
Bing Maps
ArcGIS
Zeemaps
Cache
BOM (Browser Object Model)
Understanding The Browser Object Model in JavaScript : Learn about the JavaScript BOM with practical examples
The window object
The properties and methods of the object window can be written without the prefix window .
The window screen
The window location
The window history
Popup boxes
Using JavaScript Objects Built into Browsers
The Browser Object Model
The Navigator Object
Check a user’s network connectivity using JavaScript
This involves the JavaScript navigator API and an eventListener on the window object that will help us keep track of the user’s connectivity.
The Window Object
Creating Browser Notification in JavaScript
Check if the browser supports Notification
Ask the user for permission to show the notification.
Once user grant permission, create a Notification object
Show the notification with your custom message
Web Storage
Cookies, local storage, session storage
Cookies vs Local Storage vs Session Storage
Cookies are the oldest and most common way of storing data. A cookie is basically some text-based information. We can set an expiration time for the cookie that is being set. There’s only 4KB storage space allowed for the entire cookie data. Cookies are advantageous as they work in older browsers as well. A cookie can be accessible to every window in the browser.
The Local Storage is a type of Web storage which like cookies is accessible on all windows in the browser. When it comes to the storage capacity, it can store upto 5–10 MB, which is much better when compared to cookies. And the values set in local storage never expires until and unless we manually remove them.
The Session Storage has a lot of similarities to Local Storage, but the storage size is limited to 5MB. Also, the values stored gets automatically removed from the browser when you close the active tab. As the name suggests, the values are only available for that session.
Cookies vs LocalStorage — Organized Answer for your interview
SessionStorage and LocalStorage: A UX/Security Comparison
LocalStorage data get shared across browser windows and tabs
4 Ways to Communicate Across Browser Tabs in Realtime
Local Storage Events
Broadcast Channel API
Service Worker Post Message
Window Post Message
SessionStorage data is independent of the other tabs or windows
Security Considerations
Origin, protocol, and subdomain specific storage objects
Both Storage objects are Domain Specific
Both Storage objects are Sub-Domain Specific
Both Storage objects are Protocol Specific
Vulnerability to Cross-Site Scripting (XSS) Attacks
User Experience
Use Storage objects for Browser Caching
How Performance gets affected
How users can Clear Storage
JS30-Day15-LocalStorage (新手也能懂的JS30系列 第 15 篇)
8 JavaScript Libraries for Better Handling Local Storage
crypt.io implements secures browser storage with the Standford JavaScript Crypto Libraries. When working with crypto.io, you have three storage options: sessionStorage, localStorage, or cookies.
DOM (Document Object Model)
What’s the Document Object Model, and why you should know how to use it.
What’s Best: innerText vs. innerHTML vs. textContent
使用innerHTML要小心,如果innerHTML的內容是使用者輸入的內容,可能會有資安上的疑慮!
Selecting elements
Single element
Multiple elements
Going up the DOM tree
Adding elements
Moving elements
Replacing elements
Removing elements
Create an element from raw HTML
Inspecting the DOM
5 Tips for Manipulating the DOM
Knowing your selectors: querySelector( ), querySelectorAll( ), getElementsById( ), getElementsByClassName( )
console.dir
Traversing the DOM with parentNode and ChildNodes
Data Set
Delegation
Exploring the JavaScript Window Object: document.implementation and document.links
windw.document.implementation
windw.document.links
What function window, document, undefined — window, document really means
DOM Traversal
Traversing the DOM with Vanilla JavaScript : Specifically using .matches() and .closest()
Explore JavaScript DOM Traversal : Let’s find out how to traverse using parent, child, and sibling nodes.
Modern alternatives to innerHTML and appendChild()
append() is a convenient alternative to appendChild()
replaceChildren() is a convenient alternative to innerHTML and append()
Dialog
HTML <dialog> Tag (HTML 5)
Browser APIs
How to make your web apps work offline: The power of JavaScript and browser APIs
Task 1 — Cache Static Assets
Task 2— Cache Dynamic Assets
Task 3 — Build an Optimistic UI
Task 4 — Queue User Actions for Resync
6 Browser APIs You Need To Know As A Front End Developer
Fetch API
Canvas API
Fullscreen API
Clipboard API
Payment Request API
Geolocation API
Better Data Management With JavaScript Modern Browsers APIs
Fetch API
Cache API
Device Memory API
Storage persistent
LocalForage API
JavaScript APIs Every Web Developer Should Know
Device Memory API
Storage persistent
Cache API
Fetch API
LocalForage API
JavaScript Sanitizer API: The Modern Way to Safe DOM Manipulation
Cookie
CORS
How CORS (Cross-Origin Resource Sharing) Works?
How CORS Works
CORS Preflight Request
How to Enable CORS (server side/Node.js)
How and Why You Should Avoid CORS in Single Page Apps
Learn how to avoid CORS by using the proxy configuration in frontend development server.
GraphQL
Server
JWT (JSON Web Tokens)
jQuery
JAMstack
An introduction to the JAMstack: the architecture of the modern web
JAMstack here stands for:JavaScript+API+Markup
Your Next App May Not Have a Back End: A look at the JAMstack and what could be next
RedwoodJS: 5 Features that Make it Unique among JAMstack Frameworks : A full-stack framework that combines, React, GraphQL, and Prisma
JS Delivery
Notification
Observer API
Observer APIs in JavaScript — Part I
MutationObserver
IntersectionObserver
Javascript Intersection Observer : Re-write your scrolling functions for better performance.
Observer APIs in JavaScript — Part II
ResizeObserver
PerformanceObserver
Push API
Shape Detection API
Router
RxJS
RxJS: A Simple Introduction: Introducing ReactiveX and the observer pattern for Javascript applications
ReactiveX: Asynchronous, Event-Based Programming
The state of RxJS
RxJS and the Observer Design Pattern
Working with Operators
Working with Subjects
A note on Schedulers
Observerables
5 Awesome RxJS Observables and Operators That Are Often Overlooked: Pluck, Defer, FromEvent, and more
Test
An Overview of JavaScript Testing in 2019
Unit and Integration Tests Framework
Jest, Mocha, AVA, Tape
In short, if you want to “just get started” or are looking for a fast framework for large projects, you can’t go wrong with Jest.
Functional Testing (UI Test)Tools
TestCafe, Cypress.io, Nightwatch.js, WebdriverIO
In short, if you want to “just get started” with a simple to set-up cross-browser all-in-one tool, go with TestCafe.
JavaScript Rising Stars / Test Framework
2018 Jest, AVA, Mocha, Jasmine, Tape
2017 Jest, AVA, Mocha, Jasmine, Tape
2016 AVA, Jest, Mocha, Jasmine, Tape
An Overview of JavaScript Testing in 2018
Use Jest for unit and integration tests and TestCafe for UI tests.
Top Javascript Testing Frameworks in Demand for 2019
Jest, arguably one of the most popular javascript testing framework with over 22,000 stars on github was built and is constantly maintained by the team at Facebook.
Mocha with over 16,000 stars on github is the most used javascript testing framework for years now. It is used with third party assertions, mocking and spying tools like chai or enzyme.
Jasmine is universally known as the testing framework that is officially recommended by Angular for developers to use, the Jest framework was built based on Jasmine. With over 14,000 stars on github Jasmine is one of the most popular frameworks for testing javascript, it is also one of the oldest too with the most resources and community support.
JavaScript: Debugging and Testing
Jasmine, Mocha, AVA, Jest, QUnit
Effective Javascript debugging: Memory leaks
Some examples of memory leaks
Globals
Observer pattern (Events)
Memory
5 Common JavaScript Memory Mistakes : Tips to avoid memory leaks in your web apps
TDD
Test Environment(Mocha、Jasmine、Jest、Karma)
Test structure (Mocha、Jasmine、Jest、Cucumber)
Assertion(Chai、Jasmine、Jest、Unexpected)
Creation, display, and watch test result(Mocha、Jasmine、Jest、Karma)
How to ace your JavaScript coding assignment round? — Part 2 : TDD
How to debug JavaScript applications and tests (Jest, Mocha, Jasmine, Karma)
describe/it
Jasmine is a behavior-driven development framework for testing JavaScript code
describe/it
BDD in JavaScript: Getting Started with Cucumber and Gherkin
End to end
Cypress
Passing variables between tests in Cypress : Testing business workflows end2end with cy.task()
Selenium and WebdriverIO
TestCafe
nock
Socket.io
Typescript Live Chat: React and Socket.io with RxJS Event Handling
What I learned about WebSockets by building a real-time chat application using Socket.IO.
Environment Variable
Lodash
Lodash (official site)
How to Deep Copy Objects and Arrays in JavaScript
Deep copy with lodash
Deep copy with Ramda
.setState() Not Working? Shallow Copy vs Deep Copy & Lodash
Shallow vs Deep Copies
Why It’s Important
The Fix — Lodash
var _ = require('lodash');
var newObject = _.cloneDeep(theObjectThatNeedsCloningHere);
More Lodash Features that are Available in Plain JavaScript
Curry
Partial
Eq
Add
Nesting Operators
At
Speed up your coding process using Lodash, save time writing the same old functions
_.sum
_.chunk
_.compact
_.concat
_.flattenDeep
_.head
_.tail
_.join
_.merge
How to Use Debounce and Throttle in JavaScript
Throttle and Debounce in Lodash
_.times
_.debounce
_.get
_.set
_.deburr
_.keyBy
Why You shouldn’t use lodash anymore and use pure JavaScript instead
Speed
Composition
Weight
Are We Ready to Replace Lodash?
_.debounce
_.pick
_.get
_.throttle
_.flatten
_.trim
Lodash Array Methods That Can Easily Be Implemented in Plain JavaScript
Creating our own Debounce Function
Debounce using lodash.
Debouncing in JavaScript : Sending a Request Only after the User Has Stopped Typing
JavaScript Utility Libraries : Comparison of JS, Ramda, and Lodash
Package
An abbreviated history of JavaScript package managers
Npm
Yarn
Pnpm
Workspaces
PnP
NPM
6 npm Commands Used by Highly Productive Developers
npm doctor
npm cache
npm link
npm ls
npm search
npm repo
10 things you should know about NPM
What is NPM
package.json
License
`scripts` in package.json
`— save` option
`— save-dev` option
package version
^ , < , ~ symbol for package version
`npm outdated` command
useful resource
Compare packages
Check the download trend of package
How to Analyze Your NPM Dependencies for Better, More Maintainable Code
How to Upgrade Dependencies in Your package.json
npm outdated
npm-check-updates
How To Delete All The Node_Modules Folders On Your Computer : Using npkill to clear up disk space
What Are NPM’s Optional Dependencies and When Should We Use Them?
Why You Should Think Twice Before Installing an npm Package or Module
What Really Gets Packaged? : Including and excluding files in your npm package
Bundler
Rollup
Parcel
Choosing the Right JavaScript Bundler in 2020: Why we’ve chosen Parcel for our microfrontend framework Piral
Snowpack
Why you should start using Snowpack : Fast and straightforward bundle-free build tool for modern web apps
Snowpack: A Modern, Lightweight Build Tool for Faster Web Development
Webpack
Webpack 101 : Empower your web projects with Modern Javascript
5 Methods to Reduce JavaScript Bundle Size
Code Splitting with Webpack
Using Webpack Plugins for Tree Shaking
Easy Way To Optimize Your Web App With Tree Shaking
The Webpack 4 release came with a way of notifying the compiler using sideEffect and Package.json to know the pure files in your project directly and know how safe it is to shake them.
Using Alternative Libraries and Removing Duplicates
Compressing Bundles
Using Production Mode in Webpack
Boost Your Productivity With These 6 Awesome webpack Plugins
Webpack 5 Module Federation: A game-changer in JavaScript architecture: Module federation allows a JavaScript application to dynamically run code from another bundle/build, on client and server.
Using Webpack Module Federation to Create an App Shell : Keep modules in sync across different web applications at scale
Why Frontend Developers Need to be Webpack Experts
Improve Developer Productivity
Get Better at Tree-Shaking
Using Code Splitting to Optimize App Loading Time
Supports Micro Frontends with Module Federation
Console
5 Ways To Use “Console” Object
Grouping lines of Console
Print object key value in the table form
Print only “if false”
Time of execution
Use different levels
Understanding JavaScript Console Methods
console.log
console.clear
console.warn
console.table
console.dir
console.group and console .groupCollapsed
console.count and console.countReset
console.assert
Console.error
console.time and console.timeEnd
console.trace
Playing with Javascript Console
console.log() / console.info()
console.warn()
console.error()
console.trace()
console.count()
console.time() — console.timeEnd()
console.group() — console.groupEnd()
console.table()
console.clear()
String substitutions
Console Design
How to use the JavaScript console: going beyond console.log()
JavaScript console is more than console.log()
console.warn() & console.error()
console.group()
console.table()
console.trace()
console.time()
console.clear()
console.dir()
Javascript Tips That Will Save Your Days — Part 3: Log Format
Boost your JavaScript Debugging Skills With These Console Tricks
Moving beyond console.log() — 8 Console Methods You Should Use When Debugging JavaScript and Node
A Helpful Alternative to console.log
console.table()
Things You Didn’t Know You Could Do With The Console in JavaScript
assert()
table()
time(), timeLog(), and timeEnd()
count() and countReset()
Useful hidden features in JavaScript Console (跟上面文章類似,但內容比較多一點)
.assert()
.table()
.time(), .timeLog(), and .timeEnd()
.count() and .countReset()
Advanced console.log Tips & Tricks
console.dir()
console.assert()
console.count()
console.table()
console.time() / timeLog() / timeEnd()
console.trace()
console.group() / groupEnd()
Bonus: CSS styling the console
Stop Using console.log() In JavaScript : There are better options
Using the JavaScript Console for More Than Just Simple Logging
5 Useful Browser Console Functions (Other Than Log)
console.assert()
console.count()
console.warn() / .error()
console.table()
console.time()
Stop doing this with console.log()
A better way to log multiple items
Why use lines when you can use tables?
Group grouped logs
Better warnings
Better error logging
Custom console styling
Time the speed of your functions
Better stack traces
10 Unknown Console Commands in JavaScript: 3 Minute Guide #05
Learn the Different Ways of Logging to the Web Browser Console
Alternative libraries for Console.log() for your next JavaScript Project
Console
Logdown
Consola
Ololog
Debugger
How to stop using console.log() and start using your browser’s debugger
5 Tips That’ll Improve Your JavaScript Debugging Skills and Save You Hours
Unravel Your Loops With Conditional Breakpoints
Break Using Advanced Expressions
Inspect Variables From the Watch Panel (Across Reloads)
Traverse the Call Stack to Get to the Root Cause
Pause Automatically on Exceptions
Productivity-boosting JavaScript debugger
Effectful Debugger
7 Must-Use Front-End Debugging Tools
Developer Tools in Web Browsers
Postman
CSS Lint
JSON Formatter & Validator
Sentry
JSHint
BrowserStack
Versioning
The Expand and Contract Pattern in JavaScript
Expand, Adapt and Contract
Service worker
How To Make Your Website Work Offline
Step 1: add a Service Worker
Step 2: enjoy!
Web worker
A Simple Introduction to Web Workers in JavaScript
Web workers let you do you do any time-consuming job in the background. The process is simple:
You create a web worker.
You tell the web worker what to do. (For example, crunch these numbers!)
You start the web worker.
When the web worker is done, it tells you, and your code goes from there. (For example, show the results on your page.)
What does a Worker do in JavaScript?
Synchronous Code
Asynchronous Code
Workers
Web Worker is a Web API. This means that a Worker can’t access or manipulate the DOMs at all.
相關工具
The brain-fatigued JavaScripter’s guide to modern frontend tooling in 2018
The most popular JavaScript tools you should be using
Build Tools
Transpilers: Babel、Typescript
Minifiers
Bundlers: Webpack、Browserify...
Put them all together
Static checking
Linters: JSLint、JSHint、ESLint
Code style checkers
Code formatters
Type checkers
Testing frameworks
Unit testing
Integration testing
Package managers
ESLint & Prettier
Javascript Linting and Formatting with ESLint, Prettier, and Airbnb
Keep Code Consistent Across Developers The Easy Way — With Prettier & ESLint
4-Step Guide to Setting Up ESLint & Prettier
Step 1. Installing Dev Dependencies
Step 2. Configuring ESLint
Step 3. Configuring Prettier
Step 4. Configuring Auto Format in Editor
Compare the Top 3 Style Guides and Set Them Up With ESLint
Standard vs. Google vs. Airbnb
How to ace your JavaScript coding assignment round? — Part 1 : Eslint
Error-Free Code is not just a dream after all | StandardJS 16.0
How to Make Your Team and Your JavaScript Project Better in 2019
Automatic Semicolon Insertion
JavaScript Obfuscator
Beautifytools
npm packages
javascript obfuscator
webpack-obfuscator
JavaScript Rising Stars
相關應用
Animation
How JavaScript works: Under the hood of CSS and JS animations + how to optimize their performance
How to create animated URLs with JavaScript : Easily Animating Characters & Emojis in URLs
WebGL
Understanding WebGL : Get to know the basics of WebGL by building a simple 2D plane
Audio
Authetication
6 JavaScript User Authentication Libraries for 2019
Passport JS
Auth0
Permit
Grant
Feathers authentication management
Just use Firebase Authentication (for small apps)
Authentication is hard. Let Google handle it for you.
Firebase Authentication
Authenticating HTTP Requests in Modern Web Apps: Ensure your users are authenticated using modern technologies like Axios, JWT, and TypeScript.
How To Securely Implement Authentication in Single Page Applications: Exploring OAuth, OpenID Connect, and their common security pitfalls
Passwords are Obsolete — How to Secure Your App and Protect Your Users
Everything you need to know about the `passport-local` Passport JS Strategy
Session based authentication is at the root of the passport-local strategy.
Basic HTTP Header Protocol
What a cookie is
What a session is
How the session (server) and cookie (browser) interact to authenticate a user
Checkbox
DataDrivenJS
Drag and Drop
Excel
Export Data Using the JavaScript && Tabulator
Tabulator is a great JavaScript library that allows us to create interactive tables in seconds from JavaScript Array, AJAX data source, HTML, or JSON formatted data.
File
How to Handle File Inputs With JavaScript
Access Selected File(s)
Handle Multiple Files
Dynamically Add a Change Listener
Get Information About Selected File(s)
Use Hidden File Input Elements Using the click() Method
Select Files Using Drag and Drop
Hardware
New Standards to Access Device Hardware using JavaScript : WebHID, WebNFC, and WebUSB have opened up new avenues to interact with user’s device hardware for web apps.
iFrame
Image
Base64 Encoding in JavaScript: Including upload an image using base64 in JavaScript
Browser Based Approach
The Javascript Approach
IndexedDB
Internationalization
Menu
PDF
Most Efficient Ways For Building PDFs Files With Backend and Frontend JavaScript
How to Convert HTML Tables into Beautiful PDFs
jsPDF shines when it comes to single-page content generated based on HTML shown in the UI.
pdfmake works best when generating PDF content from data rather than from HTML.
DocRaptor is the most powerful of them all with its simple API and its beautiful PDF output. But again, unlike the others, it is a paid service. However, if your business depends on elegant, professional document generation, DocRaptor is well worth the cost.
Security
How to Hide Secrets in Strings— Modern Text hiding in JavaScript
with StegCloak
7 Steps to Secure JavaScript in 2021
JavaScript Integrity Checks
Frequent Tests for NPM Vulnerabilities
Keep Minor and Patch Version Updates Enabled
Have Validations in Place to Avoid Injections
Always Keep Strict Mode On
Lint Your Code
Minify & Uglify Your Code
Speech
Timezone
Trait
Video
Visualization
How to Create a BI Dashboard Using a Pivot Table and a Charting Library
Flexmonster Pivot Table
Google Charts
How to create a mock-up real-time chart application using CanvasJS: Real-time API + ChartIO + CanvasJS = Professional Charts
Top 10 JavaScript Charting Libraries for Every Data Visualization Need
amCharts
AnyChart
Chart.js
Chartist.js
D3.js
D3.js — How to Make a Beautiful Bar Chart With The Most Powerful Visualization Library
Easier D3.js — Render C3 Charts With React Functional Components : Better charts with C3
C3 stands for Comfortable, Customizable, and Controllable. C3 is a JavaScript library that builds on top of D3.
FusionCharts
Google Charts
Highcharts
Plotly.js
ZingChart
Top 10 Graphical Libraries to Use with JavaScript Frameworks
D3.js
Chart.js
Chartist.js
FusionCharts
Britecharts.js
Two.js
Pts.js
Highcharts
Anime.js
Zdog
These are the best JavaScript chart libraries for 2019
D3.js
JSCharting
Highcharts
amCharts
Google Charts
ZingChart
FushionCharts
KOOLCHART
Chart.js
Slides
Create Mobile-Friendly Touch Sliders : Using SwiperJS and Vanilla JavaScript
Canvas
Create Interactive Visuals with JavaScript and HTML5 Canvas: How to Make Two Animated, Interactive Hero Sections
3D / Three.js
JavaScript in 3D: an Introduction to Three.js: How to bring three dimensions to your next web app
Webcam
How to access a webcam and take a picture with JavaScript : Introduce webcam-easy npm module
ECMAScript (ES)
ECMAScript其實就是JavaScript的標準,目前最新的版本是ECMAScript 2018 (ECMAScript 9),版本間的差異請詳參JavaScript Versions 或 THE COMPLETE ECMASCRIPT 2015-2017 GUIDE。
25 Years of JavaScript : From a simple scripting language to the foundation of every modern web application
ES5 to ESNext — here’s every feature added to JavaScript since 2015
The many names of JavaScript — LiveScript, JScript, ECMAScript, ES6 and not still Java
Vanilla Javascript
其實,所謂的Vanilla Javascript,不是一個新的javascript,而是指不用任何framework的純javascript
Take 10 minutes to get started with Handlebars with Vanilla Javascript
The Best Way to Type Check in Vanilla JS
Type checking with typeof in JavaScript
Why Object.prototype.toString.call() works
Creating a type_of function
How to Unit Test HTML and Vanilla JavaScript Without a UI Framework
ECMAScript 5 (ES5, ES2009)
ECMAScript 6 (ES6, ES2015)
Modules
Classes
Method definition
Property initializers
State
Arrow functions
Dynamic property names & template strings
Destructuring & spread attributes
Mixins
Default Parameters
猴子也能看懂的 React 教學 - 2 - 開始打 code 啦~
ES5 vs ES6
class
React.createClass VS extends React.Component
Props & State
bind
模組規範的整合
require VS import
“Require” is built-in with NodeJS
“Import” was introduced with ES6 modules
module.exports VS export default
export & import{}
Arrow functions
Template Strings
... (rest parameter & spread operator)
參數預設值
Component
設計 Component
使用 Component
Component 疊疊樂
父子 Component 間資訊的傳遞
ES5 vs ES6 ( With example code )
Reducing code with Arrow Function
Manipulating objects in ES6 vs ES5
Promises vs Callbacks
Exporting & Importing Modules
JavaScript ES6 — write less, do more
const and let
Arrow functions
Template Literals
Default parameters
Array and object destructing
Import and export
Promises
Rest parameter and Spread operator
Classes
These are the features in ES6 that you should know
let and const
Modules
Spread/Rest
Property short-hands
Destructuring assignment
Default parameters
Template string literals
Proper tail-calls
Promises
Class
Arrow functions
7 Javascript ES6+ Features You Must Know in 2020
Template Literals
Destructuring Objects
For of Loop
Spread Operator
Arrow Functions
Default Parameters
Sets
Object
Best of Modern JavaScript — OOP Features
Method Definitions
Property Value Shorthands
Computed Property Keys
New Methods of Object
Class
Understanding React Default Props (also solution in ES6)
Computed Properties
Import/Export
A simple intro to Javascript imports and exports (ES5 vs. ES6)
Built-In Module Imports and Exports: JavaScript ES6 Feature Series (Part 7)
Complete Guide For ES6 Import And Export Syntax Changes: Easily distribute code among files without worrying about naming conflicts
Spread/Rest syntax
What is the ES6 spread operator and why you shouldn’t use it
One syntax, two features
Spread
Using the spread operator with objects
Using the spread operator with arrays
Using the spread operator in function calls
Rest
Using rest in destructuring assignment
Using rest in a function signature
Spread & Rest Parameters: JavaScript ES6 Feature Series (Pt 4)
Revisiting JavaScript Rest and Spread Operators — JavaScript’s Three Dots
The tale of three dots in Javascript
Spread operator
Rest parameters
Use-cases
Copying an array
Unique array
Concatenate arrays
Pass arguments as arrays
Slicing an array
Convert arguments to an array
Convert arguments to array revisited
Convert NodeList to an array
Copying an object
Merge objects
Splitting a string into characters
There is no such thing as the Spread Operator in JavaScript!
這篇文章解釋為何spread不是operator
Understanding Destructuring, Rest Parameters, and Spread Syntax
Destructuring assignment (ES6)
3 Practical Uses of Object Destructuring in JavaScript
Named Function Arguments
Cleanly Parse a Server Response
Setting Default Values During Assignment
Seven things you should know about Object Destructuring in ES6
How To Use Destructuring and Arrow Functions to Improve Your JavaScript Code
JavaScript: Use Destructuring Assignment over Function Parameters
7 JavaScript Patterns Part 1: Making Variables from Properties / Destructuring assignment
What is so special about ES6 Destructuring
Object Destructuring
Array Destructuring
Understanding Destructuring, Rest Parameters, and Spread Syntax
Iterators
Template Literals
Beginners Guide to Tagged Template Literals in JavaScript
template literal
const price = 24.99;
const payments = 3;
const salesPitch =
`Only ${payments} easy payments
of $${price}!`
What Are Tagged Template Literals
Simply put, tags are functions that perform custom parsing of a template literal. A Template literal is “tagged” when you use one of these custom parsers. A popular library that uses this feature is styled-components. This library builds “styled components” by parsing template strings with their custom tags.
JavaScript Template Literals and styled-components
Tagged Templates
Using Tagged Templates
Styled HTML elements
Styled React components
ECMAScript 7 (ES2016, ES7)
ECMAScript 8 (ES2017, ES8)
ECMAScript 2017 (ES8): the final feature set
Major new features:
Async Functions (Brian Terlson)
Shared memory and atomics (Lars T. Hansen)
Minor new features:
Object.values/Object.entries (Jordan Harband)
String padding (Jordan Harband, Rick Waldron)
Object.getOwnPropertyDescriptors() (Jordan Harband, Andrea Giammarchi)
Trailing commas in function parameter lists and calls (Jeff Morrison)
ECMAScript 9 (ES2018, ES9)
Great New Features in ES2018: Including the spread operator in objects, rest operator, async iteration, and more
Spread Operator in Objects
Rest Operator
for await...of
Promise.finally()
SharedArrayBuffer
ECMAScript 10 (ES2019)
What’s new in JavaScript: Google I/O 2019 Summary
RegExp Lookbehind
Class fields
string.matchAll
Named capture groups
Numeric Separators
BigInt
Array: flat and flatMap
Multiple ways to flatten a JavaScript array; there’s more than one way to skin a 🙀
Array.flat()
Array.toString() or Template literal
Some other options if you are dealing with one level deep arrays.
How to Flatten an Array in JavaScript
Using while loop with a recursive helper function
Using Reduce and Concat Method
Using reduce, concat, and isArray, recursively
Use a stack
Use a generator function
Using Array.flat()
Object: fromEntries
globalThis
Stable Sort
Internationalization API
Promises
for-of
How to Trim Strings in JavaScript: ECMAScript10 (ES2019) added trimStart() / trimLeft() and trimEnd() / trimRight() functions to the string prototype.
Twelve ES10 Features in Twelve Simple Examples
Array#{flat,flatMap}
Object.fromEntries
String#{trimStart,trimEnd}
Symbol#description
try { } catch {} // optional binding
JSON ⊂ ECMAScript
well-formed JSON.stringify
stable Array#sort
revised Function#toString
BigInt primitive type (stage 3->ES2020)
Dynamic import (stage 3->ES2020)
Standardized globalThis object (stage 3->ES2020)
Upcoming new JavaScript features You should know if you use JavaScript everyday
Features in ECMAScript2019 (ES10)
Array.prototype.flat
Array.prototype.flatMap
New Features In Stage 3
Numeric Separators
Top-level await
Nullish Coalescing for JavaScript
Optional Chaining
Promise.any
What’s New in JavaScript — ES2019
Array.flat()
Array.flatMap()
Function.toString() Changes
JSON.stringify() Fix
String.trimStart()
String.trimEnd()
Optional Catch Binding
Symbol.description
ES 2020
New JavaScript Features Coming in ES2020 That You Can Use Now: New and powerful features in JavaScript: private fields in classes, optional chaining, nullish coalescing operator, and BigInts.
JavaScript new features for the 2020+
Optional Chaining
How To Use the Optional Chaining Operator in Your JavaScript App
Stop Letting Nested Object Properties Break Your Code: Use the optional chaining operator (?.) to help with undefined parent properties
Understand the Superpower of Optional Chaining in JavaScript
80% Cleaner JavaScript Code Using Optional Chaining and Nullish Coalescing
How To Solve One Of The Most Hated Coding Errors
optional chaining
ES2020 Optional Chaining and Dynamic Imports Are Game-Changers. Here’s Why.
Optional Chaining : Overcoming the Problem of Trust in JavaScript
Nullish coalescing operator
Native FileSystem API
Numeric Separators
Dynamic import
Dynamic Import and Tree Shaking in JavaScript: Why dynamic import isn’t always the best solution
ES2020 Optional Chaining and Dynamic Imports Are Game-Changers. Here’s Why.
JavaScript ES2020 Features With Simple Examples
String.prototype.matchAll
import()
BigInt
Promise.allSettled
globalThis
for-in mechanics
Optional Chaining
Nullish coalescing Operator
New Features In ES2020 You Should Check
Dynamic Import
BigInt
Promise.allSettled
globalThis
JavaScript new features in ES2020
Private Class Variables
Promise.allSettled
String.prototype.matchAll
Optional Chaining Operator
Dynamic Import
BigInt
The Best of Future JavaScript: Do expressions, optional chaining, and the nullish coalescing operator. Let’s look at each of them
8 New Features Shipping With ES2020
globalThis
Promise.allSettled()
The Nullish Coalescing Operator
Private Field in a Class
The Optional Chaining Operator
BigInt
dynamic import()
String.protype.matchAll
JavaScript module namespace exports: A new JavaScript ES2020 Feature
Here Are 5 New JavaScript Features in ES2020 That You Should Know
BigInt
Nullish Coalescing
Optional Chaining
Module Namespace Exports
globalThis
7 Interesting JavaScript Features in ES2020 That You Should Know
The State of JavaScript in 2020
Javascript Tools To Look Out for in 2021
Svelte, Next.js, esbuild and Snowpack
Javascript Features That You Should Start Using
The survey also showed a low adoption rate of new JavaScript features, such as the nullish coalescing operator (45.3%), optional chaining operators (66.7%), and Promise.allSettled() (14.7%)
ES2021
JavaScript ES2021 Exciting Features
String.prototype.replaceAll
Promise.any
Logical Operators and Assignment Expressions
Numeric Separators
Intl.ListFormat
dateStyle and timeStyle options for Intl.DateTimeFormat
The Top 3 New JavaScript ES 2021 (ES 12) Features I’m Excited About
Logical Assignment Operator
Promise.any
Numeric Separators
JavaScript ES2021 (ES12) Approved Features
String.prototype.replaceAll()
Promise.any() and AggregateError
WeakRefs and FinalizationRegistry
Logical assignment operators
Numeric separators
5 Upcoming JavaScript ES2021 (ES 12) Features To Watch Out for This Year
Top 5 JavaScript ES12 Features You Should Start Using Now
Numeric Separators
String.prototype.replaceAll
Promise.any() and AggregateError
Logical Assignment Operators
Private Class Methods and Accessors
ES2022
ECMAScript 2022 Is Officially Released, What Should We Pay Attention To? (2022/6 released)
Proposals included in the incoming ECMAScript 2022 standard for JavaScript
ES2022: A Complete Guide on Private Class Fields, Methods, and Static Initialization Blocks
Private class fields and methods
Static public fields (Static public methods are in ES2015)
Static private fields and methods
Static initialization blocks
Ergonomic brand checks for private fields
4 most important features coming in ES2022 that you should know about
Future
Top starred JavaScript features at early stage (level 0-1)
Top starred near-ready JavaScript features (level 2-3)
Pipelines
Let’s experiment with functional generators and the pipeline operator in JavaScript
Functional Programming and the Pipe Function in JavaScript: What is pipe and how can we use it?
Definition of Pipeline in JavaScript
Pure Functions
Without Pipe
How To Write Pipe
Compose and Pipe in JavaScript : Functional programming: What are Compose and Pipe in JavaScript?
Using Promise.allSettled now: Node 12.9.0 has been released and now supports the Promise.allSettled method. You can use it now in prior versions or the browser by rolling your own polyfill.
Decorators (目前還沒有正式成為ES標準)
What Is a Decorator in JavaScript?
This feature isn’t included in the newest ECMA-262, JavaScript in other words. You should always use Babel to use this in your project.
Learn About Decorators in JavaScript
Currently supported in TypeScript and in Babel plugins.
Creating and Using JavaScript Decorators
Characteristics of JavaScript Decorators
Method Decorators
Class Decorators
JavaScript and TypeScript Hidden Gems: Decorators : Although still an experimental feature, you can already play around with decorators and start seeing what you’ll be able to do with them.
JavaScript Finally Has Support for Native Private Fields and Methods
4 Ground-breaking JavaScript features of the future
Decorators
參考文件
How to Improve Your JavaScript Skills by Writing Your Own Web Development Framework
Stateful Monads in JavaScript — Part 1
A monad consists of the following components:
Type constructor — A feature that creates a monadic type for the underlying type.
Unit — A function that wraps a value of an underlying type into a monad.
Bind — This function is used to chain the operations on a monadic value.
Modern JavaScript Explained For Dinosaurs
We went from plain HTML and JS to using a package manager to automatically download 3rd party packages, a module bundler to create a single script file, a transpiler to use future JavaScript features, and a task runner to automate different parts of the build process.
How to differentiate between deep and shallow copies in JavaScript
Transducers: Efficient Data Processing Pipelines in JavaScript
The Easiest Way to Print Documents With Javascript — Print.js