ES6-let and const

Variable- Formally known as binding as a name is bound to a value inside a scope.

Block Level Scoping- Variables that are inaccessible outside a given block scope. Also known as lexical scope. Created inside these following places:

  • Inside a function
  • Inside a block({})

Introducing let declarations- The syntax is same as the var. let declarations are not hoisted onto the top of enclosing block. It’s best to place them first in the block so they are accessible to the entire block.

Cannot Redeclare the variable like we do in var

1
2
3
4
5
6
7
8
9
var count = 40;
var count = 20;
//No Error even in strict mode
let count = 20;
//Error-Identifier 'count' has already been declared with var. Error-If in the same scope or block;
let foo = 20;
let foo = 30;
// Error- Identifier 'foo' has already been declared

const declaration - Variables declaring const are considered constants meaning their values cannot be changed once set. const is block level variable and it’s declarations is not hoisted as well.

1
2
3
4
5
6
// Valid Declaration
const count = 20;
count = 10;
// Error- Assignment to constant variable.Cannot be assigned to a new value later.
const foo;
// Error-Missing Initialization

The value a const hold can be modified if it’s an Object. const prevents modification of the variable not modification of the bound value.

1
2
3
4
5
6
7
8
9
10
const obj = {
name:"John"
}
obj.name = "Jane";
// No error
// Throws an Error.
obj = {
name:"Jane"
}

Temporal dead zone(TDZ) - let and const bindings are not hoisted so they can’t accessible before their declaration. Any attempt to access the variable results in runtime error.

1
2
3
4
if(true){
console.log(typeof count); // Throws an Error
let count = 10;
}

Block binding in loops- Only the loop will have access to the count variable and is meant to use only inside the loop.

1
2
3
4
5
6
7
8
9
10
11
12
var a = {};
for(var i = 0 ; i < 5 ; i++) {
a[i] = function(){console.log(i);}
}
a[0](); // 5
a[1](); // 5 // The reason is i is shared across each iteration of the loop meaning all the functions hold a reference to the same variable.To fix this developers used IIFEs to force a new copy of the variable each time
for(let i = 0 ; i < 5 ; i++) {
a[i] = function(){console.log(i);}
}
a[0](); // 0 Block Scope Binding simplifies this problem for us. This loop works the same as the IIFE but a lot cleaner code.let creates a new variable each time
a[1](); // 1

const behaves differently in loops. If we use const in a for loop it will throw an error after the first iteration but it can be used with for-in loop(because the loop creates a new binding on each itertion ) and works the same way as let.

Global block binding - When var is used in the global scope it creates a new global variable which is a property on the global object(window in browser) that means we can accidentally overwrite an existing global using var.

1
2
3
4
console.log(window.RegExp); // function RegExp() { [native code] }
var RegExp = 20;
console.log(RegExp); // 20 Original RegExp is overwritten by our var declaration.
console.log(window.RegExp); // 20

if we use let or const instead in the global scope a new binding is created in the global scope but no property is added to the global object. This means we cannot overwrite a global variables. This makes let and const much safer to use in the global scope.

Best practice - use const by default and only use let when you know a variable value need to change. The rationale is the most variables should not change their value after initialization because unexpected value changes are a source of bugs.

Styling In React

Styling in React is a little different than usual. It’s core idea id to have our app visual pieces be self contained and reusable. That is why all of our HTML,CSS and JS all are in the same little black box we call component.

They way you specify styles in component is to define an object who properties are the same as we define the normal CSS properties and then assign the object to the JSX element by using the style attribute.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import React from 'react';
import ReactDOM from 'react-dom';
class Superhero extends Component {
render() {
const Style = {
backgroundColor:this.props.color,
fontFamily:"Open Sans",
fontSize:90
}
return (
<div style={Style}>
{this.props.children}
</div>
);
}
}
ReactDOM.render(
<div>
<Superhero color='blue'>Superman</Superhero>
<Superhero color='green'>Hulk</Superhero>
<Superhero color='black'>Batman</Superhero>
<Superhero color='yellow'>Iron Man</Superhero>
<Superhero color='red'>Flash</Superhero>
</div>,
document.getElementById('root')
);

Single word CSS properties(like padding, margin, color) remains unchanged and Multi word CSS properties(like font-family, font-style, background-color) are turned into camel case words with the dash - removed. As you can see above we didn’t use the px suffix in our style property. React allows us to omit the px suffix for a bunch of CSS properties.

Now if you preview this in the browser this will output as:

stylingreact

Pretty Cool Right!!!

React Gotcha:

