Categories
Uncategorized

Understanding the Execution of Code in JavaScript

What happens when JavaScript executes our code ? This is the question that we will address in this lesson.

Let us first go over the below code.

As soo as we start running our code, a global execution context gets created. So there is a thread of execution that is parsing and executing the code line by line. In global variable environment, live memory of variables with data is allocated. The above code clearly demonstrates the single threaded nature of JavaScript but it only shows the synchronous execution.

LOCAL EXECUTION CONTEXT

Running/calling or invoking a function is what creates a local execution context. So when you execute a function, a new execution context gets created. So this is what comprises an execution context :

  1. The thread of execution (we go through the code in the function line by line)
  2. A local memory (variable environment) where anything defined in the function is stored.

When we start running a function, a local execution context pertaining to that automatically gets created. Once the function is done with its execution, the same gets simply popped off from the call stack.

But what exactly is a call stack ?

Call stack is something that helps you to follow your code. So it basically tells us where the thread of execution is currently in our JavaScript code. This is a great format for tracking where our JavaScript thread currently is running the code.

Closures

When our function gets called, we create a live store of data (local memory/variable environment) for that function’s execution context. Now when the function is done with its execution, it’s local memory gets deleted except the returned value. But what if our functions could hold on to live data/state between executions ? This would let our function definitions to have an associated cache/persistent memory.

This starts with returning us a function from another function. JavaScript performs automatic garbage collection if the memory is no longer required whereas in other languages you may have to explicitly perform the deallocation of memory.

LEXICAL SCOPE

For closures, you can say it is closed over the variable environment. When a function is defined, it gets a [[scope]] property that references the local memory/variable environment to which it has been defined.

Let us see an example now,

Whenever we call the above incrementCounter function, it will always look first in its immediate local memory (variable environment) and then in the [[scope]] hidden property next before it looks any further up in the scope chain. It will always look first in its lexical scope. If it does not find the variable there, it will go up the scope chain till it finds a variable. Our lexical scope (the available live data when our function was defined) is what determines our available variables and prioritization at function execution, not where our function is called.

Categories
Uncategorized

Literals, Variables and Constants in C++

Variables, Literals and Constants in C++

In this tutorial, let us learn about variables, literals, and constants in C++ with help of some examples. So let us learn first what a variable is in C++.

C++ Variables

In programming, a variable is defined as a container that is used to store data. So it is used to store some information that we can later on reference and manipulate in our code.

So to create a variable, we first need a unique name for the variable. This unique name for the variable is also called as the identifier. So let us see some examples on how we can create and initialize variables in C++.

int age = 23; 
char b = 'a'

Here, age is a variable of the int data type, and to it we have assigned a value of 23. Next we have b which is a variable of the char data type and to it we have assigned some character data which in this case is ‘a’.

Note: One thing to note here is that a variable with the int data type can only hold integers. Similarly, a variable with the char data type can only hold data of character type. If we want to store decimals and exponentials, we can make use of the double data type.

Another thing to note here is that the variables are mutable in the sense that you can reassign the variable to difference values and hence this implies that you can change the content of a variable.

Let us also see an example for this :

int age = 23;   // initially age is set to 23
age = 29;       // reassigning the age to a new value of 29

Rules for naming a variable

  • A variable name can only have alphabets, numbers, and the underscore _.
  • A variable name cannot begin with a number.
  • It is a preferred practice to begin variable names with a lowercase character. For example, name is preferable to Name.
  • A keyword cannot be used as a variable name. For example, a keyword like int cannot be used as a variable name.
  • A variable name can start with an underscore. Also ensure that you give meaningful names to your variables which semantically makes sense.


C++ Literals

Literals are data used for representing fixed values. They can be used directly in the code. So in essence, these are source code representation of a fixed value or a sequence of characters which represents a constant value that is to be stored inside a variable.

For example: 156.5'z' etc.

Now these are called literals because you cannot assign a different value to these terms. Here is a list of different literals that we have in C++ Programming :


1. Integers

According to Wikipedia,

 An integer is a datum of integral data type, a data type that represents some range of mathematical integers. Integral data types may be of different sizes and may or may not be allowed to contain negative values. Integers are commonly represented in a computer as a group of binary digits (bits)

