Gadgets Guide, Technology & Electronics, Softwares & Reviews

Things You Probably Didn’t Know About JavaScript

0

JavaScript is necessary for any web developer. The days have gone where you could go without a little CSS and HTML. Fortunately, there are so few rules. Therefore, it is straightforward to start:

alert(“Hello World.”); // Shows the user “Hello World.” in a dialog.

There you go! Many simple tasks can be performed with just a few lines of code. There is no need to import packages or declare namespaces. You write the code, and it starts.

However, the very absence of a structure that gives JavaScript a low barrier to entry also allows novice developers with basic knowledge on coding and on JavaScript Security to write unstructured, fragile code without realizing it.

As the application grows, this unstructured code will come back to haunt you in the form of unexpected, hard-to-detect errors.

In this article, I plan to correct some common misconceptions and look at things you probably didn’t know about JavaScript.

The WebAPI

JavaScript is not the same buggy language as ten years ago. One proof of this is the stunning WebAPI. It offers a rich feature set, from DOM manipulation to notifications to battery management and WebSockets.

It also includes camera functionality, SMS, telephony, Bluetooth, and much more. WebAPI keeps you safe.

jQuery Is Obsolete In Many Cases

Many sites still download the entire jQuery library. For basic DOM manipulation, network communication, or fancy animation, you may think you need jQuery.

That was seven years ago, but not today. Now there is built-in JavaScript support for all these things. You might be surprised if you think that jQuery is the only way to manipulate DOM easily.

Animation can (and should) be done with CSS. ES2015 introduces Promises/A+ API, which makes network communication much more convenient.

One more thing: native JavaScript is much more productive. However, please don’t only take my word for it, take a look at this comparison before judging.

Object-Oriented

A lot of people have tried to hack classes on JavaScript. They created complex frameworks that simulate class behavior. However, JavaScript has never been class-centric. While this may sound bad, it doesn’t mean it’s not object-oriented. Kyle Simpson points this out in his series.

JavaScript is almost unique among languages, and perhaps the only language that has the “object-oriented” label, because it’s one of a concise list of languages where an object can be created directly, without class at all.

JavaScript is probably not class-oriented, but prototype-oriented. Even with ES2015 class syntax, we still deal with objects and prototypes under the hood.

Kyle introduced a prototype-oriented template called OLOO, which you might want to check out.

WASM

WebAssembly (WASM) adds a new language to the browser for a super-performance code. It is also compiled for other languages such as C and C++ (today, we mostly use asm.js).

It is a very complicated topic, so you should read about it somewhere else.

A short story: other languages can be compiled to work in a browser. JavaScript can also communicate with this layer.

Web Components

You’ve probably already heard of web components and shadow DOM, so let’s say HTML and JavaScript will become much more modular and reusable.

This conversation by Jarrod Overson may be a little outdated, but it will open your eyes if you have no idea what impact web components have and will have.

It won’t take long, and even jQuery plugins will be outdated. We will just download a web component that will work correctly with native JavaScript.

NaN Is Not Equal To NaN

JavaScript has quite a few predefined values, such as ‘NaN’ (not a number), undefined, zero, etc.

For many of them, the == operator returns true if the item in the left and right parts is the same.

Like (undefined==undefined) returns true; the same way (null == null).

But in the case of NaN, everything is different. (NaN==NaN) returns false.

Bitwise Operators Are Slow

In most cases, Bitwise operations in the language are performed faster than normal operations.

However, in the case of JavaScript, Bitwise operators transform an operand into a 32-bit signed integer and return it to the 64-bit floating-point. It makes the operation slower.

Global And Window Are Confusing

All JavaScript programs have a global object that contains all variables, functions, and other contexts.

Even the browser’s ‘window’ variable is also a ‘global’ property that points to ‘global’. It means that ‘window’ is actually ‘global.window’, while global.window = global. It’s a bit confusing.

Suppose you have an object named myObject at the global level of your program. So if you write ‘myObject’ directly, it will give you the value’ myObject’.

However, if you write ‘window.myObject’, firstly it will go to ‘global.window’, which is ‘global’, and then find ‘myObject’. It means that it will execute an additional loop.

