JavaScript : Foundation and Internal
#programming-languages
- 5 minutes read - 943 words
Introduction
Basics of JavaScript programming language to get an experienced programmer up and running.
Dev Environment
Places to run and try-out javascript code.
- Browser Console: Firefox ctrl+shift+k
- node console
node
- node script run
node script.js
Basics
-
Variables : use
const
andlet
to define variables in this weakly typed language.var
can be used in some cases -
Functions : supports
named
,anonymous
andlambda
orarrow
function notation to define callable function and function expressions -
Class : syntactic sugar on top or special function type called
prototype
-
this : points to current context in which a given snippet or function is executing
-
loop : for, while
-
switch
-
conditional flow (if-else) and Conditional (ternary) operator
-
types : number, bigint, string, boolean, Objects
-
inheritance is handled by prototyping
Objects
Everything in JavaScript is technically an object with a constructor and key, value map
// Object
let o = {
0: 'a',
1: 'b'
}
console.log(o.constructor) // get the constructor default Object
console.log(Object.keys(o)) // [0, 1 ] etc
An array is an object with Array
as constructor and keys are index to individual elements. The routines, for example, push
are defined by the prototype function Array
let a = []
a.push(1)
a.push('33')
A number is an object with Number
as constructor and no keys.
let a = 5;
A string is an object with String
as constructor and keys as index to each char.
let a = 'a'
Destructuring
Accessing members of an object is called destructuring.
- It can be done by directly accessing the member, if it’s not present the value will be
undefined
not an exception.
> let a = {
... 'one': 1,
... 'two': 2,
... }
> a
{ one: 1, two: 2 }
> a.one
1
> a.two
2
> a.three
undefined
- or can be picked up into local variable using a one line syntax
> const { one:first, two:second, three:third } = a;
undefined
> first
1
> second
2
> third
undefined
- If the target local variable can keep the same name then this syntax becomes even cleaner.
> const { one, two, three } = a;
undefined
> one
1
> two
2
> three
undefined
Object Spread
It is used to create a copy of existing data structure where you want to either change some of the value add new on top of existing.
// example from Mozilla blog
let numberStore = [0, 1, 2];
let newNumber = 12;
numberStore = [...numberStore, newNumber];
Promise
de-facto way of handling asynchronous actions in JS. best explained here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Basic Data Structures
- String
- Array
- List
- Queue
- Stack
- HashMap
- Set
Basic Algorithms
- Sorting
- Scalar: max, min, sum
- map-reduce, filter
lodash
lodash: a library for Data Structure manipulation and then some
npm init
npm install --save lodash
var _ = require('lodash');
// in node repl
a = [1,2,3]
b = [4,5,6]
_.zip(a, b) // two dimensional array of combined a and b
nodejs process
The process object provides information about, and control over, the current Node.js process Complete documentation here: https://nodejs.org/api/process.html
nodejs command line argument
// within JS executed in node env
process.argv
Example: node sourcefile
console.log(process.argv.length);
console.log("Node Binary: ", process.argv[0]);
console.log("Source File: ", process.argv[1]);
let a = process.argv[2];
let b = process.argv[3];
console.log(a+b);
npm
npm is node package manager
npm is to JS and node what pip is to python
npm supports npm managed projects. and managing means initializing the npm directories and helper files that keep track of packages and dependencies.
more structures than pip-requirements.txt or setup.py but less hectic than pom.xml for maven
npm init // create a blank npm project
npm install --save <package> // main dependency
npm install --save-dev <package> // dev dependencie
cat package.json // package info
cat package-lock.json
In addition to managing dependency npm handles project properties as well. Like metadata and running scripts.
npm run start
npm run dev
npm build
Explore package.json of famous projects to learn more. its very intuitive.
webpack
build system for web development projects. For my own reference it’s what maven is to java.
It bundles all the scattered JS CSS images html etc into distributable
It resolves dependency automatically (that’s the most amazing thing). All you have to do is provide a starting point and an output directory/file and done !
There is more to it but this is the gist of it.
Babel
Babel is a JavaScript compiler.
JavaScript or ECMAScript gets a new spec every year or so. It’s not always compatible with all the JS browsers out there. So, to make developer’s life easy, babel compiles or transpiles the most advanced JS spec to the most compatible JS spec.
Let’s try it in a blank npm project in cli
npm install --save-dev @babel/core @babel/cli
./node_modules/.bin/babel babeltest.js -d outdir
// this will compile babeltest.js and output the result in dir outd
JavaScript Oops
- sort() by default treat everything as string
Typescript teaser
Installation Global (-g) or Local (–save-dev)
npm install typescript # gives tsc : compile ts to js
npm install ts-node # gives ts-node : ts repl
npm install @types/node # avoid warning/errors like console not found
Typescript is JavaScript with types specified to become strongly typed. any
is wildcard use to make TS a JS
# add typescript to your project as a dev dep
npm install typescript --save-dev
# compile typescript file to js using tsc (typescript compiler)
npx tsc file.ts
# there will be a file.js in dir after that
# you'll need tsconfig to config the project to get it compiled using ts
# run a ts repl
npx ts-node
# execute a ts file
npx ts-node file.ts
npm install @types/{package} to get typescript version of your fav package