JavaScript Series: Functions (part 4 – function constructors)

This blog concentrates on building a JavaScript object. There are multiple ways for building an object, by far, the most common one is the object literal way.

object_literals

Another way of building an object is via the function constructor. A function constructor is a normal function that is used to construct objects. In the case of a function constructor, the this variable points to a completely new empty object and that object is returned from the function automatically.

Let us try to understand with the help of an example:

functionContructor

Here, we can see the new keyword (line 8). If you are familiar with any programming language, you must have already used this keyword! In JavaScript, the keyword new is a operator that is responsible to create a completely new object (line 2 & 14) Additionally, this variable in the Person()function points to the new object created (in our case the ​Person { } object)  due to the new keyword.

Interesting fact to note here is that, if the function does not ​return anything explicitly, then the JavaScript engine realizes that a function Person() is invoked, (line 8 & 11), using thenew  operator. Therefore, it will return the object that was set as the this variable (line 16 & 19).

We are being able to construct an object using a function. Therefore, the Person () method is called as a function constructor.

JavaScript Series: Functions (part 3 – function borrowing and function currying)

In this blog we will be talking about:

  1. the this keyword
  2. call(), apply() and bind() methods
  3. function borrowing and function currying

Before we jump into the concepts here, please make sure you know what functoin declarations, function expressions and IIFEs are, cause we going to use them a lot in this blog!

this

Whenever a JavaScript function is invoked, the JavaScript engine provides us with three assets: a variable environment, the outer environment and the this variable. The this points at a different object depending upon how the function is invoked.

this_in_a_function

If we give a closer look to the code snippet above, there are three execution contexts being created here, one for each – the global context, function a and function b. Whenever we create a function declaration or a function expression that is simply defined in global level of the code, then the this will always point to the global object ​(​Window).

At this point, it might be clear that although you might think  you are attaching the this variable to your function but really you are clashing it with the global object!

What do you thing would happen if we used the this variable inside a function that resides in a JavaScript Object?

this_function_in_a_obj_literal

In the case, where the function is actually attached to an object, the that becomes the Object which the method resides in. In other words, when we use the this keyword, the JavaScript engine points it at the object that contains it.

change_value_using_this

Therefore, now we can change the properties of the parent object, the one which holds the function. In the above example, since this points to the c object, we can change the name property inside the object. I hope that makes sense by now 🙂

The this keyword could be difficult to understand sometimes and can cause debugging time cumbersome. What if I said, we could control the value of this? Yes, we can do it. The methods call(), apply() and bind() help us with just that!

Function Borrowing!

All functions in JavaScript can execute few defaults methods such as call(), apply() and bind(). This is possible because of something called as ​​prototype which we will cover in one of the next blogs in the JavaScript series.

Function borrowing deals with the usage of  call() or apply() method. The call() or apply() method executes the calling method and passes an object to that calling method which signifies the value of this. To be more clear, the parameter here (the object) to the calling function signifies the value of this.

Let us understand this with an example:

functoin_borrowing

In the above case, the person2 object does not have the getFullName function but it is being able to access the function present in the person object with the help of apply() method. Lets give a closer look:

person.getFullName.apply(person2)

As we can see, the parameter  person2 has the same properties as person. It is passed as a parameter to the apply() which sets it to the value of this to the person2 object. Now when the function getFullName is invoked, the value of this.firstname would be same as person2.firstname. This is called as function borrowing.

Function Currying

Function currying involves creating a copy of a function but with some preset parameters.

function_currying

Function currying deals with the usage of  bind() method. The bind() method duplicates (makes a copy)  of the calling method and passing in the this keyword with the preset value. Just as we can see in the above example.

We took a function, created a new function from it  with some default parameters. This is called as function Currying.

Difference between the bind() and apply() methods

  • The bind() method creates a copy of the calling method where as the apply() method executes the calling method.
  • The bind() method would accept parameter in the form: bind(this, param1, param2) whereas the apply method accepts parameters in the form: apply(this, [param1, param2])

