Javascript
JavaScript is a high-level, interpreted programming language.
Last updated
Was this helpful?
JavaScript is a high-level, interpreted programming language.
Last updated
Was this helpful?
basic data type: undefined、null、boolean、number、string、symbol
object type: object array function
The shallow comparison check means that JavaScript only checks that the value's object IDs are the same, not their contents are the same. The ID here means the memory address for where JavaScript stores the information for that particular object.
Heap - Objects are allocated in a heap which is just a name to denote a large mostly unstructured region of memory
Stack - This represents the single thread provided for JavaScript code execution. Function calls form a stack of frames (more on this below)
Browser or Web APIs are built into your web browser, and are able to expose data from the browser and surrounding computer environment and do useful complex things with it.
VIP插队: micro-task, normal: macro-task
promise iis micro
variable can be used before it has been declared
Hoisting is a term used to explain the behavior of variable declarations in your code. Variables declared or initialized with the var
keyword will have their declaration "moved" up to the top of the current scope.
However, only the variable declarations and function declarations are hoisted. Variable assignments and function expressions are not hoisted.
A closure is an inner function that has access to the variables in the outer (enclosing) function's scope chain. Closure can keep its scope variable and not be gabage collection. Closure is a function that returns a function. It gives the access to an outer function's scope from an inner function. To use the closure, simply define a function inside another function and return it or pass it to another function.
The closure has access to variables in three scopes
variables in its own scope
variables in the enclosing function's scope
global variables
We can use Closure to declare a private variable.
1What will the following code output?
Answer
number 3 alerted 3 times after 1, 1.1, and 1.2 seconds.
Solve: use IIFE or let.
We pass the variable i into the outer function as a local variable named i_local, where we then return a function that will alert the i_local for us. This should now correctly alert the numbers 0, 1, and 2 in the correct order.
2. Write a function that would allow you to do this.
How would you use a closure to create a private counter?
A higher-order function is any function that takes one or more functions as arguments, which it uses to operate on some data, and/or returns a function as a result. Higher-order functions are meant to abstract some operation that is performed repeatedly. e.g.map
, forEach
, filter
, reduce
, bind
.
Currying is a pattern where a function with more than one parameter is broken into multiple functions that, when called in series, will accumulate all of the required parameters one at a time. This technique can be useful for making code written in functional style easier to read and compose. It's important to node that for a function be curried, it needs to start out as one function, then broken out into a sequence of functions that each accepts one parameter.
this
in JavaScriptThe value of this
depends on how the function is called.
The following rules are applied:
If the new
keyword is used when calling the function, this
inside the function is a brand new object.
If apply
, call
or bind
are used to call/create a function, this
inside the function is the object that is passed in as the argument.
If a function is called as a method, such as obj.method()
, this
here is the object that the function is a property of.
If a function is invoked as a free function invocation. meaning it was invoked without any of the conditions present above, this
is the global object. In a browser, it is the window
object. If in strict mode ("use strict"
), this
will be undefined
instead of the global object.
If multiple of the above rules apply, the rule that is higher wins and will set the this
value.
If the function is an ES6 arrow function, it ignores all the rules above and receives the this
value of its surrounding scope at the time it is created.
window
is the main JavaScript object root, like the global object in the browser, also can be treated as the root of the DOM.
document
is the main object of the rendered DOM.
0
null
undefined
""
false
NaN
Global Scope - declared outside for any function, use it without declaring
Function Scope - var
Block Scope - let & const
const
: immutable variable, must be initialized
Module Scope
All JavaScript objects have a prototype property, that is a reference to another object. When a property is accessed on an object and if the property is not found on that object, the JavaScript engine looks at the object's prototype, and the prototype's prototype and so on, until it finds the property defined on one of the prototypes or until it reaches the end of the prototype chain. This behavior simulates classical inheritance, but it is really more of delegation than inheritance.
classical inheritance: a description of the object to be created. Classes inherit from classes and create subclass relationships.
prototypal inheritance: a prototype is a working object instance. Objects inherit directly from other objects.
null
vs undefined
A variable that isundefined
is a a variable that has been declared, but not assigned a value. It is of type undefined
.
A variable that is null
will have been explicitly assigned to the null
value. It represents no value and is different from undefined
in the sense that it has been explicitly assigned. It is of type object
.
undefined == null // true
Object() constructor
Object.create()
creates a new object extending the prototype object passed as a parameter
Bracket's syntactic sugar
equals to Object.create(null), using a null prototype as an argument
Function constructor
call a function and setting this of the function to a fresh new Object, and binding the prototype of that new Object to the function's prototype
Function constructor + prototype
ES6 class syntax
Singleton pattern
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. e.g. addEventListener
Callback Hell is referred to the problems caused by asynchronous AJAX calls, which means where are multiple nested callbacks.
keep the code shallow
modularize
handle every single error
Promise The asynchronism here is all contained in the promise chain. myFunction
operates like any callback would, running synchronously. Our last log will print “I’m over here running synchronously” before returnsAPromise
resolves.
In our async/await version, we have to make our entire wrapper function asynchronous. This has a couple of effects— now, myAsyncFunction
returns a promise, and any synchronous code we want to run has to be pulled out of the function entirely.
A null process - which takes its name from the concept of null pointers - is what happens when no formal process is put in place
BFS
DFS
BFS visit nodes level by level in Graph
DFS visit nodes of graph depth wise. It visits nodes until reach a leaf or a node which doesn't have non-visited nodes
A node is fully explored before any other can begin
Exploration of a node is suspended as soon as another unexplored is found
Uses Queue data structure to store un-explored nodes
Uses Stack data structure to store un-explored nodes
BFS is slower and require more memory
DFS is faster and require less memory
Event Delegation Event Bubbling Event capturing
The event loop is a single-threaded loop that monitors the call stack and checks if there is any work to be done in the task queue. If the call stack is empty and there are callback functions in the tack queue, a function is dequeued and pushed onto the call stack to be executed.
Currying refers to the process of transforming a function with multiple arity into the same function with less arity. The curried effect is achieved by binding some of the arguments to the first function invoke, so that those values are fixed for the next invocation
babyAnimals is a curried function;
setTimeout
and setInterval
setTimeout sets a timer which executes a function or specified piece of code once after the timer expires.
setInterval repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.
setImmediate
vs process.nextTick
process.nextTick fires immediately on the same phase.
setImmediate fires on the following iteration or "tick" of the event loop.
new
vs Object.create
new
is Object.create
with additionally running the constructor
function. And giving the constructor
the chance to return
the actual object that should be the result of the expression instead of this
.
Lexical scope, also known as static scope, is a convention that sets the scope of a variable so that it may only be called from within the block of code in which it is defined. The scope is determined when the code is compiled.
The bind
method creates a new function that, when called, has its this
keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
Call
vs Apply
Both are used to invoke functions and the first parameter will be used as the value of this
within the function. However, call
takes in comma-separated arguments as the next arguments while apply
takes in an array of arguments as the next argument.
Apply - array
Map
vs forEach
forEach
: parameter is a function, apply the function to each item. It modifies the original array.
map
: apply the function to all elements, function has two parameters, first is value, second is index. It returns a new array, the original array is not modified.
event-driven programming a programming paradigm in which the flow of the program is determined by events such as user actions, sensor outputs, or messages from other programs or threads.
Since the arrow function offers a very clean concise syntax and more intuitive scope and this
binding.
props:
avoid callback hell which can be unreadable
makes it easy to write sequential asynchronous code that is readable with .then()
makes it easy to write parallel asynchronous code with Promise.all()
cons:
slightly more complex code
in older browsers where ES6 is not supported, you need to load a polyfill in order to use it
Singleton
Factory method
Strategy
Observer
Builder
Adapter
State
Object.freeze()
JSON Web Tokens (JWT) are an important piece in ensuring trust and security in your application. JWT allow claims, such as user data, to be represented in a secure manner.
"use strict" is a statement used to enable strict mode to entire scripts or individual functions. Strict mode is a way to opt into a restricted variant of JavaScript.
advantages:
makes it impossible to accidentally create global variables
makes assignments which would otherwise silently fail to throw an exception
makes attempts to delete undeletable properties throw
requires that function parameter names be unique
this is undefined in the global context
it catches some common coding bloopers, throwing exceptions
it disables features that are confusing or poorly thought out
disadvantages
many missing features that some developers might be used to
no more access to function.caller and function.arguments
concatenation of scripts written in different strict modes might cause issues
A module is a separated part of a program. It helps developers to separate functionality and organize the codebase by using export and import.
HTML5 Web Workers
Using iteration - not work for nested objects
Converting to JSON and back
Using Object.assign - not work for nested objects
Using Spread Operator - not work for nested objects
On the client (browser environment), as long as the variables/functions are declared in the global scope, all scripts can refer to them.
On the server (Node.js), Each file is treated as a module and it can export variables and functions by attaching them to the module.exports
object.
a function where the return value is only determined by its input values, without observable side effects.
replace()
String.replace()
var p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
var regex = /dog/gi;
console.log(p.replace(regex, 'ferret'));
Only words:
s.replace(/\W/g, '')
<div><button /></div>
$('div').on('click', function(){ alert('div') })
$('button').on('click', function(){ alert('button') })
select button first
You can place any number of scripts in an HTML document.
Scripts can be placed in the <body>
, or in the <head>
section of an HTML page, or in both.
Scripts can also be placed in external files:
You can place an external script reference in <head>
or <body>
as you like.
The script will behave as if it was located exactly where the <script>
tag is located.
Placing scripts in external files has some advantages:
It separates HTML and code
It makes HTML and JavaScript easier to read and maintain
Cached JavaScript files can speed up page loads
To add several script files to one page - use several script tags:
<script src="myScript1.js"></script>
You can create a closure to keep the value passed to the function createBase even after the inner function is returned. The inner function that is being returned is created within an outer function, making it a , and it has access to the variables within the outer function, in this case the variable baseNumber.
You can create a function within an outer function (a closure) that allows you to update a but the variable wouldn't be accessible from outside the function without the use of a helper function.
script src="</script