If you need to specify a Vendor-prefixed version of a CSS property instead of first letter being camelCase like this webkitFilter, the first letter is actually capitalized like this WebkitFilter
We can even specify a separate background color for each of our Superhero’s.

For further information checkout the docs

fin!

React-JSX

JSX

JavaScript syntax extension. It produces react elements.

1
2
3
4
5
6
7
const element = <h1>Hello, world!</h1>; // Babel compiles this JSX code into the Javascript code written below
var element = React.createElement(
'h1',
null,
'Hello, world!'
);

Javascript expression can be embedded in JSX using the curly braces {}

1
2
3
4
5
6
7
8
9
10
11
function person(name) {
return `Hello ${name}`
}
var element =<div>{person("mohit")}</div>
ReactDOM.render(
element,
document.getElementById('app')
);

After compiling JSX expressions become regular JS objects.

Attributes in JSX

We can use quotes "" to specify string literals as attributes or using curly braces {} to use JS expressions in an attribute.

React elements are immutable. These are the smallest building blocks of react app. Components are made of elements

All React components must act like pure functions with respect to their props.

Scope

Scope

Where to look for variables. JavaScript is a compiled language. It is complied every time.

var foo = "bar"

Grammatically this is a single statement but for JS engine it is 2 different statements. In the first statement JS engine will initialize the variable foo when it is compiling our code and then in the second phase the execution phase variable foo will be set to a value which in this case is the string “bar”.

Undefined means it doesn’t currently have a value like an empty place holder.But it definitely has a declared variable.

As of ES3 the catch clause is a block scope. A caveat in ECMASCRIPT. Linter still don’t understand the nuance of block scope catch variables.

1
2
3
catch(err){
console.log(err); // TypeError
}

Lexical Scope

It means compiled time scope. Where your variable sits lexically. All the scope decisions will be made during the compiled phase.

Dynamic Scope(this)

1
2
3
4
5
6
7
8
function foo() {
console.log(bar); //foo
}
function baz() {
var bar = "foo";
foo();
}
baz();

As we see in lexical scope in function foo that would give an error because the bar doesn’t exist but in dynamic scoping function foo will look for bar in the function it is being called.

The decision for how scoping works in dynamic scoping is a runtime decision as opposed to lexical it’s a author time decision.

eval

A way to cheat the lexical scoping model that JavaScript has(eval parses it’s argument in statement context)

1
2
3
4
5
6
7
8
var bar = "bar";
function foo(str) {
eval(str); //cheating
console.log(bar); //42
}
foo("var bar = 42;");

We are passing variable declaration in the form of string in the function foo eval cheats it and pretends that the line of code has existed at compile time. It modifies the existing lexical scope of ‘foo’ and add a new declaration to it at run time.Which will then modify the existing scope.

Just by having eval present in code JS engine will have to disable some of it’s optimizations.

In strict mode it will not disable the optimizations but it will create a new scope for the eval statement.

with Keyword

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var obj = {
a: 2;
b: 3;
c: 4;
};
obj.a = obj.b + obj.c;
obj.c = obj.b - obj.a;
with(obj) {
a = b + c;
c = b - a;
d = 3;
}
obj.d; //undefined
d; // 3

As we can see we are repeating the obj reference again and again so to shorthand that we use the with keyword. It can make our code shorter and nice but there are some problems. On line 13 we are intending to create a d property on our obj Object.

But that’s not how it works it’s first gonna ask the Object obj if it’s got a reference to the d variable and that’s gonna say NO to it so it will go to the outer scope which in this case is the global scope and ask for the reference again. In this case global scope will say YES! I JUST MADE ONE FOR YOU.

With Keyword at runtime is creating a whole new lexical scope which will then effect our JS engine and it will disable it optimizations.

In strict mode with keyword is completely disallowed altogether.

Hoisting

Conceptual model how JS works. It’s not physically what actually happens. In ECMASCRIPT specifications there’s no mention of word hoisting anywhere. It’s a mental construct that we have invented to explain the behaviors of JS.

So the JavaScript engine has two phases one is compiled phase and the other one is execution. All the variable and function are defined or we can say hoisted during the compiled phase.

Recursion wouldn’t have been possible without hoisting. Like header files we put in the C program are manual hoisting. As compared to JS engine which automatically hoist the values.

this

Every function while executing has a reference to it’s current execution context called this. There are 4 rules for how the this keyword gets bound. They all depend on what we call the CALL SITE. A placing code where a function gets executed.

Default binding rule- Where the function call is right there after declaration like a normal function call. If we are in strict mode default the this keyword to an undefined value if we are not in strict mode default the this keyword to global object.