So, that was my understanding about the ​this keyword, please feel free to share more information/add-ons/good reads about it in the comment box.

JavaScript series: Functions (part 2 – Immediately Invoked Function Expressions)

In this blog, we will understand about:

  1. What are Immediately Invoked Function Expression (IIFE)?
  2. How does an IIFE work?
  3. Why are the IIFEs useful?

By now, we understand what function declarations and function expressions are. To quickly jog our memory, lets revise our concept for function expressions here.

func_expression

Here, we have an equals operator which is responsible for assigning the object (function) into memory and pointing the greetFunc variable at that address. Since, the above function results in a value, therefore, it is a valid function expression.

Immediately Invoked Function Expression (IIFE)

iife

The highlighted portion in the above code snippet signifies a function object. Adding a pair of parenthesis right after the function object creation, invokes the function. Such an expression is called is an Immediately Invoked Function Expression (IIFE). In the case of IIFEs, the function is invoked at the point where it is created.

Also, note that in the above code snippet, the variable greetFunc holds a String and not a function, so we now we cannot do something like greetFunc() like we did in the previous function expression snippet.

Pretty easy to understand right? Let see where and how this is useful!

Before getting into that, let us look at some other function expressions:

expression

If you look closely, what do you expect when I run this piece of code? should it give me an error? For a matter of fact, it does not give me any errors. These are perfectly fine JavaScript expressions.Although, these JavaScript expressions are not stored in memory but they simply get executed.

uncaughtsyntaxerror

What do you think would happen if I did the same with a function? (just like in the above code snippet). You probably saw the answer in the snippet itself! Yes, it throws an error.

It is very important to understand that, here, the syntax parser looks at the starting keyword function and assumes that this is a function declaration.Since, the JavaScript syntax parser assumes this to be a function statement, it expects the function declaration to be named! Therefore, it throws an error: Uncaught SyntaxError: Unexpected token (.

What can we do to fix this? We need to make sure that function is not the first word that the syntax parser see’s.

iife_example

We can wrap the function object inside a pair of parenthesis! Parenthesis in JavaScript is an operator. We use parenthesis only with expressions like (3 * 4) + 2;. Since the JavaScript engine knows that anything inside these parenthesis is an expression, it assumes that this function (in the snippet) is a function expression which is created on the fly!

Therefore, now we have an function expression that we created on the fly. It is inviolable and I can pass values to it! This is a classic example of an IIFE.

One last thing about the IIFEs, I want to get your attention is that any code/variable in the IIFE does not interfere with/crash into or be interfered by any other code that might be included in our application.

variablesinIIFE

So now we understand that by using IIFEs in our code, we can make sure we aren’t colliding with other code when creating something reusable.

Conclusion:

  • In the case of IIFEs, the function expression is invoked at the point where it is created.
  • The JavaScript parser expects the function declarations to be named.
  • Function expressions can be defined without variable assignment.
  • Parenthesis in JavaScript is an operator.
  • Any code/variable in the IIFE does not interfere with/crash into or be interfered by any other code that might be included in our application.

JavaScript series: Functions (part 1 – declarations, expressions and arrow functions)

In this blog,  we will talk about:

  1. Function Declarations, Function Expressions and Arrow Function Expressions.
  2. Hoisting.

Before we begin, let us first understand what is a JavaScript function? In JavaScript, functions are objects, you can do something like:

functions

A greet() function which simply prints ‘Hi’ to the console. Nothing new about that, we have seen that happening in other programming languages too! Now, the interesting part is that we can assign a property, which in this case is, language to functions. Therefore, functions are objects in JavaScript. A function is a special type of object that can contain values such as a primitive, an object and it can contain another function too.

Now, lets understand what are the numerous ways a function can be defined. A JavaScript function can be defined in one of the following forms:

Function Declarations:

function_statement

The getName function in the above code snippet is an example of the function declaration (commonly known as function statement). The named function is a must in the case of function declaration without requiring a variable assignment.

A declared function is “saved for later use” and will be executed later, when it is invoked (called). To understand this better, we must understand the concept of hoisting (which we shall see in the latter part of this blog).

Function Expressions:

function_expression

An expression is a unit of code that results in a value. Here, we have an equals operator which is responsible for assigning the object (function) into memory and pointing the getName variable at that address. An interesting thing about the function expressions is that the functions stored in variables do not need function names, rather they can be invoked (called) using just the variable name.

Arrow Function Expressions:

arrow_functions

I wouldn’t call this to be a third way of defining functions but rather more like a variation of the function expressions. If you notice closely, as compared to the normal function expression above, here we get rid of the function keyword and add an arrow => operator in front of the argument.

The arrow functions are not only just used for its smaller or better syntax but also for reasons like:

this_arrow_function

The behavior of this keyword. When using  the this inside a function expression, normally this would point to the object that it resides in. In the case of an arrow function, the this keyword does not create its own scope. Therefore, it take the value of the outer scope.

Last concept that, we want to understand in this blog is ​​Hoisting​!

Hoisting

hoisting

Before your code gets executed line by line, the JavaScript engine has already set aside some memory space for the variables and functions that you have created in your application.

In the case of functions, its entire body including the name and lines present inside the function are placed into the memory. While, in the case of variables, during the execution phase (where actual code is executed line by line), variables are assigned to their values.

So when the JavaScript engine sets up the space for ​getName​ variable in the function expression, it does not know what its value will be until it starts executing the code. Instead, it puts a placeholder called ​undefined​. Therefore, at the time of assignment, all variables in JavaScript are assigned to `undefined`, while functions sit entirely in the memory.

Conclusion:

  • Functions are objects in JavaScript.
  • A declared function (function statement) is “saved for later use” and will be executed later, when it is invoked (called). Function hoisting can be performed in the case of Function Declarations.
  • An expression is a unit of code that results in a value.
  • Function expressions need not have a name to its functions. They can not perform function hoisting.
  • In the case of a arrow functions, the `this` keyword does not create its own scope. 
  • At the time of assignment, all variables in JavaScript are assigned to `undefined`, while functions sit entirely in the memory.

References and credits:

1) React training – https://courses.reacttraining.com/p/javascript-the-react-parts
2) JavaScript: understanding the weird parts – https://www.udemy.com/course/understand-javascript
3) ES6 Features – https://codetower.github.io/es6-features

 

