TechSchool
Home / Interview questions / JavaScript

JavaScript interview questions

44 questions about JavaScript with short answers and code. Each answer links to a full lesson on this site. Free, with no signup and no ads.

Basics

1. How do you find the position of an item in an array?

Use the indexOf method. It returns the first position of the item. It returns -1 when the item is not in the array.

var fruits = ["Banana", "Orange", "Apple"];
var a = fruits.indexOf("Apple");
console.log(a);

Full lesson: Jsref indexof array

2. How do you turn an array into a text string?

Use the toString method. It returns all values in one string. A comma separates each value.

var fruits = ["Banana", "Orange", "Apple"];
console.log(fruits.toString());

Full lesson: Jsref tostring array

3. How do you join array items with your own separator?

Use the join method. You give the separator as an argument. The method returns one string.

var fruits = ["Banana", "Orange", "Apple"];
console.log(fruits.join(" - "));

Full lesson: Jsref join

4. How do you remove the first item from an array?

Use the shift method. It removes the first item and returns it. The array becomes shorter.

var fruits = ["Banana", "Orange", "Apple"];
var first = fruits.shift();
console.log(first);

Full lesson: Jsref shift

5. How do you check if a value is an array?

Use the isArray method. It returns true for an array. It returns false for other values.

console.log(Array.isArray([1, 2, 3]));
console.log(Array.isArray("abc"));

Full lesson: Jsref isarray

6. How do you run one block of code or another?

Use an if statement with an else block. The if block runs when the test is true. The else block runs when the test is false.

var age = 20;
if (age > 18) {
  console.log("Adult");
} else {
  console.log("Child");
}

Full lesson: Jsref if

7. How do you find the first element that matches a CSS selector?

Use the querySelector method. It returns the first match only. It returns null when nothing matches.

var x = document.querySelector(".demo");
x.innerHTML = "Hello World!";

Full lesson: Met document queryselector

8. How do you find all elements that match a CSS selector?

Use the querySelectorAll method. It returns a list of all matches. You can loop over the list.

var items = document.querySelectorAll("p.note");
console.log(items.length);

Full lesson: Met document queryselectorall

9. How do you add or remove a CSS class on an element?

Use the classList property. It gives you add and remove methods. The property is read-only, but the methods change the classes.

var el = document.getElementById("myDIV");
el.classList.add("mystyle");
el.classList.remove("mystyle");

Full lesson: Prop element classlist

10. How do you read the selected option in a drop-down list?

Use the selectedIndex property. It returns the index number of the selected option. If many options are selected, it returns the first one.

var sel = document.getElementById("mySelect");
console.log(sel.selectedIndex);

Full lesson: Prop select selectedindex

11. How do you find the last position of an item in an array?

Use the lastIndexOf method. It searches from the end to the start. It returns -1 when the item is not found.

var fruits = ["Banana", "Orange", "Apple"];
console.log(fruits.lastIndexOf("Apple"));

Full lesson: Jsref lastindexof array

12. How do you find the last element that passes a test?

Use the findLastIndex method. It runs a test function on each element. It returns the index of the last match, or -1.

const ages = [3, 10, 18, 20];
const i = ages.findLastIndex(function (age) {
  return age > 18;
});
console.log(i);

Full lesson: Jsref findlastindex array

13. How do you add a new method to all arrays?

Use the prototype property. You attach the method to Array.prototype. Then every array can call the method.

Array.prototype.myUcase = function () {
  return this.map(function (v) { return v.toUpperCase(); });
};
console.log(["a", "b"].myUcase());

Full lesson: Jsref prototype array

14. Why does indexOf return -1 when the item is missing?

The method returns -1 to show that no match exists. A common mistake is to treat -1 as a found position. Always test the result against -1.

var fruits = ["Banana", "Orange"];
if (fruits.indexOf("Apple") === -1) {
  console.log("Not found");
}

Full lesson: Jsref indexof

Intermediate

15. Why is the rowIndex value wrong after you add rows?

The rowIndex property counts rows in the whole table. It changes when you add or remove rows. A common mistake is to store the value and use it later. Read the property again when you need it.