This means that an integer is a numerical literal that does not have any fractional or exponent within it. There are three types of integer literals in C Programming :

  • decimal (base 10)
  • octal (base 8)
  • hexadecimal (base 16)

For example:

Decimal: 0, -21, 46 etc
Octal: 02, 786 etc
Hexadecimal: 0x3f,  0x421 etc

A thing to note here is that an octal starts with a 0 and a hexadecimal starts with a 0x.


2. Floating-point Literals

Floating-point literals are numbers that have a decimal point or an exponential part. They can be represented as: Real literals. Binary floating-point literals.

-2.0

0.0000234

-0.22E-5

Note: E-5 = 10-5


3. Characters

A character literal is a type of literal in programming for the representation of a single character’s value within the source code of a computer program. It is represented by enclosing a single character inside single quotes. For example : 'b', 'f', 'G', '21', '}' etc.


4. Escape Sequences

 An escape sequence is a combination of characters that has a meaning other than the literal characters contained therein; it is marked by one or more preceding characters

Here is a lit of escape sequences for the given characters :

Escape SequencesCharacters
\bBackspace
\fForm feed
\nNewline
\rReturn
\tHorizontal tab
\vVertical tab
\\Backslash
\'Single quotation mark
\"Double quotation mark
\?Question mark
\0Null Character

5. String Literals

A string literal is a sequence of characters enclosed in double-quote marks. For example:

"This is a string"create a string
""empty string
" "string with a whitespace in quotes.
"x"a single character enclosed within quotes.
"This is a string\n"prints a string with a newline

We will also learn about Strings in a separate article as well. Let us now move forward to constants in C++.


C++ Constants

The value of a constant never changes once defined, so kind of it is immutable and cannot be re-assigned once a value has been fixed for a constant.

const int PI = 3.14;
PI = 3.233 // Error! PI is a constant.

See the above example here we have used the const keyword to declare a constant which we have named PI. Now if we try to mutate or change the value of PI,we will get an error because we cannot reassign a variable that we have declared using the const keyword. If we do so, we will get an error.

We can also create a constant using the #define preprocessor directive, something that we will learn about in a separate article.

Categories
Uncategorized web development

Top Web Development Tools in 2022

The demand for web developers is increasing exponentially as new, optimal and efficient ways are popping up for creating websites. To accelerate the pace at which websites are created and at the same time ensuring that the websites that we create are progressive, more and more tools are coming up. With improved technologies and modern workflow, we can now create modern websites at much faster pace than what we used to when these tools were not there or were in in developing phase.

Let’s discuss some tools that we can use in 2022 to improve our development skills.

Text Editors

As a developer, the first thing we need to get started with development is an editor of choice. You can use a text editor like Sublime Text or an IDE like Webstorm for building your web applications. The editor that I recommend using for building web applications is Visual Studio Code. With Visual Studio Code, you have an option to plug extensions into it to make it behave like an IDE so that it can provide us with great development experience. The only tools that we need for writing our code is a text editor and a web browser to execute our code and see the output for it.

1. Sublime Text Editor

Sublime Text is a commonly-used text editor used to write code in more than 20 programming languages. Sublime Text’s slick user interface along with its numerous extensions for syntax highlighting, source file finding and analyzing code metrics make the editor more accessible to new programmers than some other applications like Vim and Emacs.

2. Visual Studio Code

Visual Studio Code is a streamlined code editor with support for development operations like debugging, task running, and version control. It aims to provide just the tools a developer needs for a quick code-build-debug cycle and leaves more complex workflows to fuller featured IDEs, such as Visual Studio IDE.

Web Framework

A web framework is a software library that enables developers to write software that runs on the web. Common areas where developers use web frameworks are:

  • Backend: The software that runs on servers and serves web sites, web apps, and also APIs for the exchange of data.
  • Frontend: The software that runs on clients, in web browsers and provides content and interactivity to the user.

Web frameworks may be written in different languages and using different methodologies. The term ‘stack’ is applied to refer to the collection of different languages, software, and frameworks in use behind a specific service

