Nikola Brežnjak blog - Tackling software development with a dose of humor
  • Home
  • About me
Home
About me
  • Nikola Brežnjak blog
  • Home
  • About me
CodeSchool, JavaScript

Codeschool JavaScript Best Practices Notes

I finished the course at CodeSchool, and below are my notes from it.

Level 1

Ternary howto with SIAF

var allPacked = true;
var readyToGo = true;
var adventureTime;

adventureTime = allPacked && readyToGo ?

  function( ){
    return "Adventure time is now!" ;
  }()
  :
  function( ){
    return "Adventuring has been postponed!" ;
  }() ;

console.log(adventureTime);

Short-circuting, if the this.swords is not empty it takes it immediately, without looking at the thing after the ||

this.swords = this.swords || [];

Same goes for &&, as soon as it finds a first falsy value – it returns that. If all falsy, it returns the last one.

Level 2

If you need lengthy, repetitive access to a value nested deep within a JS Object, then cache the necessary value in a local variable.

var numCritters = location.critters.length;
for(var i = 0; i < numCritters; i++){
      list += location.critters[i];
}

//instead of
for(var i = 0; i < location.critters.length; i++){
      list += location.critters[i];
}

//and even better
for(var i = 0, numCritters = location.critters.length; i < numCritters; i++){
    list += location.critters[i];
}

Put script tag just before the ending body tag, or you can also leave them in the head section, but add async keyword. Use a list of variables after the keyword var all at once! Use function join() on the array instead of concatenation. with +=. console.time(“string”) is the opening statement to a timer method that will help us measure how long our code is taking to perform. console.timeEnd(“string”) ends it and prints how long it took. “string” has to be the same in both cases.

var now = new Date();

console.log(+now) == console.log(new Number(now));

 Level 3

 === compares type and content. instanceof – userful to determine, well, the instance of some object 🙂

function Bird(){}
function DatatypeBird(){}
function SyntaxBird(){}
DatatypeBird.prototype = Object.create(Bird.prototype);
SyntaxBird.prototype   = Object.create(Bird.prototype);

Runtime error catching:

try{
   if(someVar === undefined)
        throw new ReferenceError();
}
catch(err){
    if(err instanceof ReferenceError)
        console.log("Ref err:" + err);

    //TypeError
}
finally{
    //this will execute no matter what
}

Avoid eval, with.

Use num.toFixed(2), parseFloat(), parseInt(num, radix). Radix can be from 2 – 36. typeof along with isNan to determine if the number is trully a number.

Level 4

Namespace is an object that groups and protects related data and methods in JavaScript files.

Say you have a code like this:

var treasureChests = 3;
var openChest = function(){
    treasureChests--;
    alert("DA DADADA DAAAAAAA!");
};

you can use namespacing like this:

var DATA = {
	treasureChests : 3,
	openChest : function(){
	    this.treasureChests--;
	    alert("DA DADADA DAAAAAAA!");
	}
};

You then call the function like this: DATA.openChests().

Closures are a feature of JavaScript, used to cause some properties to be private, bound only to a surrounding function’s local scope, and some properties to be public, accessible by all holders of the namespace.

Private properties are created in the local scope of the function expression. Public properties are built within the object which is then returned to become the namespace. Access to private data is thus possible only because of closure within the larger module.

Say you have a code like this:

var CAVESOFCLARITY = {
  stalactites: 4235,
  stalagmites: 3924,
  bats: 345,
  SECRET: {
    treasureChests: 3,
    openChest: function(){
      this.treasureChests--;
      alert("DA DADADA DAAAAAAA!");
    }
  }
};

You would make it into a closure like this:

var CAVESOFCLARITY = function () {

  var treasureChests = 3;

  return {
    stalactites: 4235,
    stalagmites: 3924,
    bats: 345,
    openChest: function () {
        treasureChests--;
        alert("DA DADADA DAAAAAAA!");
    }
  };
}();

If a module references globally-scoped variables, it’s a best practice to bring them into the scope of anonymous closure through the use of a specific technique called global imports.

Say the code is like this and uses a global variable named globalAnswer:

var MySomething = function () {
  var a = 3;

  return {
    getA: function() {return a; },
    summon: function(){
      if(globalAnswer === "42"){
        alert("YEP!");
      }
      else{
          alert("NOPE");
      }
    }
  };
}();

You would rewrite this using global imports like this:

var MySomething = function (answer) {
  var a = 3;

  return {
    getA: function() {return a; },
    summon: function(){
      if(answer === "42"){
        alert("YEP!");
      }
      else{
          alert("NOPE");
      }
    }
  };
}(globalAnswer);

Your import ensures clarity of scope within a module. By using a parameter, you protect the global data that might have been overwritten. All imported data becomes locally scoped to the anonymous function, to be used in closure. Thus, when compared with searching the entire scope, import are both clearer and faster.

Augmentation is the term for adding or changing properties in a module after the module has already been built.

In simple augmentation, the module file and the augmentation file do not share their private state. Augmented module properties may only access the private data from their file’s closure. Private data from the original closure will not be lost, and will be accessible to all original properties that referenced it.