var table = document.getElementById("myTable");
var row = table.rows[0];
console.log(row.rowIndex);

Full lesson: Prop tablerow rowindex

16. What does the cellIndex property return for a table cell?

The cellIndex property returns the position of a cell in the row's cell collection. The first cell has index 0.

var cell = document.querySelector('td');
console.log(cell.cellIndex);

Full lesson: Prop tabledata cellindex

17. How do you get the index of a selected option in a drop-down list?

The selectedIndex property returns the index number of the selected option. If multiple options are selected, it returns the index of the first selected option.

var select = document.getElementById('mySelect');
console.log(select.selectedIndex);

Full lesson: Prop select selectedindex

18. What does the type event property return?

The type event property returns the name of the event that occurred. The name matches the event handler without the 'on' prefix, such as 'click' or 'submit'.

function showType(event) {
  alert(event.type);
}
document.body.onclick = showType;

Full lesson: Event type

19. How do you find the first element with a specific ID using querySelector?

The document.querySelector method returns the first element that matches the CSS selector. Use '#id' to select by ID.

var element = document.querySelector('#demo');
console.log(element);

Full lesson: Met document queryselector

20. How do you get the index of a cell in a table header row?

The cellIndex property of a table header cell returns its position in the row's cell collection. The first header cell has index 0.

var th = document.querySelector('th');
console.log(th.cellIndex);

Full lesson: Prop tableheader cellindex

21. What does the sectionRowIndex property return for a table row?

The sectionRowIndex property returns the position of a row in the TBODY, THEAD, or TFOOT rows collection. The first row in that section has index 0.

var row = document.querySelector('tr');
console.log(row.sectionRowIndex);

Full lesson: Prop tablerow sectionrowindex

22. How do you set the list style image for a list item?

The listStyleImage property sets or returns the image used as a list-item marker. Use 'none' to show no image.

document.getElementById('myList').style.listStyleImage = 'url(bullet.png)';

Full lesson: Prop style liststyleimage

23. How do you convert an array to a string with local formatting?

The toLocaleString method converts array elements to a string using local formatting. Numbers and dates use the locale you specify.

const prices = [1234.56, 7890.12];
console.log(prices.toLocaleString('en-US'));

Full lesson: Jsref array tolocalestring

24. How do you convert a value to a string using the String function?

The String function converts a value to a string. It returns the same result as the toString method for most values.

var num = 123;
var str = String(num);
console.log(typeof str);

Full lesson: Jsref string

25. How do you create a new image element with JavaScript?

The Image constructor creates a new image element. You can set the src property to load an image.

var img = new Image();
img.src = 'photo.jpg';
document.body.appendChild(img);

Full lesson: Dom obj image

26. What does the type property return for a select element?

The type property returns the type of form control. For a select element, it returns 'select-one' or 'select-multiple'.

var select = document.getElementById('mySelect');
console.log(select.type);

Full lesson: Prop select type

27. How do you set the type of an ordered list?

The type property of an ol element sets the numbering style. Use '1' for numbers, 'A' for uppercase letters, 'a' for lowercase letters, 'I' for uppercase Roman numerals, or 'i' for lowercase Roman numerals.

document.getElementById('myList').type = 'A';

Full lesson: Prop ol type

28. Why does querySelector return null sometimes?

The querySelector method returns null when no element matches the CSS selector. Check that the selector is correct and that the element exists in the document.

var el = document.querySelector('.missing');
console.log(el); // null

Full lesson: Met element queryselector

29. Why does lastIndexOf return -1 for a missing item?

The lastIndexOf method returns -1 when the specified value is not found in the array. This is a common source of errors if you do not check the result.

var arr = [1, 2, 3];
console.log(arr.lastIndexOf(4)); // -1

Full lesson: Javascript lastindexof array

Common mistakes

30. Why does the cellIndex property have no default value?

The cellIndex property has no default value because it depends on the cell's position in the row. If the cell is not in a row, the property can return -1 or undefined.

var cell = document.createElement('td');
console.log(cell.cellIndex); // -1

Full lesson: Prop tabledata cellindex