Implicit binding rule - When there is an Object property reference at the call site the containing object will become this binding.

Explicit binding rule- If we use call or apply at the call site both of these methods take this binder as their parameters then the this will point to that Object.

Hard Binding rule- Here the this will refer to obj even though we called obj2 in the last line with the call method. This is called hard binding. hiding the original function with a function expression which calls the original function but with a context bound exactly, because both have the same name you can’t have two references with the same name

one will be hiding the other one.but function foo still alive, and orig is making reference to it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function foo(){
console.log(this.bar)
}
console.log(foo)
var obj = {bar :"bar"}
var obj2 = {bar :"bar2"}
var orig = foo
foo = function(){
orig.call(obj);
}
console.log(orig)
console.log(foo)
foo(); //bar
foo.call(obj2); // bar

new

When we put the new keyword in front of any function call it magically turns that functional call into a constructor call.when we put a new keyword in front of a function call

  1. A brand new empty is jut magically created out of thin air.

  2. That brand new object gets link to a different object.*

  3. The brand new object gets bounds as this keyword for the purposes of that function call.

  4. If that function otherwise doesn’t return anything it will implicitly insert a return this.

1
2
3
4
5
function Cat(name , color){
this.name = name;
this.color = color;
}
var cat = new Cat(fluffy , white);

this keyword refers to an object. That object is whatever object is executing the current bit of code. by default that is the global object.

So when we executed this Cat function this was referring to a new empty object. That what new keyword does for us. It creates a new empty JS object. Sets the context of this to that new object and then calls the cat function.

So this Cat functions are commonly called constructor functions

Object-Oriented-JavaScript

Is a way of logically organizing our code in a way that makes sense with respect to the problem we are trying to solve

Every Single ‘object’ is built by a constructor function. Each time a constructor is called a brand new object is created. A constructor make an object linked to it’s own prototype.

Constructor- A constructor is simply a function that uses new to create an object. Any function can be a constructor . By convention constructor in JS begins with a capital letter to distinguish them from non constructor functions.

var object = new Object();

Objects are reference type and reference types do not store the object directly into the variable to which it is assigned, so the object variable in this example doesn’t actually contain the object instance. Instead it holds a pointer(or reference) to the location in memory where the object exists.

When you are assigning an object to a variable you are actually assigning a pointer. That means if you assign one variable to another, each variable gets a copy of the pointer and both still refer the same object in memory.

Best way to identify an array. We can use instanceof as well but it doesn’t work in the case when we are passing an array from one frame to another.

var arr = [ ] ;
Array.isArray()

With primitive wrapper type , properties seem to disappear because the object on which the property was assigned is destroyed immediately afterwards.

Functions

What distinguishes function from any other object is the presence of internal property named [[call]]. This property is unique to functions and indicates that object can be executed.

function overloading is the ability of a single function to have multiple signatures. Thus a single function can have one signature that accepts a single string argument and another that accepts two numeric argument. The language determined which version to call based on the arguments passed in. But JS can accept any number of parameters and type aren’t specified at all. So JS doesn’t have signatures which means lack of function overloading.

In JavaScript, however, when you define multiple functions with the same name, the one that appears last in your code wins. The earlier function declarations are completely removed, and the last is the one that is used.

But we can mimic function overloading in JS.

The Call() Method

Function method for manipulating this which executes the function with a particular this value and with specific parameters. First parameter is the value this should be equal and all subsequent parameters are parameters that should be passed into the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function sayNameForAll(label) {
console.log(label + ":" + this.name);
}
var person1 = {
name: "Nicholas"
};
var person2 = {
name: "Greg"
};
var name = "Michael";
sayNameForAll.call(this, "global"); // outputs "global:Michael"
sayNameForAll.call(person1, "person1"); // outputs "person1:Nicholas"
sayNameForAll.call(person2, "person2"); // outputs "person2:Greg"

The apply() Method

Second method for manipulating this . Works exactly the same as call except that it only accepts two parameters: the value for this and an array or an array like object for parameters(that means we can use arguments object as well)

1
2
3
4
5
6
7
8
9
10
11
12
13
function sayNameForAll(label) {
console.log(label + ":" + this.name);
}
var person1 = {
name: "Nicholas"
}
var person2 = {
name: "Greg"
};
var name = "Michael";
sayNameForAll.call(this, ["global"]); // outputs "global:Michael"
sayNameForAll.call(person1, ["person1"]); // outputs "person1:Nicholas"
sayNameForAll.call(person2, ["person2"]); // outputs "person2:Greg"