Ruby in Goa! – Part 2

The Event Day
~~~~~~~~~~~

IMG_20190120_093926

Right after the wonderful Golang workshop by William Kennedy, it was now time to celebrate the 10th year of Ruby Conference India on the 20th and 21st of January, 2019.

RubyConf India is a global event complementing other RubyConf events across the world. This year the event was a 2 day, single track event focused on Ruby Language, Framework and Tools.

IMG_20190120_135542.jpg

“Matz is Nice So We Are Nice”

The conference took off with Matz keynote (those of you who don’t know Matz need to know that he is the creator of Ruby language and an awesome human being!), he spoke about:

  • Ruby as a programming language.
  • The past, present and future of the programming language.
  • He also told us that he is going to work on concurrency in ruby in 2019.
  • The power of the community.

One more interesting talk that I would like to mention is The Ultimate Ruby Developer’s Command Line Toolkit – by Brad Urani. Basically, he has given a bunch of  “dot” file scripts that might help one to fasten his/her daily work. If you just go through his slide deck, you will get the entire gist of his talk. You can find his slide deck here.

Another great talk that one must look for was Using Tests as a Tool to Wrangle Legacy Projects – by Jason Swett. Jason is fairly a cool Rubyist and a trainer for Ruby testing. To get the gist of his talk you can read an article written by him here.

 

Conversations
~~~~~~~~~~~

An evening party was held at the end of the first day of the conference where I had some interesting conversations which I would like to share:

Goutum Rege: We spoke about how important it is to set goals in life. Speaking of which he said that it is very important that all our goals are time specific.