31. How do you find the position of a substring in a string?

Use the indexOf method on the string. It returns the first position of the substring. If the substring is not found, it returns -1.

var str = "Hello world";
var pos = str.indexOf("world");
// pos is 6

Full lesson: Jsref indexof

32. How do you change the marker type of an ordered list?

Set the type property of the ol element. The value can be "1", "a", "A", "i", or "I". This changes the list markers to numbers, letters, or Roman numerals.

document.getElementById("myList").type = "a";

Full lesson: Prop ol type

33. How do you run code when an image fails to load?

Use the onerror event attribute on the img element. The browser runs the code when the image cannot load. You can also assign a function to the onerror property.

<img src="missing.jpg" onerror="this.alt='Image not found'">

Full lesson: Event onerror

34. How do you get the type of an event that occurred?

Use the type property of the event object. It returns the name of the event, such as "click" or "load". The name matches the event handler without the "on" prefix.

function showType(event) {
  alert(event.type);
}

Full lesson: Event type

35. How do you set the list style type of a list item?

Use the listStyleType property of the style object. Set it to a value like "square" or "upper-roman". This changes the marker for the list item.

document.getElementById("myItem").style.listStyleType = "square";

Full lesson: Prop style liststyletype

36. How do you get the number of rows in a table?

Use the rows collection of the table object. The length property of the collection gives the number of rows. This includes rows in thead, tbody, and tfoot.

var table = document.getElementById("myTable");
var count = table.rows.length;

Full lesson: Dom obj table

37. How do you find the index of a table row within its section?

Use the sectionRowIndex property of the tr element. It returns the position of the row in its parent section (thead, tbody, or tfoot). The index starts at 0.

var row = document.getElementById("myRow");
alert(row.sectionRowIndex);

Full lesson: Prop tablerow sectionrowindex

38. How do you add a new method to all strings?

Add the method to the prototype property of the String constructor. All strings then have the method. Use a function that returns a new value.

String.prototype.firstChar = function() {
  return this.charAt(0);
};

Full lesson: Jsref prototype string

39. How do you get the type of a file upload input?

Use the type property of the file upload element. It returns the value of the type attribute, usually "file". This property is read-only.

var input = document.getElementById("myFile");
alert(input.type); // "file"

Full lesson: Prop fileupload type

40. Why does a string method not change the original string?

Strings in JavaScript are immutable. Methods like toUpperCase return a new string. They do not change the original string.

var s = "hello";
var t = s.toUpperCase();
// s is still "hello", t is "HELLO"

Full lesson: Jsref string

41. Why does the type property of a select element return "select-one"?

The type property returns "select-one" for a drop-down list that allows one selection. It returns "select-multiple" if the multiple attribute is present. This helps you check the selection mode.

var sel = document.getElementById("mySelect");
if (sel.type === "select-one") {
  // single selection
}

Full lesson: Prop select type

42. Why does the indexOf method return -1 for a missing substring?

The indexOf method returns -1 when the substring is not found. This is a common convention in JavaScript. Always check for -1 to detect a missing value.

var str = "Hello";
if (str.indexOf("world") === -1) {
  // not found
}

Full lesson: Jsref indexof

43. Why does the sectionRowIndex property return -1 for a row outside a section?

The sectionRowIndex property returns -1 if the row is not inside a thead, tbody, or tfoot. Make sure the row is inside a table section. Browsers automatically add a tbody for rows directly in a table.

var row = document.createElement("tr");
alert(row.sectionRowIndex); // -1

Full lesson: Prop tablerow sectionrowindex

44. Why does the onerror event not fire for a missing image if you set it after the image loads?

The onerror event fires only when the error occurs. If you set the handler after the image fails to load, the event has already passed. Set the handler before you set the src attribute.

var img = new Image();
img.onerror = function() { alert("Failed"); };
img.src = "missing.jpg";

Full lesson: Event onerror

More on TechSchool
See the JavaScript cheat sheet Python TypeScript HTML CSS React Vue 3 Node.js Java PHP C C++ C# Go SQL MongoDB Redis Linux Git Docker Data Structures