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.

Different color for each menu item in WordPress

In a recent project, I got a requirement that each menu item should be highlighted in a different color when visited. The menu items and their required active colors were:

  • Home – Green
  • Portfolio – Blue
  • Team – Yellow
  • Contact – Red

These colors were to be applied only when that page is being visited otherwise color of the menu item should be the default black color.

So, if a user is visiting the home page then the menu item should something like this

home_menu.png

And if the user is visiting the Portfolio page then the menu should be something like this

portoflio_menu.png

Considering that this was a WordPress theme project where we were using Understrap as a base theme which is based on Twitter Bootstrap. So, when user visits, for example, a home page WordPress will attach a .active CSS class to it. Taking advantage of that we added different classes for each menu item and then used the following rule to make menu item colors different:

.navbar-nav > .home.active > a {
    color: green!important;
}
.navbar-nav > .portfolio.active > a {
    color: blue!important;
}
.navbar-nav > .team.active > a {
    color: yellow!important;
}
.navbar-nav > .connect.active > a {
    color: red!important;
}

CSS Class Chaining Method

We utilized the class chaining method here. If you note that .home.active classes are chained together without space and which means it will select an element with both these classes.
That did the trick and all menu items were in a different color.

Rollover image – Change image on hover/mouse over

Often when designing websites static or dynamic, PHP or ASP.Net, Laravel or WordPress, you have to design in a way that if the user hovers an image it gets changed and an alternate image is displayed. This can be easily achieved via simple HTML events. Here is the trick:

<img src="FIRST IMAGE URL GOES HERE"
onmouseover="this.src='SECOND IMAGE URL GOES HERE'"
onmouseout="this.src='FIRST IMAGE URL GOES HERE - AGAIN'" />

It is simple as that.

Click here to read more tips.

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”.

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.

Give a new look to your osCommerce store

That’s how the osCommerce theme looks by default in version 2.3.1

the default redmond theme

What we want to do is, to change the light blue of the buttons, infobox headings and breadcrumb line (thats the line just under the header). In other words, we’re going to change the color theme of the store. The whole process won’t take more than some minutes, let’s start

1. Choose a theme from “themeroller”

Just go to the jquery-ui page and pick a new theme from themeroller. You can take one of the ready themes, you can make adjustements to an existing one or even create your own theme.

The jquery ui themeroller

There are really many themes to choose from. After you are done click “download”. You’ll be transfered to another screen.

Download your new theme

Leave all components checked and click “download” again. You’ll get a complete copy of jquery ui to your computer. Unzip the file and open the folder.  The folder will look like this

The themeroller folder

We don’t need all of it’s contents, because jquery ui is already installed in osCommerce. The part we need is marked with orange in the above image. It’s named by the name of the theme we choose. Here we need to do one change, to rename the file jquery-ui-1.8.6.custom.css to jquery-ui-1.8.6.css

2. upload the theme to your server

Use your favorite FTP program to upload the folder “ui-darkness” (the folder name depends on the theme you downloaded from themeroller) to following location

[catalog]/ext/jquery/ui/

3. activate the new theme

Last step is to “tell” to our store to use the new theme. To do this we need to go to file [catalog]/includes/template_top.php and change the path to the theme. This path is set in following line

29
<link rel="stylesheet" type="text/css" href="ext/jquery/ui/redmond/jquery-ui-1.8.6.css" />

This we change to

29
<link rel="stylesheet" type="text/css" href="ext/jquery/ui/ui-darkness/jquery-ui-1.8.6.css" />

Only thing we do is, to change the path to go to folder “ui-darkness” instead of “redmond” which is the default theme. You need ofcourse to set the right name, according to the theme you’re going to use

Lets see how our store looks now

jQuery Image SlideShow

So to get started you’re going to need jQuery and the Orbit plugin (make sure jQuery is attached first).

<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.orbit.min.js" type="text/javascript"></script>

Now we can quickly hookup the CSS we need:

<link rel="stylesheet" href="css/orbit.css">

And finally, let’s dig into the markup.

Now, just a couple notes before moving on…

  • First, Orbit will dynamically determine the height and width of your set of images and scale accordingly, but make sure all your images are the same size or the larger images will peek out on the sides.
  • Secondly, you’ll notice that the “id” of the parent div is “featured”, but it doesn’t have to be. When you call the Orbit plugin, you set your own selector and the magical “orbit” class gets applied.

All we need to do now is activate the Orbit plugin.

<script type="text/javascript">
     $(window).load(function() {
         $('#featured').orbit();
     });
</script>

And there you have it. Orbit, implemented and ready to rock with all the default settings.

Article resource: http://www.htmldrive.net/items/show/928/Countdown-jQuery-Slick-Image-Slider-Plugin