What every Ruby developer should know before learning Javascript

How to transition from Ruby to Javascript in one day #

After inundating myself with Ruby for close to six consecutive weeks it was time for us to go on a break. We had a lot of fun together and we learned a lot about each other but evidently in the end, we needed a break to really figure some things out.

Enter JavaScript.

JavaScript is a programming language created in 1995 by Brendan Eich while working at Netscape. Over the last 20 years it has become synonymous with front-end web development which makes it a very important language to know.

This week was our introduction to JavaScript. With my past experience learning Ruby it was an interesting experience diving into a new language. I knew that the syntax would be similar but there are certain design patterns that change from language to language.

It is human nature to want to compare one thing to another. That has been our process through years of evolution. We make patterns and connections in our mind from past experiences which helps us to make sense of the world. The process of connecting those dots happens with people as well as new languages.

The natural tendency for most people would be to compare Ruby with JavaScript and first look for their similarities. This can be a good starting point to familiarize yourself with a new programming language. You understand syntax in one language and expect it to work the same way in another.

However the beauty of something new lies within it’s differences! The magic of learning something that you never knew before is undoubtedly the patterns that are fresh, that are brand new.

Today i want to share some of those with you:

Variable setting #

At a fundamental level you need to know how to declare a variable in JavaScript. You can declare a variable in javascript using the var keyword.

var myName = "Sade Adu"
return "Hi, My name is " + myName

myName = "Daft Punk"
return "Hi, My name is " + myName

In JavaScript you can declare a variable by setting var variableName = “Something”. You MUST remember to include var in your declaration or you will run into some severe problems. After declaring the variable with var you can assign it to a new value without including the var keyword. Additionally JavaScript does not support string interpolation, therefore remember to use the + operator to string values together.

Also, the JavaScript convention for naming variables is to use camelCase!

Declaring a function #

Every function in JavaScript is an object. It is one of the design patterns which makes it an object-oriented language. JavaScript functions also make it a very powerful language to do a lot of complex functionalities on the web. Here are 3(+1) ways you can write a function in javascript:

1. Function constructor

var sum = new Function('a','b', 'return a + b;');
alert(sum(20, 30)); //alerts 50

var Artist = function(name, details){
     this.name = name;
     this.details = details;
}

return new Artist("Sade", "Goddess")

EQUIVALENT

function Artist(name, details){
     this.name = name;
     this.details = details;
}

return new Artist("Daft Punk", "Robots")

2. Function declaration

function sum(a, b)
{
    return a + b;
}
alert(sum(50, 50)); //Alerts 100;


3. Function Expression

var sum = function(a, b) { return a + b; }

alert(sum(10, 10)); // alerts 20


4. Anonymous Function

(function() {
    alert('I am anonymous');
})();

A function in JavaScript is a unique design pattern that will be a little tricky to wrap your head around coming from Ruby. It can act as a sort of class, or a method or even just a block.

In the first example you can use a Function constructor which sort of acts like a class in Ruby. With a Function constructor you can attach methods to the function and create instances of the constructor, similar to an instance object in ruby.

In the second example you can use a Function declaration which allows you to pass that function around to other areas of your program.

In the third example you can declare a function using a Function expression which will be local to the environment that you are working in. A function expression can be useful when you only need to use a function object in one area of your program and you want it to stay local to that scope.

The last example is an anonymous function which is extrememly popular in JavaScript. An anonymous function is a function that does not have any stored identifier attached to it. As you can see in the example we do not declare a Function name or pass in any arguments. The anonymous function is useful because it is not accessible after it’s creation which allows you to use it as a private function.

Methods #

A javascript method is a function associated to an object.

function artist(name, details) {
    this.name = name;  
    this.details = details;
    this.changeName = function (name) {
        this.name = name;
    }
}

In the above example we use a method changeName which will allow you to change the name of your object.

No arrity checking #

JavaScript uses a concept of no arrity checking which means that it does not keep track of the arguments you pass in.

function showArgs() {
   return arguments
}

new showArgs([1,2,3,4,5])
=>/ 1,2,3,4,5

It’s important to note here that arguments is not an array, but rather an array-like object. There are certain methods you can use on arguments which behave like an array and others you cannot.

Prototyping #

Prototyping is a feature of JavaScript that allows us to create instance methods on an object.

Artist.prototype.whisper = function() {
  return "Hi my name is  "+ this.name + " and I am a " + this.detail;
}

Using a prototype allows us to add new properties and methods to the Artist object. Whether you are creating a prototype property or method, the really useful feature is that it is available to all of the objects when you attach it.

Hoisting #

JavaScript has a very magical concept of hoisting which allows you to use a variable before it has been declared.

Example 1

x = "Sade"; // Assign "Sade" to x
var x; // Declare the variable x
x =// is now "Sade"

Example 2

var x; // Declare x
x = "Sade"; // Assign "Sade" to x

Example 1 and 2 will return the same result for x. With JavaScript hoisting, the default behaviour is to push all declarations to the top of the current scope (script, page or function). In a nutshell at run-time JavaScript moves all of your declarations to the top of the file and then runs the file.

Hoisting makes writing code very forgiving to the careless programmer. To avoid any unwanted bugs or errors it is still a good practice to declare your variables at the top! Key point to remember when hoisting:
JavaScript only hoists declarations, not initializations.

E.g. Example 1 does not give the same result as Example 2:

Example 1

(function() { 
  var a = 'Sade'; 
  var b = 'Daft PUnk'; 
  // more lines of code 
})(); //undefined

In this example a and b are undefined when the program runs.

The reason is because the declaration (var a), not the initialization (=“Sade”) is hoisted to the top.

In JavaScript hoisting a is declared before it is used and since initializations are not hoisted, the value of a is actually undefined.

Example 1 is the same as writing:

What's really happening:

(function() { 
  var a, b; // variables declared 
  a = 'Sade';   //initialization
  b = 'Daft Punk'; // initialized 
})();  //undefined

So remember that in hoisting ONLY the declarations get hoisted to the top, not the expressions or initializations. Declarations = pushed, not anything else.

In our next installment we will talk about IIFE, closures and *this!

 
3
Kudos
 
3
Kudos

Now read this

Building a Rails 4 app using the Twilio API

This weekend I wanted to challenge myself by building a functional web application using the rails framework. My goal for this project was to use an API that I was unfamiliar with and that could be used from my iPhone. I settled on the... Continue →