Javascript
Last updated: Apr 22, 2020
IMAGE GALLERY (6)
- ES6
- ECMAScript 6 or JavaScript 6
- most recent incarnation of javascript
- specification standardized by Ecma International
- node.js
- asynchronous (non-blocking) event driven JavaScript runtime
- built against V8
- V8 is JavaScript and WebAssembly engine, written in C++
- Doesn’t use OS-threads based networking for concurrency
- Uses callback pattern almost everywhere
- A callback is a function called at the completion of a given task; this prevents any blocking, and allows other code to be run in the meantime.
- normaljs + additional capabilities on c++ player like
file
,http
etc - single thread can handle multiple requests
- nodeis continuously listening to
event queue
- since its single threaded, bad for CPU intensive apps but good for read/write intensive apps
- Traditional js needs
window
object to operate on. nodejs removes that limitation by emulating a browser environment to run js
Node module system
- In node every file is a module and variables and fucntions defined in that module are scoped to that module.
- explicitly
export
the private variables or functions if want to use them in other files.module.export.url = url;
- Why this design? Hide the implementation details. Eg: a DVD player, interface options are important for operations reset everythign is implementation detail
const logger = require('./logger');
to avoid accidently overridinglogger
value- node does not run our fucntion directly, rather wraps it inside other functions.
- built-in modules
- os
- fs
- events
- http
// synchronous version
function processData () {
var data = fetchData ();
data += 1;
return data;
}
// asynchronous version with callback pattern
function processData (callback) {
fetchData(function (err, data) {
if (err) {
console.log("An error has occurred. Abort everything!");
return callback(err);
}
data += 1;
callback(data);
});
}
New ES6 syntax
Thick arrow or hipster syntax
How to filter search using only vanilla js?1
- Arrow Functions
- Fat and Concise Syntax in JavaScript
=>
- They are one-line mini functions which work much like Lambdas in other languages like C# or Python.
- By using arrow functions, we avoid having to type the function keyword, return keyword (it’s implicit in arrow functions), and curly brackets.
// ES5
var x = function(x, y) {
return x * y;
}
// ES6
const x = (x, y) => x * y;
// or
cont x = (x, y) => { x * y };
// Array traversal ES6
const array1 = ['avi', 'mehenwal']
var array2 = array1.map((item) => item)
console.log(array2)
We can skip writing liternal name twice if name of variable is same as property name. ES6 expands it automatically
// old
{ route: route }
// new
{ route }
using var
before variable names could be neglected
var foo = 5;
foo = 5;
Things to remember about ES6 syntax
- ES6 Syntax
- Arrow Function Notation, Hipster Syntax
const
andlet
overvar
- Arrays and Object deconstruction
import
andexport
- working with
Promis
Objects - Class structures
How to compiler javascript?
Babel
- Babel is a JavaScript compiler.
- Babel is a toolchain that is mainly used to convert ECMAScript 2015+
code into a backwards compatible version of JavaScript in current and
older browsers or environments.
- babel can Transform syntax.
Practise Environment
In browser, use jupyter notebook with magic command
%%javascript
to run js inside jupyter notebook.Jupyter Lab newer alternative
sudo apt install -y jupyter pip install --user jupyterlab set --export --global $HOME/.local/bin $PATH jupyter lab # add javascript kernel sudo npm install -g ijavascript ijsinstall # refresh jupyter lab
On terminal, using nodejs
jupyter lab
// no variable types
b = 123
a='avi'
c = "mehenwal"
console.log(a,b,c)
avi 123 mehenwal
const os = require('os');
totalMemory = os.totalmem();
freeMemory = os.freemem();
console.log('totalMemory =',totalMemory,'\nfreeMemory =',freeMemory)
totalMemory = 7793405952
freeMemory = 131977216
Template String syntax
ES6 or ES2015
console.log(`Total Memory: ${totalMemory}`)
console.log(`Free Memory: ${freeMemory}`)
Total Memory: 7793405952
Free Memory: 131977216
Filesystem
const fs = require('fs');
const folderPath = '/home/avi/mySoftwares/EXP/jupyter';
// new syntax
fs.readdir(folderPath, (err, files) => {
files.forEach(file => {
console.log(file);
});
});
// older syntax
fs.readdir(folderPath, function(err, files) {
if(err)
console.log('Error', err);
else
console.log('Result', files);
})
events
const EventEmitter = require('events')
const emitter = new EventEmitter();
.ipynb_checkpoints
nodejsBasic.ipynb
Result [ '.ipynb_checkpoints', 'nodejsBasic.ipynb' ]
// register a listner
emitter.on('event', () => {
console.log('event occoured');
});
EventEmitter {
domain: null,
_events: { event: [Function] },
_eventsCount: 1,
_maxListeners: undefined }
emitter.emit('event')
event occoured
true
Questions
- Difference b/w node and vue js?
Understand the CONCEPT, why JS is the way they are? What do people who wrote JQUERY wrote know that you dont know. Those that learn how things work under the hood, solves the problem better.
Javascript
// JS Hoisting, still works though a=undefined unlike other languages
b()
console.log(a)
var a = 'Hello World'
function b() {
console.log('called b')
}
// coercion example
var a = 1 + '2';
console.log(a); // a = 12
// Callbacks
let x = function () {
console.log('inside X')
}
let y = function (callback) {
console.log('Function Y')
callback()
}
y(x)
- Tools you need - browser. Setup env to run js in browser
- multiple Key-value = Objects
- language grammer, compiler/interpreter
- Syntax Parsers - parsing source code character by character as per defined grammer
- Javascript Engine creates
- Lexical Environment
- Global Execution Context - particular/running lexical env
- JS file loaded, syntax parser started and execution context was created
this.
,window
- global object- these things are automatically created by JS engine, we wrote no code for it
- Google chrome
v8 engine
- Javascript HOISTING
- Execution context is created in 2 phases
- Creation phase
- Global object
- this
- outer environment
- setup memory space for variables and functions = hoisting
- Execution phase - line by line traditional execution 1.
- Execution context is created in 2 phases
undefined
is a special value js has inside it.null
lack of existence- I the programmer, never set this value
- JS is single threaded, synchronous execution
- Function Invocation
function()
- function call - Veriable environment - namespace, where does the variable live?
- Scope Chains, lexical linking
let
block scoping. Not allowed to use it until the line of code is run that declares the variable- inside the block
- Asynchronous Callbacks
- More than one at a time
- Event Queue
- Static typing and Dynamic Typing
- Data types in JS - null, undefind, boolean, string, number, object, symbol, function
- Coercion - Converting a value from one type to another
- Frameworks
- Not seperatring the code in any way, no new execution context
- just stacking code
- Running all js code as if was inside one file
- checking the global namespace so that it doesnt collide
window.libraryName = window.libraryName || "Lib 2"
- Objects and Functions are closely related in JS
var Person = {}
- Callback Functions - Higher order functions
- First Class Objects - pass other functions as arguments to functions
- Enforce the order of time-consuming operations
- Adding new data to DB then updating the view once updated
Asynchronous Javascript
How do JS deal with asynchronous, non-blocking events?
Callbacks, Promises and async, await syntax
- Do NOT stall until action is finished, like response from server
- In 2015, ES6 Promises were introduced in language
- In ES7, async/await syntax was added to deal with Promises
// With function declaration
async function myFn() {
// await ...
}
// With arrow function
const myFn = async () => {
// await ...
}
Publish your first vue npm package
Worlds largest software registry to share JS code
- What does NPM mean?
- npm package manager UI
- npm command line tool
- npm files under npm_modules
- Plugins enhances the functionality of codebase
- As stated in the Official Vue.js documentation, there is no strictly defined scope for a plugin. It simply adds global-level functionality to your project
- Add some component options by global mixin. e.g. vue-router
- using vue-cli
--target lib
mode - npm publish –access public
- npm init - to create package.json file
- normal npm modules gets installed under node_modules directory *
vuejs
plugins are different fromnuxtjs
Typescript vs Javascript
- Strict syntactic language
- Autocompletion, autoimports