js Flashcards
JavaScript
JavaScript is a scripting language which enables you to create dynamically updating content.
A scripting language or script language is a programming language for a runtime system that automates the execution of tasks that would otherwise be performed individually by a human operator. Scripting languages are usually interpreted
JavaScript List of Primitive Types (6)
Number
String
Boolean
Null
Undefined
Symbol
Why functions are considered first-class objects?
In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.
Closure
A closure is the combination of a function enclosed with references to its surrounding state (the lexical environment).
A closure is the combination of a function and the lexical environment within which that funciton was declared.
The environment consists of any local variables that were in-scope at the time the closure was created.
lexical scoping
describes how a parser resolves variable names when functions are nested. The word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope
let vs var
The main difference is scoping rules. Variables declared by var keyword are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } (hence the block scope)
var a = 10;
function myFn() {
var b = a;
console.log(b);
c = 100;
}
myFn();
In what scope is ‘c’ declared?
‘c’ has been declared within the global scope since we did not declare it properly, therefore by defaults creates the variable within the global scope.
Hoisting
Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of code
DOM
The DOM (Document Object Model) API is a Common browser API, which allows you to manipulate HTML and CSS updating the HTML, dynamically. The DOM is represented with a logical tree.
This is a “Tree Structure” representation created by the browser that enables the HTML structure to be easily accessed by programming languages
event
Events are actions or occurrences that happen in the system you’re programming, which the system tells you about so your code can react to them.
To use events, we attach EVENT HANDLERS to an object. and these event handlers contain how they are triggerd and the response to that trigger (event listener)
example:
const btn = document.querySelector(‘button’);
btn.addEventListener(‘click’, ( ) => {//function body});
What is an Object?
An Object is a collection of related data and/or functionality. These usually consist of several variables and functions (which are calle properties and methods when they’re inside objects.
What is an Object Literal?
We refer to objects literals to objects that weren’t instantiated from classes, but written out as we’ve come to create it
What are Object Prototypes?
Prototypes are the mechanism by which JavaScript objects inherit features. Every object in JavaScript has a built-in property, which is called the prototype
What does “strict mode” do?
- Eliminates some JavaScript silent errors by changing them to throw errors
- Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode
- Strict mode also prevents us from accidentally creating global variables (usually happens due to typos).
- functions parameters are required to be unique in strict mode
- prevents from attempting to delete undeletable properties
- lastly, strict mode in ECMAScript 2015 forbids setting properties on primitive values. Without strict mode, setting properties is ignored (no-op), with strict mode, however, a TypeError is thrown.
Strict mode is already set on modules
What does “this” refer to?
The keyword “this” refers to an object which depends on the context that is being used in. For example, if used within a constructor, it refers to the object that is being created.
if an instantiated object calls one of its methods, “this” will refer to the calling object (The keyword “this” refers to the object that called the function)
What does it mean to be a scripting language?
Scripting languages are programming languages that execute within a special run-time environment by an interpreter rather than a compiler.
What does it mean for the code to be interpreted?
It means that instructions are executed without a previous compilation process (transforming code into machine code).
Is java an interpreted language?
What is the process for the code to be executed?
Well… Partially. JavaScript uses a JIT (just-in-time) compiler, which monitors (by the profiler) the interpreted code as it’s being executed in order to optimize the code .
At first, the monitor just runs everything trough the interpreter. Then looks for statements that can be optimized and sends them off to be compiled.
file.js —–> parser ——> AST
|
|
v
interpreter —-> byte code
|
|
v
Profiler ——> compiler
|
|
v
Optimized
code
v8 - JavaScript is interpreted by an interpreter named IGNITION as well as compiled by a JIT optimizing compiler named TURBOFAN
- The generated ASTs are given to the interpreter which generates a non-optimized machine code quickly and the execution can start with no delay
- The PROFILER watches the code as it runs and identifies areas where optimization can be performed. For example a ‘for’ loop running 100 times but producing the same result in each iteration.
- Using this profiler, any unoptimized code is passed to the compiler to perform optimizations and ggenerate machine code which eventually replaces its couterpart in the perviously generated non-optimized code by the interpreter
- As the profiler and compiler constantly make changes to the bytecode, the HavaScript execution performance gradually improves
What is the difference between async and refer?
[this]
Async and refer are two different strategies to load a script.
A common problem is that all the HTML on a page is loaded in order in which it appears. If you’re using JS to manipulate elements on the page (the DOM), you code won’t work if the JavaScript is loaded and parsed before the HTML you are trying to do something to. (read my notes…)
Defer:
- loads files in the order they appear on the page
- THey won’t run until the page content has all loaded, which is useful if your scripts depend on the DOM being in place.
defer tells the browser to continue downloading the HTML content once the tag element has been reached. —- defer is a solution to and old-fashioned alternative which was putting your script element right at the bottom of the body, so that it would load after all the HTML has been parsed. The problem with this solution is that loading/parsing of the script is completely blocked until the HTML DOM has been loaded. On larger sites with lots of JavaScript, this can cause a major performance issue, slowing down your site.
Async:
- downloads the script without blocking the page while the scipt is being fetched
- Once the download is complete, the script will execute, which blocks the page from rendering
- You get no guarantee that scripts will run in any specific order (bad for dependencies)
- Best to use when the scripts in the page run independently from each other.
For example, maybe you have some game data files to load, which will be needed when the game actually begins, but for now you just want to get on with showing the game intro, title, and lobby, without them being blocked by a script loading.
check image for a better understanding:
https://user-images.githubusercontent.com/1437027/49294708-06ca1e00-f4b4-11e8-86b5-3f843ab98d0b.png
What is the difference between framework and library?
Both are code written by someone else that is used to help solve common problems.
The technical difference lies in inversion control, when using a framework, the framework is in charge of the flow. It provides some places for you to plug in your code, but it calls the code you plugged in as needed, whereas a library is used only when needed.
Analogy:
A library is like going to Ikea. You already have a home, but you need a bit of help with furniture. You don’t feel like making your own table from scratch. Ikea allows you to pick and choose different things to go in your home. You are in control.
A framework, on the other hand, is like building a model home. You have a set of blueprints and a few limited choices when it comes to architecture and design. Ultimately, the contractor and blueprint are in control. And they will let you know when and where you can provide your input.
What is JSON?
[this] The JavaScript Object Notation is a standard text-based format used to represent structured data, commonly used for transmitting data.
What is a Primitive Wrapper Type?
Primitive data types do not have any methods, however, when we call a method on a variable that holds primitive data, javascript performs the following steps:
- Create an object of the corresponding type
- Call a specific method on the instance
- Delete the instance immediately
When do we say that an object has mutated?
When somebody changes its property to point to a different value.
For example, if we declare let iceCream = {flavor: “vanilla”}, we can later mutate it with iceCream.flavor = “chocolate”. Note that even if we used const to declare iceCream, we could still mutate iceCream.flavor. This is because const would only prevent assignments to the iceCream variable itself, but we mutated a property (flavor) of the object it pointed to. Some people swore off using const altogether because they find this too misleading.
Eval()
The eval() function evaluates JavaScript code represented as string. Using eval is a security risk.
console.log(eval(‘2+2’));
We should use window.Function() as an alternative
What is the difference between calling a function like ‘foo(arg1, arg2)’ and foo.call(this, arg1, arg2)?
function.prototype.call() calls a function with a given ‘this’, which allows for a function/method belonging to one object to be assigned and called for a different object.
Promise
A promise is an object returned by an asynchronous function, which represents the current state of the operation. (At the time the promise is returned to the caller, the operation often isn’t finished, but the promise object provides methods to handle the eventual success or failure of the operation)
Asynchronous programming
Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs.
Many functions provided by browsers, can potentially take a long time, and therefore, are asynchronous. Example:
- Making HTTP requests using fetch()
- Accessing a user’s camera or microphone using getUserMedia()
- Asking a user to select files using showOpenFilePicker()
How asynchronous operations occur if JavaScript is single-threaded?
Due to the implementation of engines such as v8 or spiderMonkey, we are provided with different web APIs that take charge of the operation while the rest of the code keeps executing
Do the exercise located on Onenote (JavaScript > Asynchronous programming > call stack > how js callback queue works.
…
What is a callback function?
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.
What is The Event Loop?
runtime model based which is responsible for executing the code, collecting and processing events, and executing queue sub-tasks
What is the incumbent settings object?
A settings object is an environment that provides addtional information when JavaScript is running. This includes:
- the realm and module map
- HTML specific information.
The incumber settings object is tracked to ensure that the browser knows which one to use for a given piece of user code.
A realm can be roughly thought of as the global object. What is unique about realms is that they hold all of the necessary information to run JavaScript code. This includes objects like Array and error.
Promises and Web Workers address different needs, which are they?
Promises are constructs to assign a reference to a result not yet available, and to organize code that runs once the result becomes available or a failure is returned.
- Web Workers perform actual work asynchronosuly (using operating system threads not processes - so they are relatively light weight)