Advanced JavaScript object control

Last time we talked about property descriptors and how we can use them to properly manipulate object properties to make them suit our needs as effectively as possible. In this post we are going to talk about some built in methods that can make our life with objects and their property descriptors much easier. Note that all the functions mentioned below operate on the object level. They apply to all properties and not just to one like property descriptors (link to article).

Let’s start with preventExtensions. This function will take your object and make its list of properties immutable. That means the function will disallow any further property additions to the object. If you try to add a property to that object afterwards the result will depend on the strictness of the code. In non-strict mode the property simply won’t be added, the program execution will continue as it otherwise normally do but the property won’t be added. So if you try to access it, you will get back the value ‘undefined’. In strict mode you get a TypeError. Check the following example that briefly demonstrates this useful functionality:

Note that preventExtensions does not protect the property’s against deletion. We successfully managed to delete the property ‘a’

The same example in strict mode:

If you try to execute this piece of code you will never get past line 13. The code will fail with this very descriptive error line: ‘Uncaught TypeError: Can’t add property d, object is not extensible’

preventExtensions is pretty useful when combined with strict mode because it gives you full control of your object’s lifetime. For example, say you have created a module that returns an object that for whatever reason you won’t to stay with its current properties. You can protect it with preventExtensions and any attempts to add unwanted properties will crash the script.

Next in line is seal. This function builds on top of preventExtensions to further protect your object’s properties. What seal does is it calls preventExtensions but also disables the configurability of every property. You can get the same result if you call preventExtension on your object and then modify the descriptor of every property and set configurable to false.

Check the following example, after the object is sealed we cannot add or remove any properties:

The last function for today is Object.freeze(). This function essentially calls Object.seal() on the object while also setting the writable status of every property to false. So that way you end up with a fully immutable object. See the example for more:

Of course if we try the same code in strict mode we will receive a TypeError when trying to add a new property.

That’s it for today. Three useful functions for full control of your objects. I hope you liked it and found it helpful. Check more JavaScript stuff here.

Function Expressions vs Function Declarations In JavaScript

Hello everyone! Today I’m going to talk to you about function expressions, function declarations what’s best to use, when to use and more importantly how to avoid unexpected behavior when using them. A lot of newcomers to JavaScript find this confusing but I’m here to convince you that it’s pretty simple:

This is a function declaration:

function foo(){
	console.log("I am foo");
}

This on the other hand is a function expression:

var foo = function(){
	console.log("I am foo");
}

In either case you execute foo in the same way:

foo();

The same thing applies if foo takes one ore more parameters:

function foo(param1, param2){
	….
}

var foo = function(param1, param2){
	….
}

Then you can call it like this:

foo("bar", 3.14);

So I can use whatever I like best and there is no real difference between the two besides the syntax used during the function definition?
The answer is No

Consider the two following examples:

Example 1:

foo();

function foo(){
	console.log("I am foo");
}

Output: “I am foo”

Example 2:

foo();

var foo = function(){
	console.log("I am foo");
}

Output: Uncaught TypeError: foo is not a function

Why is this happening? The reason has to do with hoisting. When you use a function declaration you can imagine that during the first pass of the compiler the function and variable declarations will be moved to the top of the enclosing function (that’s not exactly what really happens but it’s very convenient to imagine it like that). When you use a function expression, only the variable declaration will be “moved” to the top of the enclosing function. You can visualize the result of hoisting in both examples like this:

Example 1 (after hoisting):

function foo(){
	console.log("I am foo");
}

foo();

Example 2 (after hoisting):

var foo;

foo();