Miscellaneou$

Smarterer API is now FREE to use

Smarterer released its API for free. Even if you’re not into programming, you can still make use of this and give your site visitors a quick skill test (in just 10 questions and 120 seconds), by using their Smarterer Widget Builder.

Simply, search for a test and optionally name it:

smartererSearch

and embed it to your widget area (wp terminology) on your site/blog:

smartererCreate

Here are few examples you can try:

JavaScriptnode.jsAngular JS

Miscellaneou$

MacBook 12 keyboard fiasco

I love you Apple and all, but honestly I don’t know dafuq was it with the person who approved this keyboard – namely the keys for up/down/left/right. I mean, have you ever used this?! Like, in real life, no just an image in Photoshop?!

Jeez, imagine typing on a full scale size keyboard for 20 years and now, what do you know, someone makes this utter garbage, arrrgh! On one of my previous laptops (HP G6) they made the same mistake and never went back to it again.

I didn’t like the small movement keys on Air either, but that was manageable since all were the same size, but with this – tears and pain :/

I see people hitting the SHIFT key waaay more often now :/. Blame the 20 year muscle memory 😛

On the bright side of life, iWatch  looks nice – we’ll just have to wait a bit longer till they do something with the battery.

Miscellaneou$

100th post

Nothing, just saying 🙂

Ok, jokes aside, this has been a nice journey for me. It all started with the post Carcassonne scoring board application which I decided to post after reading James Clear’s post on why we should make things.

Top 10  popular posts until now:

  • How to get started on the MEAN stack (written for HackHands.com and featured in NodeWeekly)
  • Delving into Node.js and Express web framework (written for HackHands.com)
  • MEAN.io VS MEAN.js and deploying the latter on DigitalOcean (written for HackHands.com)
  • Deploying MongoDB and Node.js application on OpenShift (written for CodeProject.com)
  • How I built my own testable The Answer To Life The Universe And Everything npm module (written for CodeProject.com)
  • Build a font viewer application in WPF without writing any C# code (written for CodeProject.com)
  • Using CasperJS on Webfaction to automatically send emails with attached images via Gmail (written for CodeProject.com)
  • How to delete node_modules folder on Windows machine
  • Enable continuous scrolling by default in Adobe Reader
  • Git push origin master could not read username for http://github.com

 

Miscellaneou$

Sleep you must, yoda so says

Post from James Clear here: http://jamesclear.com/better-sleep

In the words of the researchers, sleep debt “has a neurobiological cost which accumulates over time.” After one week, 25 percent of the six-hour group was falling asleep at random times throughout the day. After two weeks, the six-hour group had performance deficits that were the same as if they had stayed up for two days straight. Let me repeat that: if you get 6 hours of sleep per night for two weeks straight, your mental and physical performance declines to the same level as if you had stayed awake for 48 hours straight.

The irony of it all is that many of us are suffering from sleep deprivation so that we can work more, but the drop in performance ruins any potential benefits of working additional hours.

Hacker Games, JavaScript

JavascriptBattle

Lately I’ve been playing at JavascriptBattle, which is

a fun and engaging web application intended to make artificial intelligence (AI) design accessible to all. Every day, your code will be pulled down from your “hero-starter” repository on Github. Your code (along with every other user’s code) will be run daily, behind the scenes, in our game engine.

Basically, you write JavaScript code for your hero in order to instruct him how to behave when for example his health drops to a certain level, or when enemies are close, etc. and then you participate in a daily battle. They have various stats, and as it turns out I’m currently on position #3 for average damage dealt, yay me!

JavascriptBattle

 

Anyways, it’s cool so feel free to check it out and take me down from the pedestal :P. If you happen to like these “hacker games” then do checkout the one I made for my university project back in the old days 1415131129_smiley-evil.

Hacker Games

Topcoder Scavenger Hunt

I just competed (and finished! – I’m Hitman666) a Topcoder Scavanger Hunt.

topcoderScavangerHunt

Anyways, you have the instructions on how to play on the link above. I’ve really missed these kind of “hacker games”, like back in the days I was very active on hackits.de, but that site is long down now. Anyone playing similar games today, which you can recommend? I made my own for the project on university: http://nikola-breznjak.com/challenge/.

The questions were quite cool (no, no answers here, you’ll have to research it yourself):

  • How many ‘Albert’ monkeys died in the US Space program?
  • What was the original name of Nintendo’s Super Mario?
  • How many female fighter pilots were there in the original Star Wars trilogy?
  • How many different combinations of coins are possible for the US dollar?
Miscellaneou$

Ekobit DevArena 2014

Here are my notes (on Croatian) from the DevArena 2014 hosted by Ekobit. The bolded bullet points were, you guessed it, topics. All in all, a very well organised developers conference.

  • Otvoreno o softerskom inženjerstvu i profesionalizmu
    • Leveli
      • level 0: continuous integration, unit testing
      • level 1: TDD, refactoring
      • level 2: coding standards
    • Testing stuff
      • https://github.com/Moq/moq4 – mocking library for .NET
      • Unit testing FTW!
      • http://sandcastle.codeplex.com/ – doxi iz unit testova; New => Help Project
      • Ne diraj ako nema testova, osim Right click => Extract to Method in VS
      • CodeRush & ReSharper
      • Code Contracts
  • Application insights
    • za sad jos samo u preview modu i samo za web http://stackoverflow.com/questions/26099664/vs2013-application-insight-for-desktop-applications/26544013#26544013
    • ALM – application lifecycle management
    • omogucava provjeru dostupnosti, performansi, koristenja
    • cilj: smanjiti MTTD (mean time to detect) errora
    • servis se obavezno vrti na Azureu
    • Add New project => Web performance and load Test project
    • log4net nugget + insights appender
    • Visual studio online
    • Azure is the way to go!
  • PRISM
    • instalacija preko NuGet-a
    • poznat još https://cinch.codeplex.com/, ali je kao jednostavniji, dok Prism (kompleksniji) im je jako se dobro uklopio u to dok su morali napraviti samo neki dio aplikacije da bude naplatni
    • napravljen po TDD i postoji source code
    • https://unity.codeplex.com/ i http://msdn.microsoft.com/en-us/library/dd460648(v=vs.110).aspx => bootstraping
    • prism inace ima sljedece patterne
      • addapter
      • app controller
      • command
      • composite and composite view
      • DI
      • IOC
      • Event aggregator
      • Facade
      • Observer
      • MVVM
      • Registry
      • Repository
  • Razvoj web i mobilnih multimedijskih aplikacija na HTML 5 platformi
    • http://middle-earth.the-hobbit.com, https://github.com/mbostock/d3/wiki/gallery
    • web browser će postati OS
    • video, audio tag
    • Grafika na webu:
      • Canvas
        • samo elementarno, requestTimeFrame
        • problem skaliranja slike
      • SVG
        • skaliranje slika
        • svaki element moze imati neki filter, npr. blur
        • ima animacije (<set>, <animate>)
        • IE 10 ima probleme s animacijama
      • ChartJS, CanvasJS, EASEJS, Fabric, Paper, Processing, Kinetic, JustGauge, $.plot chart
      • WebGL
        • grana OpenGL-a
        • direktan pristup GPU – high performance, but compli freakin cated
        • https://github.com/begedin/DiceAndRoll – PHASER!
  • Što je novo u XAML-u i XAML alatima za Visual Studio
    • NIŠTA
    • CPU usage tool with support for WPF (update 2 u VS2013)
    • .NET Managed Memory Analyzer
  • IoC i DI
    • Inversion of Control
    • Dependency Injection
    • Unity IOC, Windsor, Structure Map, nInject
    • AOP – aspect oriented programming
Miscellaneou$

Love you Apple but hasn’t this gone too far?

Love you Apple, I really do, but this video is just too true! Since you’ve allowed that I install iOS8 on my beloved 4S (unfortunately the best and last normal sized phone you’ve made [I know it’s not your fault, it’s what market demands, but still it “feels” wrong]) I have all but good words for it. Slow this, slow that, apps crash which never before crashed, the list goes on… Sure, I understand, my phone is 3 years old so what you’re (subtly) saying is that I should update. But why should I, if I’m perfectly fine with this one (and Androids just don’t resonate with me) go and buy a new one? That being said I think you should really allow us (and yes, there is more of us) to downgrade to iOS7.

There, my 0.02$.

IDIOTS from BLR_VFX on Vimeo.

Miscellaneou$

ALS Ice bucket challenge

[vcfb id=10203881466450662]

Fala Philip Taylor na nominaciji. Ja nominiram Miljenko Bistrovic, Luka Mesarić i Denis Jelenčić.
Ko nezna za kaj se ide, nek pročita: http://www.vecernji.hr/hrvatska/i-u-hrvatskoj-pocelo-skupljanje-novca-za-oboljele-od-als-a-957366 (tu imate i broj žiro računa). Inače, slažem se i s Seth Godin koji ima ovo za reći po tom pitanju: http://sethgodin.typepad.com/seths_blog/2014/08/slacktivism.html; ali ako drugo niš, podigla se barem svijest o tome… There, my $.2, well actually 100, but who cares as long as it’s for a good cause, right? – I won’t miss it and it just might help someone…

Page 8 of 9« First...«6789»

Recent posts

  • Why Strange Images Make You Remember Better
  • Productivity tip: rate things 1-10 without 7
  • Productivity: Paper, Pomodoro, Kanban, Tracking, and actually showing up
  • The Keyboard Layout That’s Making Us Type Slower
  • Stop Tabbing. Start Using Your Monitor

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (36)
  • Daily Thoughts (78)
  • DevThink (2)
  • Go (3)
  • iOS (5)
  • JavaScript (128)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (3)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (84)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (44)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (82)
  • Unity3D (9)
  • VibeCoding (2)
  • Windows (8)
    • C# (2)
    • WPF (3)
  • Wordpress (2)

"There's no short-term solution for a long-term result." ~ Greg Plitt

"Everything around you that you call life was made up by people that were no smarter than you." ~ S. Jobs

"Hard work beats talent when talent doesn't work hard." ~ Tim Notke

© since 2016 - Nikola Brežnjak