var vs const vs let in JavaScript

When programming in JavaScript, developers have three main options for declaring variables: var, let, and const. Each of these options has its own advantages and use cases, and understanding the differences between them is crucial to writing efficient and effective code.

Var

Var is the oldest way of declaring variables in JavaScript, and it has been around since the language’s inception. One of the most significant advantages of var is that it is globally scoped, meaning that variables declared with var can be accessed from anywhere in the program. However, this can also lead to unintended consequences, as variables declared with var can be overwritten or redeclared without generating any errors. Additionally, variables declared with var are not block-scoped, meaning that they can be accessed outside of their declared block.

Let

Let is a relatively new addition to JavaScript, having been introduced in ES6 (ECMAScript 2015). Unlike var, variables declared with let are block-scoped, meaning that they can only be accessed within the block they are declared in. This makes let a safer and more reliable option than var, as it eliminates the possibility of variables being accidentally overwritten or redeclared. Additionally, let variables can be updated without being redeclared, making them more flexible than const variables.

Const

Const, short for “constant,” is another ES6 addition to JavaScript. As its name suggests, variables declared with const cannot be reassigned once they have been declared. This makes const variables useful for defining values that should not be changed, such as mathematical constants or configuration values. Additionally, like let, const variables are block-scoped, making them safer and more reliable than var variables.

So, which one should you use?

The answer to this question largely depends on the specific use case. In general, however, the rule of thumb is to use const for values that should not be changed, let for values that can be updated, and var sparingly (if at all) due to its global and non-block-scoped nature.

It’s also worth noting that there is no single “best” way to declare variables in JavaScript. Each option has its own strengths and weaknesses, and developers should choose the option that is best suited to their specific use case.

In conclusion, understanding the differences between var, let, and const in JavaScript is crucial to writing efficient and effective code. By using the appropriate option for each variable, developers can write code that is reliable, flexible, and easy to maintain.

Why database should be taught before programming in universities?

Database Programming
Learn Database before Coding

Often students from the initial semester ask me how do we store our data in our programming projects? When students join university to learn about computer science and technology they are usually taught programming first in courses like introduction to programming. As part of the coursework, students are required to work on a project. The majority of the projects, in fact almost all projects involve data handling and that data needs to be stored somewhere, usually in databases.

Problems Students Face

As a novice students don’t know how to store data. One option is to store data in plain text files if filing is taught to them but in that case, their project becomes too complex for them. In my opinion, file format is an advanced topic for students that have just started learning how to program. So, students get stuck on where and how to store data. They create variables and arrays to store data in memory but that is not very useful until they have the option to store their data somewhere permanently that they can retrieve later. Otherwise, every time they run their project they have to feed data from the beginning.

Teach Database Before Programming

If universities modify their courses and add database in the first semester and replace programming courses with it then it would be easier for students to get started in computer science degree. Introduction to databases is a relatively easier course than programming and students will know what a database is, how to store data in the database, and how to retrieve it later using SQL. Then in the next semester if they do a programming course then it will require only one lecture to teach them how to access a database from your code and how to store and retrieve data. That will make their projects more valuable and make more sense to them and they can take it to an advanced level in forthcoming courses.

Your Take?

What is your opinion? Please, let me know in the comments.

Click here to read more about Databases.

Sharing data between Laravel and Angular

When building applications with Laravel and Angular you might come across a problem where you want to print data using AngularJS brackets {{}} but before it can be parsed by Angular, Laravel blade engine parses it and tries to replace the value if it finds one. Otherwise, Laravel will start complaining about the variables. To solve that you just need to prepend brackets with @ sign so the blade engine knows that you just need to ignore this expression and AngularJS will take care of it. And AngularJS will parse it and replace the variables with actual data.

Below is a sample snippet to do this:

@{{ article.body }}

In this snippet, the Laravel blade engine will ignore this and AngularJS will parse it and replace it with the article.body data it has.

Click here to read more about Laravel and Angular.

One reason why you should refactor your code often

Once upon a time, a consultant made a visit to a development project. The consultant looked at some of the code that had been written; there was a class hierarchy at the center of the system. As he wandered through the hierarchy, the consultant saw that it was rather messy. The higher level classes made certain assumptions about how the classes would work, assumptions that were embodied in inherited code. That code didn’t suit all the subclasses, however, and was overridden quite heavily. If the superclass had been modified a little, then much less overriding would have been necessary. In other places, some of the intentions of the superclass had not been properly understood, and the behaviour present in the superclass was duplicated. In yet other places several subclasses did the same thing with code that could clearly be moved up the hierarchy.

The consultant recommended to the project management that the code be looked at and cleaned up, but the project management didn’t seem enthusiastic. The code seemed to work and there were considerable schedule pressures. The managers said they would get around to it at some later point.

The consultant had also shown the programmers who had worked on the hierarchy what was
going on. The programmers were keen and saw the problem. They knew that it wasn’t really their fault; sometimes a new pair of eyes is needed to spot the problem. So the programmers spent a day or two cleaning up the hierarchy. When they were finished, the programmers removed half the code in the hierarchy without reducing its functionality. They were pleased with the result and found that it became quicker and easier both to add new classes to the hierarchy and to use the classes in the rest of the system.