As the web-development is divided into two main ends, known as front-end and back-end, so developers have created various frameworks for both ends.

Front-End Web-Frameworks

1. Angular

Angular is a modern frontend framework for building amazing and sleek user interfaces.

Angular is a development platform, built on TypeScript. As a platform, Angular includes:

  • A component-based framework for building scalable web applications
  • A collection of well-integrated libraries that cover a wide variety of features, including routing, forms management, client-server communication, and more
  • A suite of developer tools to help you develop, build, test, and update your code

With Angular, you’re taking advantage of a platform that can scale from single-developer projects to enterprise-level applications. Angular is designed to make updating as straightforward as possible, so take advantage of the latest developments with a minimum of effort. Best of all, the Angular ecosystem consists of a diverse group of over 1.7 million developers, library authors, and content creators.

2. React.js

React.js is a JavaScript library for building user interfaces.

React.js is an open-source JavaScript library that is used for building user interfaces specifically for single-page applications. It’s used for handling the view layer for web and mobile apps. React allows developers to create large web applications that can change data, without reloading the page.

3. Vue.js

Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web. It is yet another frontend framework that you can use for building amazing and sleek user interfaces. Vue follows the MVVM architecture and it is also a great alternative for building frontends. It also has an easier learning curve compared to other frameworks like Angular and React.

Backend frameworks

1. Django

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source

2. Ruby on Rails

Rails is a full-stack framework. It ships with all the tools needed to build amazing web apps on both the front and back end. Rendering HTML templates, updating databases, sending and receiving emails, maintaining live pages via WebSockets, enqueuing jobs for asynchronous work, storing uploads in the cloud, providing solid security protections for common attacks. Rails does it all and so much more.

4. Express.js

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. With a myriad of HTTP utility methods and middleware at your disposal, creating a robust API is quick and easy. Express provides a thin layer of fundamental web application features, without obscuring Node.js features that you know and love.

Package Managers:

package manager or package-management system is a collection of software tools that automates the process of installing, upgrading, configuring, and removing computer programs for a computer in a consistent manner.

A package manager deals with packages, distributions of software and data in archive files. Packages contain metadata, such as software’s name, description of its purpose, version number, vendor, checksum (preferably a cryptographic hash function), and a list of dependencies necessary for the software to run properly. Upon installation, metadata is stored in a local package database. Package managers typically maintain a database of software dependencies and version information to prevent software mismatches and missing pre-requisites. They work closely with software repositories, binary repository managers and app stores.

Package managers are designed to eliminate the need for manual installs and updates. This can be particularly useful for large enterprises whose operating systems typically consist of hundreds or even tends of thousands of distinct software packages.

1. NPM

Relied upon by more than 11 million developers worldwide, npm is committed to making JavaScript development elegant, productive, and safe. The free npm Registry has become the center of JavaScript code sharing, and with more than one million packages, the largest software registry in the world. Our other tools and services take the Registry, and the work you do around it, to the next level.

2. pip

pip is a package-management system written in Python used to install and manage software packages. It connects to an online repository of public packages, called the Python Package Index. pip can also be configured to connect to other package repositories, provided that they comply to Python Enhancement Proposal 503.

3. Yarn

Yarn is a new package manager that replaces the existing workflow for the npm client or other package managers while remaining compatible with the npm registry. It has the same feature set as existing workflows while operating faster, more securely, and more reliably.

Git Clients

Git is a DevOps tool used for source code management. It is a free and open-source version control system used to handle small to very large projects efficiently. Git is used to tracking changes in the source code, enabling multiple developers to work together on non-linear development.

1. GitHub Desktop

It is a software by GitHub which helps you to create and manage GitHub repository on your desktop. GitHub Desktop is currently available for macOS and Windows Operating Systems. If you do not like to work with git commands or terminal you can simply download GitHub desktop and use its interactive interface to commit and manage your GitHub repository.

2. GitKraken

Millions of developers and teams around the world choose GitKraken Client to make Git work for them. It makes Git more visual and accessible with an intuitive UI, the flexibility to switch between a GUI or a terminal, and a seamless experience across operating systems. Integrations with GitHub, GitLab, Bitbucket, and Azure DevOps make it swift and simple to clone, fork, and add remotes. You can even create, view and manage pull requests.

