New eBook Release Annoucement

JavaScript in Plain Language -A Self-Study Method
A JSON and AngularJS Prep

Is now available on Amazon.

Thank you for your amazing feedback!

Please click on the image to read more about it.


Code separation and encapsulation

In order to avoid conflicts of interests it is always a good idea to keep variable names unique.

Avoiding name duplication is easy to do in a simple demo script but in real life it is not so easy. Actually it is virtually impossible because code comes from different sources, the ones we write ourselves and the ones provided by applications we link to.

What we can do to prevent such conflict of interest is to isolate our own code into a closed circuit. This type of implementation if called encapsulation.

There are many ways of applying encapsulation. One such way is to include our code inside of a function. Another way is to write it as an object.

  • A function has its own scope which protects its declared assets from being mistaken by global items with the same name.
  • As for items inside of objects, they require proper addressing whenever we want to use them. That in itself prevents us from calling the wrong global item by mistake.

I show a few simple encapsulation examples on my latest post at jsplain.com.


Styling JavaScript Console.log

Did you know we can style the output from a console.log on a modern JavaScript Console?
It may not be something to do all the time but for that particular occasion where it will make a difference here it is the recipe:

console.log("%cHello World!", "color: red; font-family: Verdana");

It outputs Hello World!

What about a multicolor output?

console.log("%cHello %cWorld!", "color: red; font-family: Verdana","color: blue; font-style: italic");

It outputs Hello World!

The secrete is in the %c which serves as a placeholder for the style that follows as the second or third arguments.


Can we run JavaScript tests on the Windows command prompt?

Yes we can ( once we install Node.js on our machine).
Node.js was first published by Ryan Dahl in 2009 and could only run on Linux.In June 2011, Microsoft partnered with Joyent to help create a native Windows version of Node.js.
Node.js is a cross-platform runtime environment for server-side and networking applications. Once installed on Windows we can do lots of things with it, one of such benefits is to run JavaScript on the command prompt.

Installation only takes minutes. Please see my other article on how to go about it, from installation to testing JavaScript on the command line:
jsplain.com/javascript/index.php/Thread/26-Running-JavaScript-tests-on-Windows-command-prompt/

Happy first of September, everyone!


forEach, a way to manipulate arrays

The array method forEach( ) was introduced with ECMAScript 5 when nine new methods were added to help developers create ways of searching and manipulating array contents. These methods perform operations that previously would require complex iterative loops. The nine additional methods are: indexOf, lastIndexOf, every, some, forEach, map, filter, reduce, reduceRight. All these methods are variations of the forEach() method which I’m about to discuss.

forEach( ) performs a specified action for each element on the array. The specification of what to do is written by the programmer as a function in the form of an argument to the forEach() mechanism.

Remember, the purpose of a function is to store some code that will run when the function is called. We create the function, and forEach() will process it.

So, forEach( ) takes a function as its argument. The parameters of the function itself will interface with each valid element of the array in an iterative manner, just like a loop would do. By valid element I mean an element with data ( not an empty element location). Array indexes not having a value, or the value being undefined (if any), are ignored.
1- Let’s experiment with this method in increments. Start by introducing on the console a new array (I’m using Chrome):

var g = ["red", "blue", "white"];

2- Call forEach( ) on the array g by using a function with just one parameter, “y” , and in the function we stored a simple console.log output:

g.forEach(function(y) {
console.log(y);
});

The function being used here may contain up to 3 arguments. The first argument (as the example above), points to the array data. In the forEach( ) example given above, the parameter y will point to the value of each index on the array, and the method forEach will process each value according to the instructions on the body. In this case the next instructions are to console.log each value at each “y” iteration and the result is: red blue white (in separate lines).

For a more detailed explanation as well as an explanation of all the other 8 methods please refer to my eBook:


JavaScript’s Conditional Operator

The conditional operator is a one liner if/else statement. Another name for it is ternary operator because it uses three operands:

expression1 ? expression2 : expression3;

If expression1 evaluates to boolean true, expression2 gets executed. Else, expression3 gets executed instead.

If you’re like me, you probably prefer to use if, else if, else statements, but the ternary operator can be very handy at times. One of the things we can’t do with our regular branching techniques is to include alternative outputs on a one console.log statement, but with the ternary operator we can:

var x = 10;
var y = 9;
console.log(x < y ? "hello!" : "goodbye!");
// it outputs "goodbye!"
console.log(x > y ? "hello!" : "goodbye!");
// it outputs "hello!"

Cool thing!


White space in JavaScript

JavaScript does not care for white space. It just ignores it. However there is one exception to the rule: when the white space is in between quotes such as a string literal. Example:

var text = "the quick
brown fox
jumps over
the lazy dog";

If you test the above script on the Chrome’s Console (CTRL SHIFT j), JavaScript will throw an error: SyntaxError: Unexpected token ILLEGAL. We need to use the backslash \ as an escape character. An escape character is one which invokes an alternative interpretation on subsequent characters in a character sequence. In this case, the backslash will tell JavaScript to ignore the subsequent line break and just make it a continuous string:

var text = "the quick \
brown fox \
jumps over \
the lazy dog";

Notice how I included the space before the backslash and not after it. We only want to escape the line return. Now, when we call variable text it outputs the the correct sentence: “the quick brown fox jumps over the lazy dog


Follow

Get every new post delivered to your Inbox.

Join 85 other followers