Matz: I was very curious about how new features are added to Ruby. When I asked Matz about the same, he said that he used to speak with the core developers of Ruby and used to visit many conferences where he met various Ruby users. He also added that once he has collected all the views from the developers and the users, he chooses what could possibly go in the next version of Ruby.

When I asked him about his opinion on learning new languages, he said every programming language is created to solve a specific set of problems and that learning new languages help in understanding a different perspective. So it is good to know other languages too.

Anshul Khandelwal: He is the founder of difference-engine.ai, a company in Mumbai that works on AI to solve problems faced by lawyers while creating documentation. So at present, they are using Teraform for provisioning the machines in their infrastructure but were looking for a change! Considering how Teraform and Foreman are pretty similar applications 😛 , I thought it was the right time to tell him that I work on Foreman. If things go as per plan, we might soon have a Foreman session in Mumbai.

Bilal Budhani: We spoke about how GraphQL has grown through the years. Last year when I met Bilal he was writing a book about GraphQL and Ruby. The reason why he couldn’t finish his book yet is that too many features are getting introduced with each version of GraphQL and that many quick changes taking place with each release.

I also spoke to a group of people who were talking about whether there should be informal/non-technical talks in a technical conference like Ruby Conf.

 

Conclusion
~~~~~~~~

Ruby Conf India has been one of the exceptionally awesome conferences where I keep meeting some new like-minded people every year.

Golanging in Goa! – Part 1

Prelude
~~~~~~~

Goa is a state in the western India with coastlines stretching along the Arabian Sea. Goa is known for its beaches, ranging from popular stretches at Baga and Palolem to those in laid-back fishing villages such as Agonda. But my reason for being in Goa this time was a lttle different.

I visited Goa for two reasons:

  1. Golang Workshop by William Kennedy(“Bill”).
  2. Ruby Conf India 2019.

Golang Workshop
~~~~~~~~~~~~~~

The Golang workshop was a two-day event, which was meant for a naive or new to Golang audience. It aimed at learning the specifications, implementation and idioms to help one be a better Go developer.

Bill is a very enthusiastic teacher and has many years of experience in teaching Golang. In his words “this workshop is about teaching enough Go so people can read as much code as possible. I throw in a lot of the why and reasoning behind the language.”

IMG_20190116_174039.jpg

The workshop covered many topics right from language syntax, methods, interfaces, concurrency to Go routines and channels. Bill focused a lot on explaining the history of Golang and why things are the way they are in Golang.

Quotes :
~~~~~~~

I would like to share some beautiful, informative and inspiring quotes that Bill shared while he was talking about the history of Golang:

Engineering is all about understanding the cost of your decision.

He said that every decision that you make comes with a cost. There is a benefit of that decision and there is a cost. If the benefit is worth the cost then you have made the right engineering decision.

There are two kinds of software projects: those that fail and those that turn into legacy horrors – Peter Weinberger.

Debuggers don’t remove bugs, they only show them in slow motion – William Kennedy

What he meant by this was that he doesn’t believe in fixing his issues using debuggers because debuggers are not meant for doing that. This was a new thing for me though! According to Bill, one should use their logs extensively rather than the debuggers.

The one that I like the most and can surely agree to is:

We think awful code is written by awful developers. But in reality, its written by reasonable developers in awful circumstances – Sarah Mei

Some of the specific take-aways from the Golang workshop are:

  • Nothing is free! every engineering decision comes with a cost.
  • Golang is a data-oriented programming language.
  • Everything in Golang is a “pass by value”. What you see is what you get!
  • There are only types of semantics – value semantics and pointer semantics. In value semantics, every piece of code operates on its own copy of data while in pointer semantics data is shared between the resources.
  • When we define a piece of data in Golang, we must think about the semantics and make it consistent throughout the application for that data.
  • Don’t guess anything!
  • Go promises not to take more than 25% of the CPU capacity.
  • Remove non-productive allocations!
  • Don’t hide sharing of data(meaning ), it hides the cost!
  • SMALL == FAST !
  • Use comments when you are taking an exception.
  • Always use pass by value for slice and map.
  • Never to go from pointer semantics to value semantics.
  • You don’t always need interfaces in Go. It’s called interface pollution.
  • You cannot design your project with interfaces, you need to discover them.
  • Interface values are valueless. It is used for data storage.
  • In your program, the main function is the only function that talk configuration!
  • Don’t treat Go channels as queue’s, treat them as signals.

 