foo = function (){
	console.log("I am foo);
}

As you can see in the second example when the engine executes the statement ‘foo();’ it does not possess sufficient knowledge about foo. At that time it only knows that foo is a variable, the actual assignment takes place later in the code.

This is actually the most important thing between function declarations and function expressions

Hoisting

Ok so this is going to be a short one. I recently stumbled upon a question in StackOverflow (actually include a link here) that was asking something like this:

Why is this code valid?

//Start of this file
myFavoriteMovie = "Star Wars"
console.log(myFavoriteMovie);   //Actually prints 'Star Wars' even though `myFavoriteMovie` is undeclared
.
.
.
// A few more lines of irrelevant code
.
.
.
var myFavoriteMovie = "Inception";   //myFavoiteMovie declared
console.log(myFavoriteMovie);

So what do you think would be the output of this script?
Most people would say that an error will be shown claiming that `myFavoriteMovie` is undefined or that `undefined` will be printed in the console. The strange thing is, that the same people that find this code wrong, will find the following code fine:

var game = new VideoGame("Mass Effect", "Bioware", "Action RPG");
console.log(game);

function VideoGame(title, developer, genre){
	this.title = title;
    this.developer = developer;
    this.genre = genre;
}

Those two examples are essentially the same thing. In the first example, `myFavoriteMovie` is used before declaration. In the second example, the same thing happens with the VideoGame function. It’s used before declaration but few people notice the similarity. I too, could not see it and I was surprised when I found out. I think the source of confusion for most of us is that using a variable before declaration is counterintuitive, it’s something that we normally do not do and if we do it’s probably by mistake. However, defining a function or a class at the end of a file and using it before declaring it is rather common because it helps some developers (including me) with code organization. But using a variable before declaring seems off to the most of us. Perhaps that’s because most of us started coding in a more strict language than JavaScript, C for example where it is unthinkable to use a variable before declaring it.

Anyway, there is a name for this and that’s Hoisting. It’s something that happens every time you run your JavaScript script (or just JavaScript 😛 ). Hoisting is the process of moving all variable, function and class declarations found in the file, at the start of that file. So right before execution the code of the first example gets transformed and ends up looking like this :

var myFavoriteMovie = "Inception";
myFavoriteMovie = "Star Wars";
Console.log(myFavoriteMovie);
.
.
.
// A few more lines of irrelevant code
.
.
.
myFavoriteMovie = "Inception";
console.log(myFavoriteMovie);

That is why you can use variables, functions, classes and objects before you actually declare them.

Hope you find this explanation of JavaScript Hoisting helpful. Check more awesome JavaScript stuff here

Custom HTML Elements

Hi, everyone! We’re back to Aurelia and this time I’m going to show you how to build your own custom element just with HTML, without a view-model. Yes, that’s possible!

There are many advantages to an HTML-only element, like, first and foremost, not having to use a view-model at all! This is particularly useful when your custom element does not implement complex business logic but you just need a quick component for your applications.

Now, HTML-only custom elements bring us some good and some bad news.

The good news is that you can still add bindable custom attributes to your elements by adding them to the bindable attribute of the template element in a comma separated fashion:

//my-element.html
<template bindable="attributeOne, attributeTwo, attributeThree ">
….
</template>

 

You can then use it like that: 

<require from="./my-element.html"></require> 
<my-element attribute-one="someVar1" attribute-two="someVar2"></my-element> 

 
Yes, Aurelia does the conversion from camelCase to dash-case on its own all the time. That comes in handy.  
One thing you might have noticed in the example above is that, in order to use an HTML-only element, you also need to include the “.html” extension in your path. That happens mainly due to the absence of a view model. 
 
The bad news is that HTML-only custom elements do not support two-way binding by default. That means that, if you want two-way binding functionality, you need to explicitly state it. I will demonstrate this with a simple example as it can be very confusing to newcomers: 

The HTML-only element:

And how we can use it:

Working with aurelia-dialog

The Aurelia Dialog is a very useful Aurelia plugin for creating and showing popup dialogs in your Aurelia applications. The official repository can be found here:

aurelia-dialog does not come with the standard Aurelia installation so you need to take some steps before you can use it.

Follow these simple steps to install and start using Aurelia Dialog:

Run


jspm install aurelia-dialog

Go to your Aurelia configuration file (In my demos it’s main.ts) and add the plugin to the Aurelia configuration object as shown below:

The Aurelia Dialog module exports two classes, the DialogController and the DialogService. We can use the first one to create our own custom dialogs and the latter to trigger those dialogs.

In this tutorial, I am going to use the UserInfo class I introduced in my earlier tutorial about sharing state (link here) and display the user’s personal information on a custom dialog that’s triggered when a button is clicked. The dialog will ask the user if the information displayed on it is valid and provide the user with two “Yes” or “No” buttons for answering. The user’s answer will then be logged to the console. It’s a simple example but enough to get you started with creating and managing Aurelia dialogs.

Let’s start by creating a new folder within our src directory named ‘dialog-demo’. We’re going to need to add four files to this folder.
• info-dialog.ts: The view model for our custom ‘Personal Information’ dialog

• info-dialog.html: Where we will design our custom dialog

• dialog-demo.ts: The view-model for the page that will host our shiny new popup dialog

• dialog-demo.html: Will  just contain a button that will trigger the popup

 

Finally we make the required additions to the configureRouter method of the App class in app.ts to add our new demo page to the router navigation.

{ route: 'dialog-demo', name: 'dialog-demo', moduleId: './dialog-demo/dialog-demo', nav: true, title: 'Dialog Demo' }

Note: At the time of this writing there is still a bug in Aurelia Dialog’s code that prevents the popup dialog from closing when the user clicks outside the box.

You can view the whole repository here for more Aurelia demos

Level-order traversal of a Binary Tree

Level order traversal is different from other more common types of tree traversal algorithms such as in-order, pre-order or post-order. Level order traversal visits the nodes level by level. Once it’s done with the root (level 0) it moves to level 1, then to level 2, e.t.c. Perhaps the two most major differences between level-order traversal and the other 3 algorithms are that:

  1. It is an iterative algorithm
  2. It makes use of an extra data structure, a FIFO queue.

The reason why we need to use a queue is because we have no easy way of travelling backwards in a tree.

For example, in the following tree, if we are at the node with value 2, it may be easy to go to node number 5, but what about node 8?

binarytree
(Node-2 and Node-8 belong to different subtrees, accessing one from the other requires going backwards)

The only node that connects these two nodes (formally called the Lowest Common Ancestor) is node number 6, the root of the tree. Now imagine a very deep tree with countless of leaves and the problem gets downright impossible.

That’s where the queue comes into play. The algorithm is pretty simple.

  1. Push the root into the queue
  2. While the queue is not empty
    1. Pop a node from the queue (Remember a queue works in a First-In First-Out way)
    2. Do something with its data
    3. Push its children into the queue
  3. By the time the queue is empty, the algorithm will have visited all nodes

Let’s apply level-order traversal to the above tree to visit and print all of its nodes. We start with a queue that only contains the root of the tree.

Queue: node-6
Output:

First loop (Level 0)

We begin by taking the first element out of the queue, which of course is the root of the tree. We print its value to the output and push its children into the queue

Queue: node-6, ode-4
Output: 6

Second loop (Level 1)

We take node-9 out of the queue, print its value and push its two children into the queue

Queue: node-4, node-2, node-5
Output: 6, 9

Third loop (Level 1)

We take node-4 out of the queue, print its value and push its right child into the queue

Queue: node-2, node-5, node-8
Output: 6, 9, 4

Fourth loop (Level 2)

We take node-2 out of the queue. Node-2 does not have any children so nothing gets pushed to the queue. We just print “2”.

Queue: node-5, node-8
Output: 6, 9, 4, 2

Fifth loop (Level 2)

We take node-5 out of the queue. Node-5 has no children nodes so we just print its value and move on

Queue: node-8
Output: 6, 9, 4, 2, 5

Sixth loop (Level 2)

We take node-8 out of the queue. Node-8 has no children nodes, so we print “8” and then notice that the queue is empty. So the sixth loop is the final one and we’ve managed to print all elements of the tree in a level-order from left to right.

Queue:
Output: 6, 9, 4, 2, 5, 8

Now to the C++ implementation of the algorithm:

Each node is described by the following struct:

And here’s the levelOrderTraversal function

The C++ Standard Library provides a FIFO queue out of the box accessible to you by including the header. However you can still use a custom implementation of it if you like .

Post-order Traversal of a Binary Tree in C++

If you know about pre-order traversal you know that it visits the root first and the subtrees later. If you know about in-order traversal you know that it visits the nodes in-order (duh), first the left subtree , then the root and finally the right subtree. The remaining combination is to operate on the root when you’re done with the subtrees. That’s what post-order traversal does.

Let’s see an example of printing all the nodes of a tree using post-order traversal:

binarytree

Starting from the root the post-order traversal algorithm will visit the left subtree, the right subtree and then return to the root node when it’s done.

Output so far:

We visit the left subtree on node-9 and move on its own subtrees until we find the tree’s leaves.

Output so far:

When we reach node-2 there are no left and right subtrees so we print it

Output so far: 2

Same way with node-5

Output so far: 2, 5

We return to node-9 and since we’re done with its subtrees we print the value 9

Output so far: 2, 5, 9

Back to node-6. We haven’t yet visited its right subtree so on we go

Output so far: 2, 5, 9

Node-4 has no left subtree, so we visit its right-hand one.

Output so far: 2, 5, 9

We visit node-8’s left and right subtrees which are empty and then return to node-8 and print its value

Output so far: 2, 5, 9, 8

Now that we’re done with node-4’s subtrees we print its value

Output so far: 2, 5, 9, 8, 4

We’re done with both subtrees of our tree’s root, node-6. It’s time to print its value too.

Output so far: 2, 5, 9, 8, 4, 6

And that’s it. We’ve traversed the tree In a post-order fashion and have printed its nodes.

The algorithm that achieves that in C++ is the following:

In-order Traversal of a Binary Tree in C++

In-order traversal is probably the most widely used type of tree traversal algorithm mainly because when applied to Binary Search Trees it can operate on the nodes in order (duh!). The in-order traversal algorithm first operates on the left subtree, returns on the root operates on it and then traverses the right subtree.

To demonstrate the algorithm we’re going to print the integer values of a binary tree whose nodes are described by the following struct:

An unconventional and not very scientific way to think about the algorithm is that it visits nodes in this order:

  1. Left
  2. Middle
  3. Right

It helps if you’re trying to visualize it. Speaking of visualization let’s see an example of the algorithm in action. We have the following binary tree:

binarytree

Starting from root-node 6, the algorithm will check if the node is NULL and since it is not, it will visit its left subtree first, then it will return print 6 and visit the right subtree.

Output so far:

We are at node 9, the start of node-6 left subtree. The node is not NULL so the algorithm goes deeper to the next left subtree

Output so far:

Node 2, also not null. The algorithm goes to the left again

Output so far:

We’ve bumped into NULL, the function returns control to the caller. So we’re back at node 2. We print it

Output so far: 2

Now it’s time for the right subtree. We visit it, find out it’s NULL and then return to node-2. Node-2 is done so back to node-9

Output so far: 2

We’re done with node-9’s left sub tree so we print 9 and head over to its right subtree

Output so far: 2, 9

We’re at node-5, it’s not NULL so we go to its left subtree which is NULL so we return to node-5, print 5 and move to the right subtree which is also non-existent so we go back to node-9

Output so far: 2, 9, 5

We’ve printed node-9’s left subtree, its own value and its right subtree so we’re done and return to node-6. We print 6 and move to the right subtree

Output so far: 2, 9, 5, 6

We are at node-4 which is not NULL so we visit its left sub-tree

Output so far: 2, 9, 5, 6

Node-4’s left subtree does not exist so we return to node-4 and print its value

Output so far: 2, 9, 5, 6, 4

Next, we visit node-4’s right subtree at node-8

Output so far: 2, 9, 5, 6, 4

Node-8 is not NULL so we visit its left subtree. Node-8’s left subtree is NULL so we return to node-8 print its value and visit its right subtree

Output so far: 2, 9, 5, 6, 4, 8

Nothing here so back to node-8. But we’re done with node-8 so back to node-4. Node-4 is also finished, so back to the root. The root is also finished so we’re done.

Final Output: 2, 9, 5, 6, 4, 8

Here’s the code of in-order traversal in C++ :

Pre-order Traversal of a binary-tree in C++

The pre-order traversal algorithm is a traversal algorithm that visits the root node of the tree first, and then recursively visits the left and right subtrees for binary trees, or every other subtree for non-binary ones. In this blog post we’re going to see how the recursive pre-order traversal works. An iterative method is also possible with the use of a stack but I find the recursive method more intuitive, plus if you’re not yet familiar with recursive functions, then recursive tree traversal algorithms is a very nice place to start. To demonstrate the algorithm we are going to print the values of a tree in a pre-order fashion.

Every node in our Binary Tree representation is described by the following struct:

We will be using integers for this example but of course a binary tree may contain whatever data type is needed. You can replace int data with char data or double data, or, even better, use Abstract Data Types and C++ templates. The left and right pointers point to the left and right subtree respectively.

The first thing the algorithm does is to check if the node passed to it is actually a valid node. If it isn’t, the algorithm stops and does nothing more. I know this may sound obvious but it’s vital to understanding the algorithm as you’ll see later in this post.
If the node is an existent one (not NULL) the value of the node gets printed and then the algorithm visits the left subtree followed by the right subtree. Notice that I’m not saying left node but left subtree, so after the root node gets printed the algorithm will visit the left subtree recursively and only after the left subtree has been dealt with, will the algorithm move on to the right subtree. And this is applied recursively to the subtrees of the subtrees and so on.

Ok, enough with theory. Recursive algorithms and especially tree traversal ones are best explained with the use of an example.
Let’s say we want to traverse the following tree:

binarytree

 

Starting at the node we print the value 6 and then do a pre-order traversal of the left subtree. Only after we’re done with the left subtree will we move to traverse the right one.

Output up until now: 6

The algorithm visits the node with value 9, it’s not null so it prints the value to the output and then traverses the left subtree (the one starting with the value 2)

Output up until now: 6, 9

We’ve reached the node with value 2, the node is not a NULL one so we print the value and move to traverse the left subtree

Output up until now: 6, 9, 2

The left subtree of node 2 is non-existent!. We’ve passed NULL to our algorithm so it will stop. There is nothing more in the left subtree so the algorithm will now visit the right subtree. What subtree? The one on the right of node 2. But that’s non-existent too. So the algorithm is done with the subtree starting at node 2 so it goes back to node 9. The traversal of this node’s left subtree is over so the algorithm will visit its right subtree, namely node 5

Output up until now: 6, 9, 2, 5

Node 5 does not have any child nodes so we’re back at node 6, the root of the tree. Now it’s time to explore the right subtree. The algorithm goes to node 4, prints it and moves to its left subtree

Output up until now: 6, 9, 2, 5, 4

Node 5 does not have a left sub tree, nothing to do here, back to 4. Time to search the right subtree. The root of the right subtree is 8, the algorithm prints it

Output up until now: 6, 9, 2, 5, 4, 8

No left, or right subtree for node 8, back to node 4. We’ve visited both subtrees of node 4, so back to node 6. Same thing here, so we’re done. We’ve traversed the whole tree.

Now let’s see how this translates into code:

As we’ve seen earlier in this post, the algorithm stops if the given root is NULL. If the node is not NULL the algorithm immediately prints the data and then moves on to do the same for the left and right subtree. That’s it! It’s actually simple.

A variation of the algorithm that actually results into a smaller call stack size, checks the left and right subtrees before traversing:

The check for NULL takes place in both algorithms so the second one is a very minor optimization because of the fewer function calls. However the first algorithm seems cleaner and easier for beginners to grasp.