Call and bind doesn’t create copy of the function they executes them right away.

The bind() Method

Third method for changing this is bind. It behaves quite differently than other two. The first argument of bind is the this value for the new function.All other arguments represent named parameters that should be permanently set in the new function. We can still pass in any parameters that aren’t permanently set later.

Dereferencing Object

JavaScript is a garbage-collected language, so you don’t really need to worry about memory allocations when you use reference types. However, it’s best to dereference objects that you no longer need so that the garbage collector can free up that memory. The best way to do this is to set the object variable to null.

var object = new Object();

// do something

object = null

Here Object is created used and finally being set to null.

Prototype

A function’s prototype is the object instance that will become the prototype for all objects created using this function as a constructor.

An object’s prototype is the object instance from which the object is inherited.

functions(){}

Functions()

Functions are Objects with a special property through which we can invoke the code within them.

1
2
3
4
5
6
7
8
9
function foo(a , b) {
// function Declaration. 'a' and 'b' are called the parameters passed to the function. Parameters are like placeholders. These are variable that don't have a value until we assign a value in the arguments.
console.log(a);
return a + b;
// function body. This is what will be executed when we invoke the function. Function body never runs unless until it is called.
}
foo(12 , 12); // 24
//Function call/Invoking the function with '()' parenthesis and what passed through these are called arguments. Even if we have 2 parameters we can have multiple arguments because JS is really flexible and it doesn't mind the extra arguments. It will just ignore the extra ones.

Return/Side Effect

Once the function hits return statement it will immediately exits from the function. If the function don’t have a return statement it will return undefined. Rest of the statements are in the function body are called the side effects. Like the console log statement.

arguments

It’s build in JS keyword which is an array like structure. It acts like an array, looks like an array but it isn’t exactly an array. It doesn’t have all the features of an array like the array METHODS but it does have the length property
So we can have different type of scenarios with arguments like if

=== 4``` then do this or `else if` ```arguments === 5``` then do that
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
### Constructor
Constructor is a function that returns an `Object`.
### Scope
It defines where we can access a variable. Where to look for a variable.
To declare a global variable inside a function
1. leave the `var` and just declare the variable it will be global
2. We can attach it to the window object as well. window.__
A child function can access the variable of it's parent functions but a parent can not access the child's variables. A function can go outside to look for the variable but it can't go inside another functions to look for it.
```javascript
function foo(num) {
return function add(num1) {
return num + num1
}
}
foo(12)(12); // 24

Here the function add will have access to the variable num because a child can access it parents variable but function foo can not have access to variable num1. It’s not in it’s scope

Closure

Closure is when a function “remember” it’s lexical scope even when the function it executed outside that lexical scope.

Closure is a process in which the child function(function which is being returned) will have access to the variables of it parent function even though the parent function is executed and off the execution stack.

Recipe to Create Closure

1.Create a Parent Function.

2.Define some variables in the parent’s local scope.

3.Define another function inside the parent function(Child function).

4.Return the function from inside the parent function.

1
2
3
4
5
6
7
8
var innerVar = "Global Scope";
function parent() {
var innerVar = "Local Scope";
function child() {
return innverVar;
}
return child;
}

It’s like taking advantage of the scope. Works the same even if we are returning Objects instead of functions

Arrays

[Arrays]

Another type of data structure in which we can store data. Can store any type of data that includes functions and objects as well.

Declaring an Array

1
var arr =[]; // This is known as Array literal syntax.

Adding Properties to an Array

1
arr[0] = true; // Boolean at index zero. Array Index starts with Zero
1
arr[1] = 'Hello'; // String at index 1
1
arr.push({name :'John'}) // We can also push to add properties to an array.Here we are adding an Object which we declared with Object literal syntax on the fly.This Object is going to be at index 2

Delete a property

1
arr.pop(); // It's gonna delete the last porperty of the Array. In this case the Object that we just pushed into the array will be deleted.

Array as an Object

Since Arrays are Objects we can add or remove properties to them just like we can in Objects.

1
2
3
4
5
6
7
arr['size'] = 2;
arr['0'] = "Hello";
// These both properties will be added to the array just like name value pairs in an Objects and we can iterate over these properties with a for in loop like Objects.
for(var prop in arr) {
console.log(prop); //
}

So adding a property to an Array is the same as adding a property to an Object. So the property ‘size’ is not an added index it’s just an property of the Array.

Length property

1
2
3
4
5
arr.length
arr['length']
arr[box.length-1]
arr.unshift //native array methods(function because we are calling it with a paranthesis)
arr.push(); // this can take miltiple arguments