Conclusions
~~~~~~~~~~~

The workshop seemed to revise a lot of things that I had once studied theoretically in college. I loved to learn about the reasoning that Bill gives for Golang to be the way it is. I really enjoyed the Golang workshop, thanks to William Kenedy for that.

RootConf’18

Prelude
~~~~~~~

The ###rootconf India is one of the most renowned conferences on DevOps and IT Infrastructure. The conference attracts a huge amount of contributors and DevOps enthusiasts throughout India. RootConf’18 was held on 10th and 11th May at Bangalore.

  • The aim of the conference:
    1. Learn how to avoid expensive mistakes when designing and maintaining your infrastructure.
    2. To network with some of the best system engineers and DevOps programmers in India and South Asia.
    3. To talk to decision-makers and IT managers on how they plan infrastructure for their companies.

This slideshow requires JavaScript.

The Event
~~~~~~~~~

Day 1: Ansible Workshop
~~~~~~~~~~~~~~~~~~~~~

I was invited to ###rootconf for conducting a workshop on Automation with Ansible: beginner to advanced

  • Topic covered in the workshop were:
    1. Introduction to configuration management.
    2. DevOps concepts like infrastructure as code, idempotency, and build/deployments.
    3. Ansible requirements, installation, and configuration.
    4. Ansible inventory, playbooks, modules, variables and conditionals, roles and galaxy.
    5. Lastly, how Ansible fits in as a perfect configuration management tool in the DevOps world.

The workshop was held on 9th May, one day prior to the main conference, I had created a GitHub repository which consisted of multiple questionnaires, exercises, and quizzes for the attendees. Multiple pull requests were received for the quiz and exercises.

 

 

Day 2 and Day 3: Main Conference Days
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

IMG_20180510_154007_HHT

 

It was a two-day conference and all the talks mainly focused on DevOps and Securing Systems. The first day of the main conference was mostly about Securing Systems while the second day consisted of the DevOps related talks.

I presented a lightning/flash talk about the Foreman project at the conference which can be found on youtube.

At around 6 pm in the evening, when the conference was about to end…the screens were shutting down…we were packing up to head home, Bangalore rains decided to give us a surprise. Stuck in the rain, when we were just starting to wonder on finding ways to pass the time, we accidentally ended up meeting @_riddhishree and attending an awesome session on application security. Well, that’s the thing about tech conferences. The most interesting conversations mostly are the ones not on the schedule.

 

This slideshow requires JavaScript.

 

Conclusion
~~~~~~~~~

If I had to summarize RootConf in a single sentence, it would be – “interesting talks, workshops and super enthusiastic people!”

 

 

My talk at TheDevTheory Conference’18

Prelude
~~~~~~~

TheDevTheory Conference was a developer community based, one-day technical conference. The conference was held at hotel Le Meridien, Gurgaon on 14th April, 2018. It had two dedicated tracks, covering various topics on DevOps and modern web development. The conference aimed to present a perfect opportunity to network with delegates and explore the modern trends and solutions in the industry. Connecting developers, discussing & debating on latest technologies were one of the main focus areas of the conference.

The Event
~~~~~~~~~

The event started with a keynote by Lee Faus(@leefaus) where he pointed out the importance of software economy and how software economy is shaping the way we use information, make decisions and collaborate on best practices.

This slideshow requires JavaScript.

Soon after the keynote the conference room was divided into two tracks, one with the DevOps theme and the other with the modern web development theme. My talk was for the DevOps theme and I spoke about the Foreman project.

