Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Javascript Callback Function

A callback function is a function passed into another function as an argument, which is then invoked inside that function at a later time. JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors. To prevent this, you can create a callback function.

Callback Function Synchronous

<h4 class="text-center">Callback function synchronous</h4>
<div class="row">
    <div class="col-3">
        <button onclick="checkin()" type="button" class="btn btn-outline-primary">Check In Synchronous</button>
    </div>
    <div class="col-6">
        <div class="text-center" id="welcomeNote"></div>
    </div>
</div>


<!-- Callback function synchronous -->
<script>
function checkin(){
    console.log("checkin...");
    checkUser(greeting);
    console.log("checkin done!");
}
function greeting(name) {
    console.log("greeting...");
    alert('Hey ' + name);
    document.getElementById("welcomeNote").innerHTML = "Welcome "+name+"!";
    console.log("greeting done!");
}

function checkUser(callback) {
    console.log("checkUser...");
    var name = prompt('What is your name?');
    callback(name);
    console.log("checkUser done!");
}
</script>

 

Callback functions are often used to continue code execution after an asynchronous operation has completed. A good example is the callback functions executed inside a .then() block chained onto the end of a promise after that promise completes or rejects. This structure is used in many modern web APIs, such as fetch().

Callback Function Asynchronous

<h4 class="text-center">Callback function asynchronous</h4>
<div class="row">
    <div class="col-3">
        <button onclick="checkApi()" type="button" class="btn btn-outline-primary">Check In Asynchronous</button>
    </div>
    <div class="col-6">
        <div class="text-center" id="apiNote"></div>
    </div>
</div>

<!-- Callback function asynchronous -->
<script>
function checkApi(){
    console.log("checkApi...");
    getRandomNumber(showApiResult);
    console.log("checkApi done!");
}

function getRandomNumber(showApiResult){
    let apiEndpoint = "https://www.random.org/integers/?num=1&min=1&max=6&col=1&base=10&format=plain&rnd=new";
    $.get(apiEndpoint, function(data, status){
        console.log(status);
        console.log(data);
        showApiResult(data);
    });
}

function showApiResult(randomNumber){
    document.getElementById("apiNote").innerHTML = "Here is your random number "+randomNumber+"!";
}
</script>

Callback Function jQuery

<h4 class="text-center">Callback function with jQuery</h4>
<div class="row">
    <div class="col-3">
        <button onclick="checkjQuery()" type="button" class="btn btn-outline-primary">Check In jQuery</button>
    </div>
    <div class="col-6">
        <div class="text-center" id="jqueryNote"></div>
    </div>
</div>
<!-- Callback function asynchronous with jquery -->
<script>
$(document).ready(function(){
    /**
    Note: use this to reference variables and functions
    */
    this.name = "Folau";

    this.checkjQuery = function(){
        console.log("checkjQuery...");
        this.getJQueryRandomNumber(this.showJQueryApiResult);
        console.log("checkjQuery done!");
    }

    this.getJQueryRandomNumber = function(showJQueryApiResult){
        console.log("getJQueryRandomNumber...");
        // reference this to outside function.
        var self = this;
        let apiEndpoint = "https://www.random.org/integers/?num=1&min=1&max=6&col=1&base=10&format=plain&rnd=new";
        $.get(apiEndpoint, function(data, status){
            console.log(status);
            console.log(data);
            self.showJQueryApiResult(data);
        });
        console.log("getJQueryRandomNumber done!");
    }

    this.showJQueryApiResult = function(randomNumber){
        console.log("showJQueryApiResult...");
        document.getElementById("jqueryNote").innerHTML = "Here is your random number "+randomNumber+"!";
        console.log("showJQueryApiResult done!");
    }

    // this function does not work as it does not use this
    function showJQueryApiResult(randomNumber){
        console.log("showJQueryApiResult...");
        document.getElementById("jqueryNote").innerHTML = "Here is your random number "+randomNumber+"!";
        console.log("showJQueryApiResult done!");
    }

});
</script>

Source code on Github

October 8, 2019

Javascript Introduction

Javascript was created to make web pages responsive. With Javascript you’ll be able to create reponsive web pages, games, animated 2D and 3D graphics, comprehensive database-driven apps, and much more. Today, JavaScript can execute not only in the browser, but also on the server, or actually on any device that has a special program called  the JavaScript engine. The browser has an embedded engine sometimes called a “JavaScript virtual machine”.