Boolean Is Wired

var a=new Boolean() returns a true value, but its value is false. Again, it’s confusing, but this is how Boolean works.

Let’s run an example.

var a=new Boolean();

console.log(a.toString());

if(a){

console.log(‘a is truthy’);

}

You will see that the first console.log prints false, but if(a) is correct.

Actually, ‘a’ here is the object. So when we write if(a), if we execute it as if(object), we return true. However, the Boolean’s default value is false.

The Behavior Of Object And Property

var obj1={a:1,b:2};

var obj2=obj1;

obj1.a=10;

console.log(obj2.a);

//It will print 10.

obj1=null;

console.log(obj2.a)

//will still print 10

Because obj2 did not point to obj1, the point is that both obj1 and obj2 pointed to the same memory area. obj1=null, just made obj1 a pointer to another memory area.

Fun With ‘Hoisting’

JavaScript is hoisting and here is another silly thing. For example, let’s write a piece of code in 2 different ways.

var a=1;

function myFunc(){

console.log(a);

console.log(a);

}

myFunc();

//Output is:

1

1

 

var a=1;

function myFunc(){

console.log(a);

var a=2;

console.log(a);

}

myFunc();

//Output is:

undefined

2

 

In the second case it is a printout of the undefined first, because the JavaScript interpreter pushes the declaration at the start of the function. Thus, after interpretation, the code actually becomes:

function myFunc(){

var a; // a is redeclared, but no value is assigned

console.log(a); // therefore it evaluates to undefined

a = 2; // now a = 2

console.log(a); // and then it logs to 2

}

myFunc();

It’s Time For A Hangout

Do you remember the vision of 80s video communication in Facetime style?

It took 20 years before it became widespread, thanks to the almost ubiquitous broadband Internet and the intensive use of a small software called Skype.

With the power of Adobe Flash and Google’s attempt to build a social network, we already have video communication capabilities in our browser. It would be great to have these features without using third-party plugins like Flash.

Fortunately, browser manufacturers have also thought about implementing the “getUserMedia” API in their software. It was the first step to access devices such as cameras or microphones directly from your browser.

Using Node.js as a server at the back of such an application makes it surprisingly easy to air the video signal to clients. Fortunately, at the time of writing, only Chrome and Opera support the API, but others will quickly catch up.

A cleaner approach to two-way communication is the only thing Chrome currently has called WebRTC.

With WebRTC, clients can open peer to peer communication channels, directly connecting to the client.

To have some fun, check out Sindre Sorhus and Photo Booth implementation done in 121 bytes!

var video = document.getElementsByTagName(‘video’)[0],

navigator.getUserMedia(‘video’, successCallback, errorCallback);

function successCallback(stream) {

video.src = stream;

}

function errorCallback(error) {

console.log(error);

} $(‘light’).fadeIn();

The Arduino microcontroller platform is a class A for an example of using JavaScript “out of the box”. It is an open-source electronics prototyping platform based on easy-to-use, flexible hardware and software for people who are not too familiar with the Arduino platform.

It is designed for artists, designers, amateurs, and anyone interested in creating interactive objects or environments.

Arduino only supports code written in C, which is still not anything special. With a few lines of C (except that others have done the work for you), Arduino can receive commands via its USB port using a serial port protocol.

But how do you access the serial port via JavaScript? Obviously, not from a browser.

Node.js to the rescue!

Thanks to the efforts of public defender Chris Williams, we have a library of serial ports Node, where we can send data via the old SP protocol.

It was the first breakthrough based on the library, and other people have developed a more abstract approach to Arduino’s capabilities. For example, the node-Arduino and duino libraries.

The hottest library around the JS-controlled Arduino programming block at the moment is Johnny-five. Check out Bocoup’s blog for some hot stuff they did with the Arduino platform and many plugins.

The JSConf video from Jörn Zaefferer and Nicolai Onken can also give you a twist in what is possible today with a little bit of code.

Your Hands Are Made For The Browser

The Report’s future vision of minorities (where they control computers with their own hands rather than machines) is getting closer every day.