I covered  the “Configuration Management at its peak with Foreman” topic, where I addressed the following:

  1. What is the need for configuration management?
  2. Forms of configuration management.
  3. Puppet: a configuration management tool.
  4. What is Foreman?
  5. How does it add up to the big picture?
  6. Key features and architecture of Foreman.
  7. Demo: Puppet integration with Foreman.

This slideshow requires JavaScript.

You can find the slides for my talk here.

This was one crazy crowd…way beyond my expectations! Such knowledge and enthusiasm on the Foreman project is not something a speaker gets to experience everyday. The session was a highly interactive one. Many questions were asked, few of them were:

  1. If I am using Cobbler, well integrated with Ansible, and it seems to work perfectly fine then why should I use foreman instead?
  2. There are APIs that Puppet, Ansible and other configuration management tools provide for reporting related work, then what is so special about Foreman’s API?
  3. Does Foreman support Ansible as a configuration management tool?
  4. I have some Ansible playbooks as part of my source code repository and I do not want to do all these tasks in Foreman UI. Rather I would like to configure Foreman in such a way that it can pick these playbooks and inventory files from my git repository and run them on the managed host. Is this feature available?

 

Conclusion
~~~~~~~~~

The talk being so interactive and people asking a lot of questions signifies the popularity and curiosity of people towards Foreman. I also met an attendee who had bought the ticket of the conference just becasue there was a talk submitted on Foreman. It was really great to hear that and made me so proud to be a part of this awesome project.

This slideshow requires JavaScript.

 

 

A day at the hackathon!

Prelude
~~~~~~~

This Hackathon I am going to tell you about was held on 16th February, 2018 at the Maharashtra Institute of Technology(MIT) College of Engineering, Pune. The 30 hours Hackathon was made a part of the Persona Fest.,2018 which was organized by the MIT college. The Hackathon focused on building a smart application that would automate tasks that are usually done manually in a university, such as – hostel management system, smart laboratory system, announcements portal, etc.

The Event
~~~~~~~~~

16th February
~~~~~~~~~~~~~

Under the Red Hat’s University Outreach program, I and Poojarani Chopra were invited to mentor the Hackathon.  The Hackathon had around 16 teams, including 2 teams from Bangalore and 1 from Mumbai. A total of 70 students participated in the Hackathon.

The event began with a ceremony where the Dean of the MIT college, Prof. Dr. Kishore Ravande, felicitated us with a bouquet of roses and introduced us to the participants.

This slideshow requires JavaScript.

Soon after the ceremony, the Hackathon began! Since students were going to build their project from scratch, I thought it would be great if I could explain them the importance of an Open Source License in their project.

I spoke about “How to choose an Open Source License“, where I addressed the following topics:

  1. What is Copyright?
  2. Why do we write software?
  3. Why use an Open Source License?
  4. Types of Open Source Licences.
  5. How to decide what type of open-source license to use?

This slideshow requires JavaScript.

You can find the slides for my talk here.

Throughout the hackathon, a lot of interesting questions came up. I don’t really remember all..but a few interesting ones were:

  1. Which open-source database is the most appropriate to use in a web application?
  2. One should use Django or Ruby on Rails for the given problem statement?
  3. How to contribute to Open Source?

Students also asked many questions related to their code as and when they got stuck. A lot of students were trying to deploy their applications on Heroku but were facing problems doing so. That’s when I decided to demonstrate Openshift to them. I explained how they can deploy their small application for free on Openshipt online. One of the students literally thought of Openshift as magic! Well, it is 🙂

Conclusion
~~~~~~~~~

Meeting enthusiastic students and spending some fun time coding is something I totally love doing. I would like to take this opportunity to thank Rupali and Varsha for giving me this chance of being at such a fun event. The University Connect program is not only helping a lot of students meet Red Hatters and learn more about Open Source and Red Hat…it is also helping a lot of us get more opportunity of working with students and also delivering interesting sessions.

The one great feeling thats worth sharing here was that when I was distributing some feebies at the college, the students loved it so much that they ended up calling me Santa Clause! I totally loved being one 😛

end