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>
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.
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.
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:
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:
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.
Read every detail carefully. Clarify inputs, outputs, constraints, and edge cases before writing a single line of code. Ask yourself:
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.
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)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.
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.
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.
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.
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.
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, 2019This 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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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