JavaScript virtual machine is complicated. But the basics are easy.

  1. The engine (embedded if it’s a browser) reads (“parses”) the script.
  2. Then it converts (“compiles”) the script to the machine language.
  3. And then the machine code runs, pretty fast.

The engine applies optimizations at each step of the process. It even watches the compiled script as it runs, analyzes the data that flows through it, and further optimizes the machine code based on that knowledge.

There are at least three great things about JavaScript which is the only browser technology that combines these three things.

  • Full integration with HTML/CSS.
  • Simple things are done simply.
  • Support by all major browsers and enabled by default.

 What can JavaScript do in browser? 

Modern JavaScript is a “safe” programming language. It does not provide low-level access to memory or CPU, because it was initially created for browsers which do not require it.

JavaScript’s capabilities greatly depend on the environment it’s running in. For instance,  Node.js  supports functions that allow JavaScript to read/write to disk, perform network requests, etc.

In-browser JavaScript can do everything related to webpage manipulation, interaction with the user, and the webserver.

For instance, in-browser JavaScript is able to:

  • Add new HTML to the page, change the existing content, modify styles.
  • React to user actions, run on mouse clicks, pointer movements, key presses.
  • Send requests over the network to remote servers, download and upload files (so-called  AJAX  and  COMET  technologies).
  • Get and set cookies, ask questions to the visitor, show messages.
  • Remember the data on the client-side (“local storage”).

 What can’t JavaScript do in browser? 

JavaScript’s abilities in the browser are limited for the sake of the user’s safety. The aim is to prevent an evil webpage from accessing private information or harming the user’s data.

Examples of such restrictions include:

  • JavaScript on a webpage may not read/write arbitrary files on the hard disk, copy them or execute programs. It has no direct access to OS functions.Modern browsers allow it to work with files, but the access is limited and only provided if the user does certain actions, like “dropping” a file into a browser window or selecting it via an input tag.There are ways to interact with camera/microphone and other devices, but they require a user’s explicit permission. So a JavaScript-enabled page may not sneakily enable a web-camera, observe the surroundings and send the information to the  NSA .
  • Different tabs/windows generally do not know about each other. Sometimes they do; for example when one window uses JavaScript to open the other one. But even in this case, JavaScript from one page may not access the other if they come from different sites (from a different domain, protocol or port).This is called the “Same Origin Policy”. To work around that, both pages must agree for data exchange and contain a special JavaScript code that handles it. We’ll cover that in the tutorial.This limitation is, again, for the user’s safety. A page from http://anysite.com which a user has opened must not be able to access another browser tab with the URL http://gmail.com and steal information from there.
  • JavaScript can easily communicate over the net to the server where the current page came from. But its ability to receive data from other sites/domains is crippled. Though possible, it requires explicit agreement (expressed in HTTP headers) from the remote side. Once again, that’s a safety limitation.
October 8, 2019

How to tackle a problem

Every senior developer follows a structured approach to problem-solving. Whether you are debugging a production issue or building a new feature, these seven steps will help you arrive at a clean, efficient solution every time.

We will walk through each step using a real-world example: find duplicate values in a list.

1. Understand the Problem

Read every detail carefully. Clarify inputs, outputs, constraints, and edge cases before writing a single line of code. Ask yourself:

  • What is the input type and size?
  • What should the output look like?
  • Are there constraints on time or space?

Our example: Given a list of integers, return all values that appear more than once. Input: [1, 3, 5, 3, 7, 5] → Output: [3, 5]. The list can be empty. Duplicates should appear only once in the result.

2. Have Examples of the Problem

Create multiple test cases before you code. Good examples expose edge cases you would otherwise miss.

  • [1, 2, 3][] (no duplicates)
  • [1, 1, 1][1] (all same)
  • [][] (empty input)
  • [4, 4, 5, 5, 6][4, 5] (multiple duplicates)

3. Solve with Brute Force

Get a working solution first. Do not optimize prematurely. A brute-force approach compares every element against every other element. This runs in O(n²) time.

public List<Integer> findDuplicatesBrute(int[] nums) {
    List<Integer> result = new ArrayList<>();
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[i] == nums[j] && !result.contains(nums[i])) {
                result.add(nums[i]);
            }
        }
    }
    return result;
}
def find_duplicates_brute(nums):
    result = []
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] == nums[j] and nums[i] not in result:
                result.append(nums[i])
    return result