A huge step in this direction is the Microsoft controller, not trying to play, Kinect. Amazing gameplay, you might think, but what does it have to do with JavaScript?

With the release of the Microsoft’s Kinect SDK, a group of people crossed the browser bridge used for Kinect. First of all, these are the guys from ChildNodes who have created a complete working kinect.js library that allows you to use Microsoft’s Kinect in your browser.

It is recommended that you read their demos and videos. One of the main drawbacks of the kinect.js library is that there needs to be a WebSocket server program running at the back of the client (this is Kinect -> C# -> JS glue).

Several MIT fame students are working on a demolition solution for this wall called DepthJS. This browser plugin allows you to use Kinect for Chrome and Safari, even for sites not optimized for use in Kinect. DepthJS is currently at an early stage of development, but it is definitely worth watching.

3D Games Controlled With Your Gamepad

Have you ever tried playing a Non-Flash browser game? Graphic possibilities are amazing, especially when you see game clones like Quake.

However, during the game, you’re always tied to the keyboard and often the clumsy mouse. It is a major drawback, especially in action games. It keeps them away from the browser.

Wouldn’t it be cool if you plug the Xbox controller into your computer and start playing your favorite browser game? That’s not the future anymore, say hello to the Gamepad API!

If you have a gamepad on your desk, plug it in now and enjoy some games that already use the Gamepad API.

Programming the input controls is also a piece of cake, take a look at this piece of code or, better yet, run it yourself:

<div id=”gamepads”></div>

<script>

function gamepadConnected(event) {

var gamepads = document.getElementById(“gamepads”),

gamepadId = event.gamepad.id;

gamepads.innerHTML += ” Gamepad Connected (id=” + gamepadId + “)”;

}

window.addEventListener(“MozGamepadConnected”, gamepadConnected, false);

</script>

If you desire to learn more about the 3D capabilities of browsers, pay attention to the open-source 3D simulator engine Ascent by Three.js and Jens Arps based on it.

Running Flash On Your iPad

Thankfully, Apple did not put Flash on the iPod and iPad, it’s the beginning of a movement to implement open technologies such as HTML5, CSS3, and JavaScript.

Most customers have to pay twice for a simple advertisement or campaign that they launch to have interactive content launched in the old IE7 or IE8 via Flash and modern browsers, and in iDevices via HTML5.

Polyfling in older browsers has its limits, mainly called performance. So is it possible to run Flash on these Flashless iDevices? Of course it is, as it is built into JavaScript.

In 2010, Tobias Schneider released a small library called “Gordon”. It allowed SWF files to run directly in the browser. It worked well for small Flash files, such as advertising, which used functionality only before Flash version 2. However, higher-level functionality was not included.

When Tobias joined UXEBU’s ueberJS, they had a new idea. It is how Bikeshed began. It is a kind of JavaScript animation framework.

Still, it’s also JavaScript to Flash for everything you want it to be a compiler. It is adapter based. Therefore, you can write adapters for everything you want, although the standard behavior is to compile Flash into JavaScript.

It is compatible with ActionScript 3 and Flash 10. Check out its web page to learn more about many other features besides the compiler.

Writing Apps For A Smartphone

Writing native applications for mobile phone environments can be challenging. It starts with deciding which platform you want to support or if your application runs on iPhone and iPad, Android mobile device, Windows Mobile, Blackberry devices, webOS platform, and so on.

Each of these platforms has its API and mainly uses different programming languages.

If you have survived browser wars, let me say that this is a more difficult struggle. It’s almost impossible for a developer to build an application for all these platforms on time and on a low budget.

So, what should we do? Hire more developers? Pay more for applications? Or find an even better approach to make sure that your codebase works on every device? Most people would probably prefer the latter approach.

However, what should these applications be? What is common about all these platforms? You probably know the answer, it’s a web browser and, therefore, a JavaScript engine.

Cordova

It is the idea of Apache Cordova, better known as PhoneGap. Cordova is a JavaScript framework that abstracts the API of each mobile environment and reveals a neat JavaScript API to control them all.

It enables you to maintain a single code base, which you then build and deploy on different mobile devices.

Check out the resources here to learn how to use Cordova to build mobile applications that you create once and will work everywhere.

Running Python And Ruby In Your Browser.

Mozilla is the company behind the famous Firefox browser. It hires a lot of crazies, that’s for sure. One of them is Alon Zakai, an engineer with Mozilla’s research team who created a fancy tool called Emscripten.

Emscripten allows us to take LLVM bit code, which can be generated from C/C++ libraries into JavaScript. It achieves this by compiling the libraries into bit code, and then taking that bit code and converting it into JavaScript.

Have you ever heard about the phrase “Using CoffeeScript and Prototype is the closest thing to running Ruby in your browser?” Don’t worry if you haven’t, because it is not true anymore.

With Emscripten you can just take Ruby’s sources, convert them to JavaScript and voila, run the real Ruby in your browser! However, this does not only apply to Ruby; for example, Python was also Emscripted.

You can also check the h.264 Broadway decoder in your browser. It is an emscripten C++ library!

Go to repl.it to see several programming languages (including Ruby and Python) running in your browser!

Writing OS Independent Desktop Programs.

We used to talk about targeting several mobile platforms using Apache Cordova. No wonder that JavaScript can be used not only for targeting mobile platforms, but also to fight against our old friend – the desktop computer.

The first solutions came from the guys from Appcelerator with Titanium Desktop Suite and Adobe, the widely used platform Air.

However, like most open-source enthusiasts, you are probably looking for a more open and Node.js-based technology.

Meet app.js! app.js, It is an open web technology and desktop builder based on Node.js. It allows you to write real desktop programs with file system access, window control, and more.

You can rely on stable cross-platform Node APIs and create our software UI with HTML and CSS.

app.js is quite a young project and, therefore, only supports Windows and Linux now. However, according to the mailing list, Mac support is on the way.

Running A Web Server

At present, you don’t shock anyone when you tell them that a JavaScript-based web server serves your site. If you went back two or three years ago and told web developers the same thing, they would probably laugh at you or worse.

However, with incredible success, Node.js is, fortunately, still far away. It does not surprise people anymore, because of its asynchronous nature node.js is a performance wunderkind, especially when it comes to solving the problem of multiple parallel connections.

Not only is its performance an explosion, but a straightforward API attracts many developers.

Let’s see the example of “Hello World” from the world of nodes, it’s not just a screen printout of “Hello World”, it’s an http webserver!

var http = require(‘http’);

http.createServer(function (req, res) {

res.writeHead(200, {‘Content-Type’: ‘text/plain’});

res.end(‘Hello World\n’);

}).listen(1337, ‘127.0.0.1’);

If you’re not struck by this simplicity, I can’t help you either. One of the best parts of node’s popularity (or hype) is that big companies like Microsoft support it: in their Azure Cloud Services!

Screenshotting And Web Scraping

Let’s take a look at something that can run the headless QUnit tests on the command line. PhantomJS is a headless WebKit-based browser with a neat JavaScript-based API (or CoffeeScript).

However, testing JavaScript and DOM is not the only way to use Phantom. What is fascinating is its ability to screenshot sites and take screenshots!

Yes, you read correctly. With Phantom, you can display web pages in various graphic formats. It is as easy as stealing sweets from your baby.

Let’s have a look at the script that does exactly that:

var page = new WebPage();

page.open(‘http://google.com’, function (status) {

page.render(‘google.png’);

phantom.exit();

});

That’s all you need to take a screenshot of, and since it’s JavaScript-based, you can also use jQuery and manipulate the page content before taking screenshots!

To Sum Up

As we can see, most of them do what we could already do with ES5’s JavaScript specification, but more accessible, cleaner, and legible.

It needs to be done carefully, avoiding using these magic features to make your code more confusing. After all, these features are here to make it better, not worse.

Also, if necessary, use a compiler to make these new features understandable to older browsers. You can test MDN for browser compatibility with these features.

Some topic headers have a link to the appropriate MDN page, so go there to see more information about each of them.

I hope you are as surprised as I was when I discovered each of these tools. This article has just touched on a few things that are now possible with JavaScript.

Leave A Reply

Your email address will not be published.