Skip to content

Instantly share code, notes, and snippets.

@SanthoshVijayabaskar
Last active November 27, 2019 21:47
Show Gist options
  • Save SanthoshVijayabaskar/a49470f4cced0c4582b2 to your computer and use it in GitHub Desktop.
Save SanthoshVijayabaskar/a49470f4cced0c4582b2 to your computer and use it in GitHub Desktop.
Understanding the wired parts of Javascript

Bind()

Bind creates a copy of the function and sets the param passed as "this" variable. Gets us to control the "this"
bind

Call and Apply Example

"Call" and "apply" executes the methods with passing in the reference to "this" keyword and necessary parameter for the function bind_call_apply

apply

Use Case 1: Function Borrowing

function_borrowing

Use Case 2: Function Currying

currying

Functions are Objects in JS

First Class Functions

Everything you can do with other types you can do with functions. Assign them to variable, pass them around, create them on the fly.

function_are_objects

Example

![func_examples](https://cloud.githubusercontent.com/assets/1716894/11166646/fe53bf2c-8b63-11e5-84bd-aed863198b6f.jpg)

By Value vs By Reference

  • Objects always use By reference (even when passed as parameters)
  • Equal operator sets up a new memory space (new address)
  • All Primitive types uses By Value

by_value

by_reference

JS don't have Function Overloading

Since Functions are Objects, having first class functions, we don't have Function Overloading. But to achive this kind of overloading logic, we have a design pattern in Javascript, where we define a function which takes the necessary arguments and calls the actual function within, with the additional arguments.

Warning: Automatic Semicolon Insertion

The JS Syntax parsers inserts an automatic semicolon upon seeing carriage return (ENTER) after specific lines. If it inserts after "return" statement, it will cause empty function issue, making it undefined. Hence we end the "return" statements with "{", so that the JS Syntax parsers know we are starting an Object literal sytax and will not insert semicolon at the end.

Whitespace

Invisible characters that create literal 'space' in your written code. (Carriage Return, Space, Tabs)

Immediately Invoked Function Expression (IIFE) & Safe Code

var greeting = function(name){
console.log('Hello '+ name);
}('John');

var greeting = function(name){
return 'Hello '+ name;
}('John');

console.log(greeting);

var firstname = 'John';

(function(global,name){
var greeting = 'Inside IIFE: Hello';
global.greeting = 'Hello'; console.log(greeting + ' ' + name);
}(window,firstname)); //IIFE - Also you can use the params inside the outer parantheses or outside the outer parantheses

Objects and The DOT

objects

Examples

![examples_objects_and_dots](https://cloud.githubusercontent.com/assets/1716894/11165088/2b49cb86-8b2b-11e5-8510-f20ded3adea2.jpg)

Object Literals

Instead of using a 'new' operator to define a Object as below,
var person = new Object(); // Creates an Person Object

We can use the '{ }' braces to create an object which is termed as Object Literal.
var person = { };

Namespace: Faking Namespace in JS

NAMESPACE : A Container for variables and functions, typically to keep variables and functions with the same name separate.
Javascript dosen't have namespace due to the language design,but we can fake it using Object Literal.

var english = {};
var spanish = {};

english.greet = 'Hello!';
spanish.greet = 'Hola!';

JSON Vs Object Literals

JSON: Javascript Object Notation (Inspired from Object Literals in Javascript)

  • JSON is a subset of Object Literal Syntax
  • Not all Object Literal Syntax is a JSON, But all JSON is a valid Object Literal Syntax
  • JSON has much stricter Syntax Representation
  • JSON needs property names to be within doubleQuotes "firstName": "Santhosh"
  • Examples:

var objectLiteral = {
firstName: 'Mary',
isAProgrammer: true
}
console.log(JSON.stringify(objectLiteral));

var jsonValue = JSON.parse('{ "firstname": "Mary", "isAProgrammer" : true}'); console.log(jsonValue);

Conceptual Aside

Syntax Parsers

A Program that reads your code and determines what it does and if its grammar is valid.

Lexical Environment

Where something sites physically in the code you write
Example: the variable 'a' sites lexically within the function "hello()"
HINT: 'Lexical' means 'hanving to do with words or grammar'. A Lexical environment exists in programming languages in which where you write something is important.

Execution Context

A wrapper to help manage the code that is running

There are lots of lexical environments. Which one is currently running is managed via execution contexts. It can contain things beyond what you've written in your code.

Name/Value Pair

A Name which maps to a unique value

The name may be defined more than ones, but only can have one value in any given context
That value may be more name/value pairs
Example: Address = "100 Main Street."

Object

A Collection of Name Value Pairs Example:
Address: { Street: 'Main', Number:100, Apartment: { Floor:3, Number: 301 } }

Execution context (Global)

The JS Engine creates a global Execution Context. This Global Execution Context contains the following things:
* Global Object * 'this' * Outer Environment * Your Code

The Execution Context : Creation and Hoisting

PHASE 1: CREATION PHASE

* The Global Object is created in memory * 'this' is setup in memory * Outer Environment is created * Setup Memory Space for Variables and Function (AKA Hoisting)
--> During Hoisting the Variables are set to "Undefined"

PHASE 2: EXECUTION PHASE

* It runs the code line-by-line

Single Threaded

One Command is Executed at a time

Synchronous

One at a time (and in Order)

Javascript is Single threaded, Synchronous in its behavious

Execution Stack

execution_stack

Variable Environment

Where the variable live and how they relate to each other in memory

The Scope Chain

scope_chain

Scope

Where a variable is available in your code

Asynchronous

More than one at a time

Types

Dynamic Typing

You don't tell the engine what type of data a variable holds, it figures it out while your code is running.
Variables can hold different types of values because it's all figured out during execution.

Example: Static Typing
bool isNew = 'hello'; //an error

Example: Dynamic Typing
var isNew = true; //no errors
isNew = 'yup!';
isNew = 1;

Primitive Type

A Type of Data that represents a single value (That is, no a object)
* UNDEFINED (Represent lack of existence - You shouldn't set a variable to this) * NULL (Represent lack of existence - You can set a variable to this) * BOOLEAN (true or false) * NUMBER (Floating point number - there's always some decimals - Unlike other programming languages, there's only one 'number' type... and it can make math weird) * STRING (a sequence of character - both '' and " " can be used) * SYMBOL (Used in ES6 - the next version of Javascript)

Operators

A Special Function that syntactically (written differently)- Generally they take two parameters and return one result Operators are functions which uses InFix Notation (+, -, /, *, <, >)

Prefix Notation: +(3, 4);
Postfix Notation: (3 , 4)+;
InFix Notation: (3 + 4); - Javascript uses Infix Notation

Operator Precedence

Which Operator Function gets called First (Functions are called in order of precedence - HIGHER precedence wins)

Associativity

What order operator functions gets called-in: Left-to-Right or Right-to-Left
Reference: * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Operator_Precedence * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

Coercion

Converting a value from one type to another
This happens quite often in Javascript as its Dynamic Typed

Existence and Boolean

The Coercion within if statements will resolve to Boolean.

Boolean(null) --> false
Boolean(undefined) --> false
Boolean(0) --> false

Default Values

name = name || 'your Name here'

Conditional Operator mentioned above sets the name variable to '' when the passed in name argument is null (or) undefined (or) 0

Arguments

console.log(arguments);
The above statement, we print "arguments" supplied to the function
console.log(arguments[0]);
console.log(arguments.length);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment