Blog

The Key to Success

The answer you usually hear in speeches is “follow your passion”.

Bulls**t! The person saying that is almost always already successful and rolling in money thanks to a stroke of good luck.

The real answer is much harder:

Find something you’re good at and spend a few decades working your ass off!

And while you’re doing that you’re going to fail multiple times.
You’re going to work for people you hate. In jobs that suck the life from you.
You’re probably going to get depression.
And a mid-life crisis. Not to mention being hit by a few other crisis’s along the way.

You’re going to want to give up (many times). Then find enthusiasm aging. And give up.
You’ll be told you’re an idiot. And lose friends. Question yourself daily. And maybe have the odd good moment, only to be followed by more crap.

It is going to be a hard, often lonely, slog.

I know this:

I’m living it.

I’m not successful. Not the success I’m have in mind. But I want to me. I will me. I’m working hard for it. And if I don’t get it I’ll die trying.

Until then I work every day for it. Not 80 hour weeks – not anymore. That is, not wasted 80 hour grinds.
I’m still “working” every minute I’m awake, but I’ve learnt to re-focus some of that energy to other things: Learning. Thinking. Walking. Rest. Re-evaluation.

True success isn’t the founders of Facebook, Google or Tesla. They got lucky. Yes, the did some work, but not what the work everyone else has to do.

For the average person success is a lot a vision and a lot of guts, the ability to adapt, and the fortune to positions themselves to strike when opportunity is right.

And a hell of a lot of hard work and failure leading up to it.

I’ll be an overnight success some day…. 20-something years in the making.

Notesheet: ES6/ES2015+ (JavaScript)

Status: Work in Progress. Updated: 3 February 2020


Arrow Functions

  • Shorthand format for writing traditional functions.
  • Denoted by what some people call a “fat arrow”: =>
  • Removes the “function” keyword and often the “return” keyword and function block curly braces (“{” and “}”)
  • Formats can include:
    • () => { return …..; }
    • {x} => (return x+1; }
    • (x, y, z) => { if (x == 1} { return y; } else { return z; } }
    • Class.someFunction(x => x + 1);
    • var myFunction = x => x + 1;
    • var myFunction = x => { return x + 1; };
  • https://caniuse.com/#search=arrow%20functions

 

Traditional JavaScript function:

function sumOfNumbers(number1, number2)
{
  return number1 + number2;
}

 

ES2015 arrow function equivalent:

var sumOfNumbers = (number1, number2) => { var sum = number1 + number2; return sum * 2; }

 


Classes

Traditional “class” using a function

function Person(firstName, lastName)
{
  this.FirstName = firstName;
  this.LastName = lastName;

  this.GetFullName = function()
  {
    return this.FirstName + " " + this.LastName;
  }
}
var person = new Person("Bob", "Smith");
person.GetFullName();

ES2016 Class

class Person
{
  constructor(firstName, lastName) 
  {
    // FirstName and LastName properties are automatically created.
    this.FirstName = firstName;
    this.LastName = lastName;
  }
  
  /*
  *	Method to return the full name.
  */
  GetFullName() 
  {
    return this.FirstName + " " + this.LastName;
  }
}
var person = new Person("Jason", "Snelders");
person.GetFullName();

 

You can also define a property on the class like pre-ES2015, as in the following example.
Define it in the constructor() and you don’t have to pass a constructor parameter in to do anything with it (just give it a default value).
Then you can use the special “set” and “get” function to access it later. Or access it directly.
In this example “_displayName” is the defined property in question.
NOTE: You can’t use the same name for a property as the “set”/”get” function, so a good convention is to prefix the property with an underscore (“_”).
It’s still publicly accessible but represents a logically private property.

 

class User {
  constructor(username, password, loggedIn = false)
  {
    this.username = username;
    this.password = password;
    this.loggedIn = loggedIn;
    
    this._displayName = "";
  }

  set displayName(name) { this._displayName = name; }
  get displayName() { return this._displayName; }
  
  show()
  {
    console.log(`Username: ${this.username}`);
    console.log(`Password: ${this.password}`);
    console.log(`Logged In: ${this.loggedIn}`);
    console.log(`Display Name: ${this._displayName}`);
  }
}

// Create an object from the Class
const jason = new User("jason", "test123");

console.log("Show(1)...");
jason.show();

jason.displayName = "Jason Snelders";

console.log("Show(2)...");
jason.show();

jason._displayName = "Directly set _dislayName";

jason._displayName = "The Jason";

console.log("Show(3)...");
jason.show();

console.log(`Read directly from jason.displayName = '${jason.displayName}'`);

See it in action (open the Console) at https://codepen.io/jsnelders/pen/abOOGVe.

 


Define Variables: ‘let’ and ‘const (vs ‘var’)

  • Traditionally we only had ‘var’ keyword to define a variable.
  • ‘let’ is like ‘var’ but the variable is constrained to block scope – i.e. within the curly braces (“{” and “}”) it is defined between. For example, if() and for() statements.
  • ‘const’ is a constant with a value that is set at the time it is defined and that cannot be changes later.
    • The exceptions are:
      • arrays: values/elements within the array can be added and remove (but the whole array cannot be re-assigned).
      • objects: values of individual properties can be update, but the whole object cannot be reassigned.
  • https://caniuse.com/#search=let
  • https://caniuse.com/#feat=const

 

Simple var, let and const

var aVariable = "One";
const aConst = "Two"
let aLet = "Three"

console.log(aVariable);  // Display "One"
console.log(aConst);     // Display "Two"
console.log(aLet);       // Display "Three"
  
aConst = "Four";	 // No. You cannot change a constant. Will produce a "Assignment to constant variable" error.
  
aLet = "Five";
console.log(aLet); // Now displays "Five"

 

Scoping ‘let’

if (aVariable == "One")
{
  // A new variable 'aLet' is defined within only within the block scope of the if() statement.
  // It will not affect the value of 'aLet' defined above.
  let aLet = "New Let";
  
  console.log(aLet);	// Display "New Let".
}

// We cannot see the 'aLet' defined in the if() statement 
// so we display the value of 'aLet' defined in the out scope 
// (i.e. the original aLet).
console.log(aLet);	// Display "Three"

 

Arrays as constants

const array = [1, 2, 3];
  
console.log(arrayToString(array));  //Display 1,2,3
  
// We cannot do this - re-assign the array.
//array = [4,5,6];	
  
// But we can still add/remove individual items from the array.
array.push(7);
  
console.log(arrayToString(array));   // Display 1,2,3,7

 

Objects as constants

const person = {
  name: "Jason",
  age: "Old"
}
  
console.log(person.name);   // Display "Jason"
  
// We cannot re-assign the object (like the array).
//person = { name: "Bruce" };
  
person.name = "Bruce";
  
// But we can update individual properties on the object.
console.log(person.name);   // Display "Bruce"

 

Example: using ‘let’ in counters to preserve existing variables.

//-- Traditional variables
var i = "Cat";
  
console.log(i);   // Display "Cat"
  
for (var i = 0; i<=5; i++)
{
  // Do something
}
  
The original declaration of 'i' was re-purposed for the counter.
console.log(i);   // Display "5".
  

//-- ES2015 example with 'let'
  
let i = "Cat";
  
console.log(i);   // Display "Cat"
 
for (let i = 0; i<=5; i++)
{
  // Do something
  console.log(i);   // Will update and display increasing from "1" to "5" with each loop.
}
  
// The original definition of 'i' in the outer scope (outside the for() loop) is preserved.
console.log(i);   // Display "Cat".

 


Default Function Parameter Values

  • A default value can be specified on parameters in the definition (signature) of a function.
  • If the function is called and that parameter is missed, the default value will be used.
  • If a value is passed in to the parameter then the supplied value is used.
  • Parameters without default values must appear before the first default parameter.
    • e.g. This is wrong myFunction(param1, param2 = ‘some value’, param3) because param3 does not have a default value but it appears after a parameter that does have a default.
    • Why? Consider calling the function: myFunction(‘first value’, , ‘third value);. Having a blank parameter when calling a function is not not valid code.
  • https://caniuse.com/#feat=mdn-javascript_functions_default_parameters

 

Traditional function

function aboutMe(firstName, lastName, location)
{
  return "My name is " + firstName + " " + lastName + ". I come from " + location + ".";
}

// This will error because the 'location' parameter is not passed in.
var result = aboutMe("Jason", "Snelders");

 

ES2015 function with a default parameter value

function aboutMe(firstName, lastName, location = 'Woop Woop')
{
  return "My name is " + firstName + " " + lastName + ". I come from " + location + ".";
}

// The default value of "Woop Woop" will be used for 'location'.
var result1 = usingDefaultParameters("Jason", "Snelders");
console.log(result1);   // Display: My name is Jason Snelders. I come from Woop Woop.
  
// The provided value of "Melbourne" will be used for 'location'.
var result2 = usingDefaultParameters("Jason", "Snelders", "Melbourne");
console.log(result2); // Display: My name is Jason Snelders. I come from Melbourne.

 


Reset Operator in Function Parameters

Example function definition:

function myFunction(myName, ...roles) 
{ 
  console.log(roles); 
}

The 3 dots preceding ‘roles’ (…roles) is the rest operator.

So if we call the function:

myFunction("Jason", "Developer", "Architect", "Lead", "Consultant");

The console output of ‘roles’ from that function will be an array:

["Developer", "Architect", "Lead", "Consultant"]

 

 


Template Literals

  • A string surrounded by back ticks  (`).
  • The string can be split over multiple lines.
  • You can embed literal references to variables in the same scope that are replaced when the string is “rendered” (aka “variable/expression replacement” or “string interpolation”).
  • A good option for “+” operator based string concatenation.
  • Any expression in JavaScript can be used within the curly braces (“{…}”).
  • https://caniuse.com/#feat=template-literals
var name = "Jason";
var statement = `My name is ${name}`;

console.log(statement);   // Displays "My name is Jason"

var multilineStatement = `My name is ${name}
and I am a software developer`;

console.log(multilineStatement);   // Displays "My name is Jason
                                                and I am a software developer".

Alternative to concatenation:

Old style:

var createUrl = function(domain, path) { return "https://" + domain + "/" + path;  }

With string literals:

var createUrl = function(domain, path) { return `https://${domain}/${path}`;  }

 

Other expression examples

`2 + 2 = ${2 + 2}`
`It is ${new Date().getHours() < 12 ? 'AM' : 'PM' }`

 


Spread Operator (…)

Example:

const myArray = [1, 2, 3];
console.log(...myArray); // Displays "1 2 3" (the individual values of the array).

Example scenario:

function add = (a, b, c) => a + b + c;
const myArray = [1, 2, 3];
add(...myArray);  // Returns "7"

Using the spread operator splits myArray and assigned each of the value to the arguments of the add() function we are calling.

Another example – add arrays together:

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const array3 = [...array1, ...array2, 10];

This will create an array that looks like [1,2,3,4,5,6,10].

Similar Example with objects:

const obj1 = { name: "Jason" };
const obj2 = { location: "Melbourne" };
const obj3 = { ...obj1, ...obj2, "Learning": true };

We end up with an obj3 that l looks like:

const obj3 = { name: “Jason”, location: “Melbourne”, “Learning”: true };

And we can change obj1.name = “Bruce” and obj3.name remains as “Jason”.


Tagged Templates

  • Function that take a mix of string and variables, then formats and returns them based on some rules you apply.

 


Modules (“import” and “export”)

  • Code that can be written in one file and used in another (outside of the global scope).
  • Keywords “import” and “export”.
  • The name of the module is (by default) taken from the name of the .js file.
  • Each function we want to make available to other files is included in an “export”.
  • To use exported functions in other files we use the “import” keyword and reference the file to import from.
  • By default all exported functionality is imported, or we specify just the functions we want.
  • You can export a single default function (“export defailt …”) from a module and when importing you can give it any name you want.
  • NOTE: As of early 2020 modules is not handled well natively in Node (and I presume browsers) so you will need to use bundlers to get it working.

 

 


Other features to create examples for:

  • 22:34 Extended Literals
  • 24:42 Extended Object Literals
  • 28:18 Destructuring Assignment
  • Promises
  • async/await

 

 

 


Learning Resources

The responsibility of a software developer is to “deliver stakeholder value”

The responsibility of a software developer is to “deliver stakeholder value”.

 

Stakeholders are people and business.

We are tasked with creating things that provide positive value to those who commission it (the business) and use it (the customer).

Our responsibility and priorities are the following 3 tenents of software development:

Security: Ensuring the software we develop does not harm the business or customer, either directly or indirectly.

Usability: The customer can effectively discover, learn and usability the software in the easiest, most satisfying way possible. It should bring calm and cause a smile.

Sustainability: Ensuring once the software has been created it can be easily and effectively maintained into a long and unforseeable future. That includes ensuring it is cost effective, upgradable, extensible, buildable and deployable.

 

Software development is not about playing with technology.

It has nothing to do with language features, tools or frameworks.

Learning and change are not the reason for doing the work.

Cool should only apply when we find a way to improve on one of the tenents or delight a stakeholder.

Methodology, patterns, practices and paradigms are irrelevant if they don’t fit the tenents.

Explaining “The Cloud”

The “Cloud” is just computers that someone else owns and manage.

They own the hardware, make sure all the infrastructure (hardware and operating software) is kept up-to-date, and other people “rent” those systems to run their specific software applications.

All jokes aside, this explanation from Kitty is one of the best I’ve heard so far.

[videos] My first software training videos: Hoisting and Closures in JavaScript, and the MVC pattern

I recently needed to create 3 short software training videos for a software development training role I was applying for.

These are the first training videos I’ve ever created and published. I did my best to research the topics (even though I’ve worked with them for years) and try to present in the simplest way possible with examples. It’s not my finest work, but I am just getting started.

Hopefully someone finds them useful.

Any feedback is welcome at jason@jsnelders.com.

 

Hoisting in JavaScript

 

Closures in JavaScript

 

The MVC Software Pattern

Notesheet: Node Package Manager (npm)

Updated: 31 January 2020

 

The npm website is: https://www.npmjs.com/.

Note: As npm evolves some commands may change or become deprecated. We’ve already seen this with v5 (–save is now added by default during npm install) and v5 (npm audit seems to have replaced nsp check). Such is the ways of software development.

This chaetsheet was created with front-end web development in mind.

 

Initialising

  • npm init: Asks questions to create a package.json file.
  • npm init -y: Create package.json with all default answers accepted.
  • npm set: Set defaults for when you run npm init.
  • npm get: Check a default setting used when running npm init.
  • npm config delete: Remove a default setting used when running npm init.
  • Settings are stored in the ~/.npmrc file in the root of the user directory.

 

Installing packages

  • npm install {package_name}: Install a package in your projects. Installs to the “node_modules” sub-directory of your current directory. Installs the latest version.
  • npm install {package_name} –save: Save it to the dependencies section of package.json file.
  • npm install {package_name} –save-dev: Save it to the ‘dev’ dependencies list of package.json file.
  • Install packages globally so they can be used across projects.
  • npm install {package_name} -g: Install a package globally to a special folder on your computer.
  • npm install {package_name}@{version_number}: Install a specific version of a package locally.
  • In package.json:
    {
      "dependencies": { "underscore": "^1.8.3" }
    }

    The “^” means if a new version of the package is published, the newest version will be installed (auto upgraded).
    It also means we only want the latest version of the major release (the first digit, in this example the minor version is 1).

  • In package.json:
    {
      "dependencies": { "underscore": "~1.8.3" }
    }

    The “~” means we only want the latest version of the minor release (the second digit, in this example the minor version is 1.8).

  • In package.json:
    {
      "dependencies": { "underscore": "*" }
    }

    The “*” means just wan the latest version of the library (regardless of major or minor release).

  • In package.json:
    {
      "dependencies": { "underscore": "1.8.3" }
    }

    Just the number means we even install that exact version of the library (in this example, 1.8.3).

  • npm install {package_name}@{version_number} –save –save-exact: Install a version of a package, and tell package.json to use the exact version (don’t auto upgrade) via the –save-exact flag.
  • After package.json is setup, a new use just needs to use npm install to install all package dependencies.
  • npm install {url}: Install a package from a specified URL (e.g. GitHub or hosted server).
  • npm install gist:{github_gist_hash}: Install a package from a GitHub gist. You can use –save with it.
    • After, if you use npm list you may see it marked with “npm ERR!  extraneous: ….”. That means “the package is installed but is not listed in your project’s package.json”.
    • If you save it to packages.json then list it out you may see it as “invalid”. You can ignore that. It has to do with not being in the npm registry.
  • To install a private/closed source package from a folder: npm install {path_to_package_folder}. (e.g. “npm install ../my-package”).
  • npm list: List of packages you’ve installed locally, with their dependent packages.
    • list will return a complete dependency tree, with all sub-sub-sub-etc dependencies.
    • You can return just the first level of packages by using npm list –depth=0. To include the first sub-level of package dependencies,
    • npm list –depth=1.
  • npm list –global or npm list -g: List of packages you’ve installed globally, with their dependent packages.
    • You can use –depth=x after -g same as with local packages.

 

Updating Packages

  • npm outdated: Checks the npm registry to see if any of the installed packages are outdated (i.e. newer versions are available).
  • npm update: npm will get the latest compatible version of your dependencies and updates them
    (Question: is this only looking at package.json? What if there is no package.json – does it just look at the installed modules? According to https://www.hostingadvice.com/how-to/update-npm-packages/: “The npm update command allows you to update any out-of-date packages, according to your package.json versions”. So my takeaway is that npm update requires package.json).
  • npm update –dev and npm update –prod: Update just development dependencies or production dependencies, respectively.
  • npm update {package_name}: Update a single dependency/package.
  • npm update -g: Update all global dependencies.
  • npm update -g {package_name}: Update a single package in global dependencies.

 

Removing Packages

  • npm uninstall {package_name}: Uninstall a package locally. Does not remove from the “dependencies in your package.json file.
  • npm uninstall {package_name} –save: Uninstall a package locally and remove from the “dependencies in your package.json file.
  • npm uninstall {package_name} -g: Uninstall a package from the global repository.
  • Pruning: Removing packages that are not listed in your package.json file (e.g. if you run npm list and notice an “extraneous” error in the results).
  • npm prune: Goes through and compares installed local packages to the package.json file and removes anything that should not be there.
  • npm prune {package_name}: Prune a single package. Essentially the same as npm remove.
  • npm prune –production: Removes all dev dependencies, which will leave your package (?? no, project) ready to go to production.

 

Running Scripts

  • Scripts: Create scripts that can be run in the “scripts” section of package.json
    • 2 default scripts: “test” and “start”.
    • npm test: Run the “test” script.
    • npm start: By convention, the script you will run to launch the project.
    • Example section in package.json:
      {
        "scripts": {
          "test": "node test.js",
          "start": "node index.js",
        }
      }
    • For other supported script names see https://docs.npmjs.com/misc/scripts.
    • You can also use your own custom script names (e.g. “uglify”: “gulp compress” to use gulp to compress and uglify the code. So you would run “npm run uglify”).
    • npm run {script}: Run a custom script.
    • The scripts section is good guidance for other developers on tasks to run in the project.

 

Other Actions

  • npm repo {package_name}: Take you to the official source repository for the package.
  • To upgrade NPM itself: npm install@latest -g. Note: must be run on a command-prompt with administrator privileges.
  • npm audit: (since npm v6) Run a security check on your dependencies (packages) for security issues.

 

Resources/tutorials

Export all core WordPress data (posts, pages, attachments, comments, tags, categories and users) to a JSON formatted file.

I created a small WordPress plugin you can use to export all your core WordPress data to JSON formatted file.

Exported data includes:

  • Posts (status: publish, private, draft)
  • Pages (status: publish, private, draft)
  • Attachments (media)
  • Comments (approved)
  • Tag definitions
  • Category definitions
  • Users

The file is generated in /wp-content/export.json in your WordPress site (note: it will be available for anyone to access).

Simple create a new page in your site, add the shortcode and run the page to generate the file.
I suggest removing the page and deleting the export.json once you’re finished with it.
This is just intended as a quick and easy way of exporting your site data to a JSON file.

Note: It may degrade performance or result in a page timeout for large sites.

Complete plug-in source code at https://gist.github.com/jsnelders/fd22ebc26530468125ffed2d5d1eb279.

Feel free to adapt the script as needed.

XBox One sound stopped for headphones connected to controller

I was playing a game yesterday and everything was fine.
I paused the game, put the controller down, and left everything as it was.

Today I came back, plugged my simple headphones into the controller, and there was not sound.

I rebooted the box but still no sound.

It turns out my controller has a firmware update ready to install, although there was no indication of that, and after installing sound was back to normal.

You can check and update the controller via the Settings > Devices & Accessories menu (or similar). Find your controller and there will be a tile for updating it.

Code to convert exported Chrome bookmarks HTML to JSON

When you can’t find an existing solution to do something “simple” like convert an exported Google Chrome bookmarks HTML to JSON, it helps to be a programmer so you can build your own.

Check out my public GitHub code repository at: https://github.com/jsnelders/chrome-bookmarks-converter

I also have it running live at: https://chrome-bookmarks-converter.netlify.com/

It’s quick and dirty and only took a couple of hours but it work.

Software Development: Build, to Fail. Fail, to Learn. Learn, to Succeed.

The only way to learn as a software developer is to build.

Today I started my third major application using VueJS and realised there was a better way to approach something I’ve done in the last 2 applications.

As a mature developer you must continually question and re-evaluate what you know. Keep looking for better and easier ways achieve a result, and choose to discard those that don’t suit.

I’m not ashamed to say my last 2 approaches where inadequate. It took that time, different searches, and re-framing of the problem to eventually reach the point I needed.

But coming from a Microsoft development background I’ve had a career living the philosophy: “don’t implement until version 3” (which is to say, wait until version 3 before you get it right).

In all my years I’ve never seen a developer get it “right” the first time.

Maturity is recognising success takes time and working through the process.