API Testing tools

API stands for Application Programming Interface, and API testing tools are the software which is used to test the quality of the API and the tool check whether the API stands on all the expectation or there are some shortcomings in that API.

1. Postman

Postman is an API platform for building and using APIs. Postman simplifies each step of the API lifecycle and streamlines collaboration so you can create better APIs—faster.

Thanks for reading the article !

Categories
Uncategorized

Demystifying the useRef Hook in 6 minutes

In this video, we will learn about the useRef hook in React. This hook is very similar to the useState hook that we had learnt earlier in the sense that it also persists the values across re-renders but unlike useState, useRef does not cause a re-render of the component. We will see a couple of examples to understand this hook in great detail..

Categories
javascript Uncategorized

Arrow Functions – When and When not to use them ?

Hey everyone 👋🏻,
In this article, let us understand When and when not should we use arrow functions.

Arrow Functions

With ES6, JavaScript has evolved a lot because of the customizations that the new standard brings to the language. It has immensely improved our development experienced with the introduction of Next Generation JavaScript features. One of such features that ES6 brings to the table is the Arrow Functions.
The purpose of writing this article is to make the reader aware about the scenarios where he/she should not use arrow functions and instead make use of the good old school function syntax or the function expression syntax. We need to be a bit careful as well while using arrow functions because they can affect the readability of our code as well.

When to use Arrow Functions ?

There are some solid reasons why using arrow functions can be a plus.

  1. Securing the scope : The arrow functions remember their context in which they are defined in and they stick to that.
    So even if we introduce a normal callback function and mix that with a couple of arrow functions, then that can lead to messing up of the scope.
  2. Compact : Easier to read and write. Just a fat arrow, and they can be anonymous as well.
  3. Code Clarity: When every function in your code is an arrow function, then a normal function is the one that we rely on for defining the scope. So we as developers can always look up the next higher order function statement to figure out the this keyword.

When not to use arrow functions ?

1. Defining methods on an object

In JavaScript, as we know a method is a function that we set in a property of the object. So right at the time of invoking the method, the this keyword points to the object that the method belongs to.

Now let us talk about Object Literals here. Let us say we want to define a method inside an object literal. At first, you might be tempted to use an arrow function for a method definition within the object literal. But let us understand with the help of an example, why you should not use an arrow function within the object literals.

const user = { 
  stocks : [
     {
      stock : 'Amazon', 
      price_in_dollars : 937,
      units_bought: 5
   },
   {
      stock : 'Tesla', 
      price_in_dollars : 652,
      units_bought: 3
   }, 
   {
      stock : 'Meta Platforms', 
      price_in_dollars : 465,
      units_bought: 2
   }
],
get_total_invested : () => { 
        console.log(this === window);
        return this.stocks.reduce((acc, stock) => acc + stock.price_in_dollars * stock.units_bought, 0);
  }
};

console.log(this === window);
const invested_amount = user.get_total_invested(); 
console.log(invested_amount); 

user.get_total_invested method as we can see is defined within an arrow function. But if you try the above code, the invocation to user.get_total_invested would throw a TypeError because in the above case this.stocks would resolved to undefined.

Image description

Now the thing to note here is that when we are invoking the get_total_invested method on the user object, the context in which it is called in is the window object which we can easily verify by comparing this keyword with the window object in the get_total_invested method as you can see within this method, the this keyword points to the window object. So in essence, this.stocks resolves to window.stocks and this ultimately gives us undefined because we don’t have any stocks property on the window object.

In order to solve this, we can simply switch to the function expression syntax or its shorthand for method definition. For this case, at the invocation point, this keyword would refer to the the thing to the left of the dot at the invocation point. Here is the code with the above modifications :

const user = { 
  stocks : [
     {
      stock : 'Amazon', 
      price_in_dollars : 937,
      units_bought: 5
   },
   {
      stock : 'Tesla', 
      price_in_dollars : 652,
      units_bought: 3
   }, 
   {
      stock : 'Meta Platforms', 
      price_in_dollars : 465,
      units_bought: 2
   }
],
get_total_invested(){ 
        console.log(this === user);
        return this.stocks.reduce((acc, stock) => acc + stock.price_in_dollars * stock.units_bought, 0);
  }
};