It works. It is correct. That is all that matters at this stage.

4. Optimize Your Solution

Now analyze the brute-force approach and look for improvements. The nested loop is the bottleneck. A HashSet lets us track seen elements in O(1) time, reducing overall complexity to O(n).

The trade-off: we use extra memory (a set) to gain speed. This is almost always worth it.

public List<Integer> findDuplicates(int[] nums) {
    Set<Integer> seen = new HashSet<>();
    Set<Integer> duplicates = new HashSet<>();
    for (int num : nums) {
        if (!seen.add(num)) {
            duplicates.add(num);
        }
    }
    return new ArrayList<>(duplicates);
}
def find_duplicates(nums):
    seen = set()
    duplicates = set()
    for num in nums:
        if num in seen:
            duplicates.add(num)
        seen.add(num)
    return list(duplicates)

O(n) time, O(n) space — a significant improvement over the O(n²) brute force.

5. Walk Through Your Solution

Trace through the optimized code with a concrete example before implementing it in production. Using [1, 3, 5, 3, 7, 5]:

  • 1 → not in seen, add to seen. seen={1}
  • 3 → not in seen, add to seen. seen={1,3}
  • 5 → not in seen, add to seen. seen={1,3,5}
  • 3 → already in seen, add to duplicates. duplicates={3}
  • 7 → not in seen, add to seen. seen={1,3,5,7}
  • 5 → already in seen, add to duplicates. duplicates={3,5}

Result: [3, 5]. The logic is correct. We are ready to implement.

6. Implement Your Solution

Write clean, production-ready code. Use clear names, handle edge cases, and keep methods focused on a single responsibility.

import java.util.*;

public class DuplicateFinder {

    public static List<Integer> findDuplicates(List<Integer> nums) {
        if (nums == null || nums.isEmpty()) {
            return Collections.emptyList();
        }
        Set<Integer> seen = new HashSet<>();
        Set<Integer> duplicates = new LinkedHashSet<>();
        for (int num : nums) {
            if (!seen.add(num)) {
                duplicates.add(num);
            }
        }
        return new ArrayList<>(duplicates);
    }
}
def find_duplicates(nums: list[int]) -> list[int]:
    if not nums:
        return []
    seen = set()
    duplicates = []
    for num in nums:
        if num in seen and num not in duplicates:
            duplicates.append(num)
        seen.add(num)
    return duplicates

Notice the use of LinkedHashSet in Java and an ordered list in Python to preserve insertion order of duplicates — a detail that shows attention to quality.

7. Test Your Solution

Write tests that cover normal cases, edge cases, and boundary conditions. Do not skip this step.

@Test
void testFindDuplicates() {
    assertEquals(List.of(3, 5),
        DuplicateFinder.findDuplicates(List.of(1, 3, 5, 3, 7, 5)));
    assertEquals(List.of(),
        DuplicateFinder.findDuplicates(List.of(1, 2, 3)));
    assertEquals(List.of(1),
        DuplicateFinder.findDuplicates(List.of(1, 1, 1)));
    assertEquals(List.of(),
        DuplicateFinder.findDuplicates(List.of()));
}
def test_find_duplicates():
    assert find_duplicates([1, 3, 5, 3, 7, 5]) == [3, 5]
    assert find_duplicates([1, 2, 3]) == []
    assert find_duplicates([1, 1, 1]) == [1]
    assert find_duplicates([]) == []

Cover all the test levels: unit tests for individual methods, integration tests for component interactions, and functional tests for end-to-end flows. Small, focused test cases run faster and catch bugs just as effectively as large ones.

Key Takeaway

Solving problems is a skill you build through repetition. Follow these seven steps consistently and you will write cleaner code, catch more edge cases, and deliver faster. The pattern is always the same: understand, example, brute force, optimize, trace, implement, test.

October 6, 2019

Phone Interviews

October 4, 2019

Questions to ask recruiter

Question 1: What is the job description?

This question summarizes aspects like the duties, skills required for the job, who you would be accountable to and are accountable to you. It gives you a brief idea about the work associated with the position.

Question 2: What are the prerequisite skills or educational qualifications for the position?

