Skip to content

Instantly share code, notes, and snippets.

View tekaratzas's full-sized avatar

Thomas Karatzas tekaratzas

View GitHub Profile
@tekaratzas
tekaratzas / inheritanceAndIterating.js
Last active July 21, 2017 19:40
Different Ways of iterating through lists.
// Adding a property to the global Object => all objects inherit from this. ex: toString method and prototype.
Object.prototype.WTF = "this should not be in your object";
function a() {
this.unwanted = 10;
this.crap = "dhjbjbfdjbf";
}
function child() {
this.a = 1;
@tekaratzas
tekaratzas / anonymouswrappers.js
Last active July 24, 2017 13:56
Anonymous Wrappers and Namespaces
(
// evaluate the function in the parenthesis
function(){}
// return the evaluated function object
)() // call it immediately
// The same functionality can be done as follows;
!function(){}()
+function(){}()
(function(){}());
@tekaratzas
tekaratzas / scopesAndReferences.js
Last active July 21, 2017 18:46
Exploring Scopes And namespaces in JavaScript
var foo = 12;
function changeFoo() {
foo = 34; // changes global scope and not local scope!
}
changeFoo();
console.log(foo);
@tekaratzas
tekaratzas / thisHell.js
Last active July 24, 2017 13:19
Where "this" gets weird in JS
function test() {
this.arr = [1,2,4];
this.message = "I am here";
this.fun = function() {
this.arr.forEach(function(item) {
console.log(this.message); // will print undefined 3 times since this refers to the global object
});
}
}
@tekaratzas
tekaratzas / 5WaysOftThis.js
Last active October 15, 2017 22:43
The different ways "this" is used in JavaScript
// 1
console.log(this); // refers to the Global Object aka window
// its methods include prompt alert confirm etc...
// 2
function test() {
console.log(this);
this.method = function inner() {console.log(this)};
}; // Here again "this" will refer to the global object
test();
@tekaratzas
tekaratzas / typeofHell.js
Last active July 24, 2017 13:20
Showing the inconsistent behavior and a much better alternative
console.log(typeof "foo" === "string"); //true
console.log(typeof String("foo") === "string"); // true
console.log(typeof new String("foo") === "string"); // false
console.log(typeof 1.2 === "number"); //true
console.log(typeof new Date() === "Date"); //false Date is an Object
console.log(typeof [1,2,3] === "array"); //false, an array is on object!
/** Proper way to test type of object **/
function is(type, obj) {
@tekaratzas
tekaratzas / comparisons.js
Last active July 24, 2017 20:59
Difference between "==" and "===" in JS.
// examples with ==
1 == "1" // true
"/t" == 0 // true
"34" == 2 // false
new Number(10) == 10 // true
Number(10) === 10 //true
// examples with ===
@tekaratzas
tekaratzas / semi-colon.js
Last active July 24, 2017 13:24
Semi-Colon Hell Javascript
/**
Here, the parser will add a semi colon after return causing the function to return undefined.
**/
function test(){
var name = "Hello";
return // it will add a ; here
{
name: name
}
}