const invested_amount = user.get_total_invested(); 
console.log(invested_amount);

Now in the above code, get_total_invested is a method that is being called on the user object. So with the regular function syntax, the thing to the left of dot which is the user object here is what this resolves to in the end and therefore the above code would work fine. Here is the output for the above code :

Image description

From the output, you can also easily decipher that the this keyword indeed points to the user object and hence this === user returns true as a result.

Let us now move forward and take arrow functions with Object Prototype

function User(name, age, profession) { 
  this.name = name; 
  this.age = age; 
  this.profession = profession;
}
User.prototype.sayHello = () => { 
  console.log(this === window);
  return `Hello ${this.name}`; 
}
const user = new User('Alex',24,'Developer');
console.log(user.sayHello());

Now here also the same thing holds true as discussed above. In the above code, instead of using the arrow function syntax for defining our sayHello method where the this keyword points to window we should instead use the function expression syntax to solve this. So here is the modified code :

function User(name, age, profession) { 
  this.name = name; 
  this.age = age; 
  this.profession = profession;
}
User.prototype.sayHello = function(){ 
  console.log(this === window);
  return `Hello ${this.name}`; 
}
const user = new User('Alex',24,'Developer');
console.log(user.sayHello());

So with just this simple change, sayHello regular function is changing its context to user object when called as a method : user.sayHello().

2. Arrow Functions cannot be used as constructors

For constructors, use regular functions otherwise JavaScript will throw an error if it encounters an arrow function getting used as a constructor. This means that JavaScript implicitly prevents from doing that by throwing an exception.

Let us go a bit deeper inside and try to understand a bit more on this :

In simple words, the objects (or the “constructors”) rely on the this keyword to be able to be able to be modified.

The this keyword always references the global object which is the window object.

So if we have something like this :

const User = (name, age, profession) => { 
    this.name = name; 
    this.age = age;
    this.profession = profession; 
}
const user = new User("Alex", 21, "developer"); 

Executing new User("Alex", 21, "developer"), where User is an arrow function, JavaScript throws a TypeError that User cannot be used as a constructor.

But, instead if you do something like this :

const User = function(name, age, profession) {
   this.name = name;
   this.age = age;
   this.profession = profession; 
}
const user = new User('Alex',21,'developer');
console.log(user.name);

Now here, the new keyword does some magic under the hood and makes the this keyword that is inside the User to initially first refer to the empty object instead of referencing to the global object like it earlier did. Right after this, new properties like name,age and gender get created inside this empty object pointed to by the this keyword and the values will be Alex,21 and developer respectively. Finally, the object pointed to by the this keyword gets returned.

Now a thing to note here is that arrow functions do not allow their this object to be modified. Their this object is always the one from the scope where they were statically created. This is called Static Lexical Scope. This is precisely the reason that why we cannot do operations like bindapply, or call with arrow functions. Simply, their this is locked to the value of the this of the scope where they were created.

3. Arrow Functions as callback functions

As we know in client side JavaScript, attaching event listeners to the DOM elements is a very common task. An event triggers the handler function with this as the target element.

So for example, let us say we have this code 

const button = document.querySelector('button');
button.addEventListener('click',() => { 
 console.log(this === window); 
 this.innerHTML = 'Changed';
});

Now as discussed just a while back, this points to the window object in an arrow function that is defined in the global context. So whenever a click event occurs, browser tries to execute the handler function with the button as context, but arrow functions still stays bound to its pre-defined context.
In above code, this.innerHTML is same as window.innerHTML which does nothing infact.

In order to solve this, we need to make use of the function expression syntax which will allow us to change this depending on the target element.

const button = document.querySelector('button');
button.addEventListener('click', function() { 
 console.log(this === button); 
 this.innerHTML = 'Changed';
});

Now for the above code, this keyword will infact point to the button. Therefore, this.innerHTML will correctly modify the button text and reflect the same in the UI.

So this is it for this article. Thanks for reading.