Any corporate job will demand a specific set of skills. To be capable and perform the duties without any errors, you need to possess the expertise to handle the role. The above question lets you learn about the required skills along with other qualifications needed for position.

Question 3: How long has the position been open?

This question lets you know about two things: demand for the job and the strictness of candidate assessment. If the job has been open over a month, there is a high probability of people not being interested in the job. Alternatively, it could also mean that the candidates are failing to make through the interviews due to strict interview conditions. Then again, you might get to know that the job has been open for only a week. In that case, you do not get any idea about the competition for the job or the interviewer’s meticulousness.

Question 4: Is the position in question a newly created one or vacancy due to changes in the workforce?

Sometimes companies have a change in management which might also result in the creation of some new roles and designations. Or, there might be a change in ideas and priorities which creates new job titles. Then again, an open position could be a consequence of a change in the workforce (like promotion, retirement, or firing [in extreme cases]). You are not looking for a right or wrong answer to this question. It only lets you understand the circumstances which led to the availability of the job.

Question 5: What are the reasons that other candidates haven’t been selected?

There are preliminary conditions set for a specific job; meeting them makes a candidate eligible for the position after which the interview process follows. Asking the recruiter about the cause of non-selection of other candidates might reveal potential shortcomings you need to careful of. It could be related to a skill, experience or any other aspect. Being aware of the things gives you forewarning – providing time to work out the inadequacies to perform better in the interview.

Question 6: What are some of the challenges and opportunities associated with the position?

A job comes with associated duties, tasks that you need to do and are ultimately responsible for. Knowing the challenges and opportunities that you will encounter in the position gives you time to prepare yourself mentally. It won’t feel like a bad surprise when you face the issue later down the road. It will also help you evaluate your career progression, letting you know if the job matches your intentions and ambitions.

Question 7: I want a job that provides me a chance for career advancement. What’s the scope of growth and benefits of working with this position and company?

People want gradual progress their careers, be it in the form of salary increases, increase in responsibilities or job title. Through this question you get to know the perks of working in the position.

Question 8: How much does a job like this pay on average?

Inquiring about pay gives you a salary number that the company is willing to compensate for the position. Not only do you get to know how much you might get paid, but it also lets you assess the value. Value relating the job responsibilities. This information also allows you to consider and compare other offers (if any).P

Questions To Ask A Recruiter Related To The Company

When working in any job, you will be a small part of the big system, i.e., the company. All organizations are different, and so are their principles. You should be appropriately informed about the work ethics and culture of the company. Ensure that it matches your preferences before deciding to join them.

The following questions intend to explore those topics.

Question 1: What is the interview process like with this company?

Every company has their own rules when it comes to conducting interviews and hiring employees. Asking the recruiter provides insight into the process. Whether there is a preliminary written test, whether there is a phone interview before the actual meeting and more. Knowing these small details allows you to prepare accordingly to perform better.

Question 2: Will I be subject to any form of training?

The training, in this context, could be related to the period before being assigned any work, or during the working period to improve your skills and help in career development. Some companies actively engage their employees in training programs while others don’t. This information will be vital to shaping your career growth plan.

Question 3: What will be the criteria for evaluating my performance as an employee?

Companies don’t just hire people and forget about them. They tend to keep track of their work and performance. Your performance matches closely to their expectations. If not, you risk getting demoted (or in worse cases, fired from the job). There are usually parameters that help employers evaluate their employees’ performance. Inquiring about them in advance will let you know the factors you’ll be judged.

Question 4: What is the culture of the company and the workplace?

Every company has a system based on work ethics and culture which varies from one organization to the other. Google does away with formal wear while the company in question might be mandating that you dress formally. Formal wear is just one aspect. Knowing the principles that the company relies on and how it relates to your future work will help you make an informed decision.

Question 5: What can you tell me about the hiring manager?

The hiring manager is usually the one you will be reporting to before joining the company. It might be that the recruiter and the hiring manager are close acquaintances. Alternatively, that might not be the case. This question is to assess the relationship between the recruiter and the hiring manager while also letting you know more about the manager. This additional information (like their technical background, history with the company) will help you communicate with them during the interview process.

Question 6: What’s your opinion on this company?

Asking this question will sum up the recruiter’s impression of the company. They might provide useful insight that could help you make a decision.

October 4, 2019