Objects{}

Javascript objects are dynamic meaning they can change at any point during code execution. When a property is first added to an object JS uses an internal method called [[put]]which creates a spot in the object to store the property.

The result of calling [[put]] is the creation of own property. and when a new value is assigned to an existing property a separate operator called [[set]] takes place which replaces the current property with the new one.

To check if the property exists on an object we can use in . in operator checks for both own property and prototype property. To check only if the given property is own property we can use hasOwnProperty()

console.log("name" in Cat); // true

console.log("toString" in Cat); // true

console.log(Cat.hasOwnProperty('toString')) // false

console.log(Cat.hasOwnProperty('name')) // true

``

To delete a property on a object delete operator is used. delete will always return true each time regardless of whether the property existed or not!

delete Cat.name ; // this will delete the property.

Object property Descriptor

1
2
3
4
5
6
var Cat = {
name : 'fluffy',
color : 'white'
}
Object.getOwnPropertyDescriptor(Cat , 'name')
// Object {value: "fluffy", writable: true, enumerable: true, configurable: true}

Writable Attribute

It defines whether the properties value can be changed from it’s initial value. We can change the property attribute using the object define property method

1
2
3
4
Object.defineProperty(Cat , 'name' , {writable:false})
//Object {value: "fluffy", writable: false, enumerable: true, configurable: true}

Now if we try to change it console will throw an error but only in strict mode.

We change the name property on a object it’s pointing to like this

'name : {first : "fluffy , last : "fluffy"}'

Now we can change the properties on the object even though name property is read only. Since name is really just a pointer. When we make it read only we are only preventing that pointer from being changed.

We can prevent the object form being changes as well

Object.freeze(Cat.name);

Enumerable Attribute

Enumerable means we can loop over the properties of an object using for in loop

Object.defineProperty(Cat , 'name' , {enumerable:false})

There, now notice that even though I’m still looping over all the properties in my cat object that the name property was not actually returned in my loop. That is one of the main use cases for the enumerable property. Setting enumerable to false also makes it so the property does not show up in the object keys. You can look at an object’s keys like this. Now let’s just display that. Notice that object.keys returned an array with all the properties except notice that name is not showing up because it’s not enumerable. If we make name enumerable again, then you can see that it does show up in the object keys. Note that you can still look at the property with bracket notation. So setting enumerable to false does not change the ability to look at the property. You just can’t enumerate it, see it in the object’s keys, or serialize it.

Configurable Attribute

The configurable property locks down a property to prevent certain attributes from being changed. It also prevents the property from being deleted from the object.

Object.defineProperty(Cat , 'name' , {configurable:false})

If configurable is false for a property, you cannot change the enumerable attribute, you cannot change the configurable attribute, and you cannot delete the property. You can, however, change the property’s writable attribute.

getters and setters

Getters and Setters are a couple of pretty cool attributes on a property that allow you to specify the return value of a property using a function and set the value of a property using a function. But you can access the property just like you would any other property.

1
2
3
4
5
6
7
8
9
10
11
Object.defineProperty(Cat , 'fullName' ,
{
get:function(){
return this.name.first + " " + this.name.last;
},
set:function(value){
var nameparts = value.split(" ");
this.name.first = nameparts[0];
this.name.last = nameparts[1];
}
});

Extensible

It’s a boolean value that indicates if an object itself can be modified. All the objects that we create are extensible by default meaning new properties and methods can be added any time.By setting it to false we can prevent new properties from being added to an object.

1
2
3
4
5
var Cat = {
name : 'fluffy',
color : 'white'
}
Object,preventExtensions(Cat);

Now new properties can never be added to the function again.

Sealing Objects

A sealed object is non extensible and non configurable

Object.seal(Cat);

Freezing Objects

A frozen object is where you can not add or remove properties, you can’t change property types and you can’t write to any data properties. In essence a frozen object is a sealed object with data properties are also read only.

Hello-World

Hello World

This word has a significant meaning in the world of programming. Almost every developer who starts off their journey in programming use Hello World as their first program. It is traditionally used to introduce novice programmers to a programming language and you are saying to the world, that your programming environment is ready and that you have the basic understanding necessary to use it. Just like Hello World this is my first Hello World blog post. I will be posting about every resource, book, tutorial I came across during my journey in programming. The only purpose of this blog is to document all the learning material and my struggle along the way and share it with the developer community. I hope we all can learn new things from one another and I hope you find something helpful in my post’s that may help you in your journey.

Proudly powered by Hexo and Theme by Hacker
© 2017 Mohit Garg