The project management was not pleased. Schedules were tight and there was a lot of work to
do. These two programmers had spent two days doing work that had done nothing to add the
many features the system had to deliver in a few months’ time. The old code had worked just fine. So the design was a bit more “pure” and a bit more “clean.” The project had to ship code that worked, not code that would please an academic. The consultant suggested that this cleaning up be done on other central parts of the system. Such an activity might halt the project for a week or two. All this activity was devoted to making the code look better, not to make it do anything that it didn’t already do.

How do you feel about this story? Do you think the consultant was right to suggest further clean-up? Or do you follow that old engineering adage, “if it works, don’t fix it”?

Six months later the project failed, in large part because the code was too complex to debug or to tune to acceptable performance. The consultant was brought in to restart the project, an exercise that involved rewriting almost the whole system from scratch. He did several things differently, but one of the most important was to insist on continuous cleaning up of the code using refactoring.

This is an excerpt from the book preface “Refactoring – by Martin Fowler”.

AngularJS vs BackboneJS vs EmberJS? What I decided and why?

I was researching for Javascript frameworks/libraries to use in my next project. I found three promising JS frameworks.

What I was looking for was that framework should be easy to learn and should be integrated in the project easily. Keeping in that mind I searched a little bit about each and went through some reviews. What I concluded I’d just say it in one line for each.

Backbone.js – You need to write lots of boilerplate code to get to work.

Ember.js – It has a steep learning curve.

Anguler.js – Just in between. Offers more than backbone and is easier to learn than ember.

So, that was it! I picked Angular for my next project since it was easier to learn and you don’t have to do a lot to get it working in your project. Since the project was new and the deadline was short, this was the requirement. So, I decided to go with Angular and I’m glad I made the right decision.

What’s your call? What you picked and why? I would like to listen in the comments.

Create your first real-time AngularJS application

In my previous article I talked about creating real-time PHP application. That was on the server side and I demonstrated a very very basic client to connect with it. Let’s take that to next step and create a Javascript client with AngularJS.

Code

angular-client.html


<html>
 <head>
 css/bootstrap.min.css" rel="stylesheet">
 
 
 
 <script src="angular-client.js"></script>
<style>
 body { margin-top: 10px; }
 input.message { height: 30px; }
 </style>
 </head>
 AppCtrl">
 <form class="form-inline">
 <button ng-click="connect()" class="btn">Connect</button>
 <input type="text" ng-model="text" placeholder="input message to send" class="message"></input>
 <button ng-click="send()" class="btn">send</button>
 </form>
 
 <table class="table table-striped">
 <tr ng-repeat="message in messages">
 <td>{{message}}</td>
 </tr
 </table>
 </body>
</html>

angular-client.js


var app = angular.module('app', []);
app.factory('ChatService', function() {
 var service = {};
 
 service.connect = function() {
 if(service.ws) { return; }
 
 var ws = new WebSocket("ws://localhost:8080");
 
 ws.onopen = function() {
 service.callback("Succeeded to open a connection");
 };
 
 ws.onerror = function() {
 service.callback("Failed to open a connection");
 }
 
 ws.onmessage = function(message) {
 service.callback(message.data);
 };
 
 service.ws = ws;
 }
 
 service.send = function(message) {
 service.ws.send(message);
 }
 
 service.subscribe = function(callback) {
 service.callback = callback;
 }
 
 return service;
});
 
 
app.controller('AppCtrl', ['$scope', 'ChatService', function($scope, ChatService) {
 $scope.messages = [];
 
 ChatService.subscribe(function(message) {
 $scope.messages.push(message);
 $scope.$apply();
 });
 
 $scope.connect = function() {
 ChatService.connect();
 }
 
 $scope.send = function() {
 ChatService.send($scope.text);
 $scope.text = "";
 }
}]);


Details

It is pretty straightforward. We created an Angular Service and consumed that in our Angular controller. The only purpose of Angular service is handling communication. It will hand over the message to the subscriber in our case Angular controller and controller can do anything with that message. Here since we demonstrated the chat application so controller displays that message received.

That’s it! so simple.

Note: Both HTML and Javascript files are also available on Gist.

Code was referenced from here.

Global Variables in AngularJS

I’ve followed the angularjs tutorial and I noticed that I wasn’t able to have global variables.
Turns out to be actually simple but Angular doesn’t mention it.
You will need to edit your app module (app.js )

var app = angular.module('appName',);
//Add this to have access to a global variable
app.run(function ($rootScope) {
    $rootScope.globalVariable = 'Hi, global variabel'; //global variable
});

Now if you want to use it from your controller

function appNameCtrl($scope, $rootScope){
    $rootScope.globalVariable = 'Modji';
}

In your view

My name is {{globalVariable}}

If you are using any services like $http in your controller then you have to pass $rootScope as service along with $http.

app.controller('appNameCtrl', ['$http', '$rootScope', function ($scope, $rootScope){
    $rootScope.globalVariable = 'Modji';

}]);


To see the example visit my Plunker at http://plnkr.co/edit/JyIfkT1AxiCU2xx4WjJK?p=preview

This post is edited and was originally published at Coding Insight.