JavaScript is one of the trending languages in the market. If you are planning to continue your career as a web developer, then JavaScript should be on your fingertips. Since the different versions releases, there are a lot of methods and functions available in JavaScript. So what are the questions that can be asked in the interview? Well, in this article, we try to cover the most asked javascript interview questions.
Table of Contents
Q1. What is JavaScript? Tell us briefly.
Answer: JavaScript is a client-side and server-side scripting language, but it is mainly used as client-side validation. It is also an object-based scripting language. It one of the fastest-growing languages and is primarily used for making web pages dynamic.
Q2. How many data types do we have in JavaScript? And what is their use?
Answer: There are seven data types available in JavaScript:
- String: It is used to store a single character, a word, or sentence or alphanumeric values.
- Boolean: It is used to represent true or false.
- Null: It is used to show nothing or empty.
- Object: Use to store a collection of data.
- Number: It is capable of storing integer as well as floating point-numbers
- Undefined: If a variable is declared, but its value is not defined, it represents an undefined data type.
- Symbol: It is used to create unique identifiers for an object.
Q3. List some of the features of JavaScript.
- It is a lightweight and interpreted programming language.
- It works very well with the network-centric application.
- It is an open and cross-platform language.
- It is complementary to Java and HTML.
- Useful for easy validation of the user’s input.
Q4. Is JavaScript a loosely typed or a strongly types programming language?
Answer: JavaScript is a loosely types language. It means that you don’t need to specify what types of information you are going to store in a variable.
JavaScript does that automatically for you according to the data which you save. Unlike other languages like Java and C in which you have to specify the variable’s type.
Q5. What is the difference between undefined and undeclared?
Undeclared: It occurs when we try to access a variable that has neither declared nor initialized.
Undefined: It occurs when a variable has been defined, but it hasn’t assigned any value.
Q6: What is the difference between “==” and “===”?
Answer: “==” is used for comparing two variables. It returns true if both variables are the same, even if their type is different, whereas “===” is also used to compare variables. But, it strictly checks the data types of the variables.
console.log(1 == true) //returns true
console.log(1 === true) //returns false
Q7. How many types of functions do we have in JavaScript?
Named function: Those functions which we define with a name are called named functions. They are useful when we want to call them several times by passing different values to it.
function add(a, b) {
var sum = a + b
console.log("Addition is: " + sum)
}
add(2,7)
Anonymous functions: A function that is declared without a name is called an anonymous function.
var add = function (a, b) {
var sum = a + b
console.log("Addition is: " + sum)
}
add(5, 8)
Immediately invoked function: these functions execute immediately as soon as the browser encounters them.
function(a, b) {
var sum = a + b
console.log("Addition is: " + sum)
}(3,7))
Q8. Is JavaScript a case sensitive language?
Answer: Yes, JavaScript is case sensitive. It means that all the keywords and variable’s names should be written carefully. For example, a variable “str” is not the same as “Str”.
Q9. What is the difference between undefined value and null value?
Answer: Undefined is a value that is not defined and only declared.
Null is a value that is explicitly specified by the “null” keyword is known as a null value.
Q10. What will be the output of 7 + 9 + “3”?
Answer: The answer will be 163. 7 + 9 is 16, then the 3 will be concatenated as a string with 16, so it becomes 163.
Q11. What will be the output of “7” + 9 + 3?
Answer: 793, because after the string, all the + operator will be treated as a concatenation operator, not a binary addition operator.
Q12. What are escape characters?
Answer: Escape characters are used when you want to insert any special symbol like a quotation mark, backslash, etc. We use \n for a new line, \“ for a double quote,\’ for a single quote, and \\ for backslash.
Q13. What are the different popups available in JavaScript?
Alert: It is usually used to display a message with the “OK” button.
Prompt: It enables you to take input from the user with the “OK” and “Cancel” button.
Confirm: It enables you to ask user permission to whether a certain process should continue or not. It also has two buttons “OK” and “Cancel”. It returns true if a user press OK else return false.
Q14. What is meant by scope in JavaScript?
Answer: Scope means the accessibility of variables inside your code. JavaScript variable has two types of scope, Local and global.
Local variable: A local variable will only be accessible within its function scope. It means a variable that is declared inside a function cannot be accessible outside the function.
Global variable: A global variable has global scope. It means that it can be accessed everywhere inside JavaScript code.
Q15. What is a closure?
Answer: A closure is a feature in JavaScript in which an inner function has access to its outer function’s variables. They have access to their variables, their outer function’s variables, and the global variables.
Q16. How to check the variable type?
Answer: The typeof operator returns the types of any variable. It returns the data types of its operand in the form of string.
console.log(typeof(241)) //return “number”
console.log(typeof(“Hello”)) //return “string”
console.log(typeof(true)) //return “Boolean”
console.log(typeof(str)) //return “undefined”
Q17. Difference between let and var?
Answer: Both let and var are used for declaring variables in JavaScript. But the most important difference between both of them is let is function scoped and var is blocked scope.
for(i = 1; i <= 10; i++) {
let table = 5
var msg = "Table completed"
console.log(table + " * " + i + " = " + i*table)
}
console.log(msg)
console.log(table) //Uncaught ReferenceError: table is not defined
Q18. What is the difference between shift() and pop() method?
Answer: Both are used to remove the element from the array and alter the original array. The difference is that the shift() method removes the element from the start of array and indexes down the other elements of the array. Whereas the pop() method removes an item from the last of an array.
Q19. What is the method to write functions concisely in JavaScript?
Answer: Arrow functions, also known as Fat arrow functions, are used to write a function compactly. This feature was introduced in ES6. It reduces a lot of extra code and stuff. It is a better choice when we use it with callbacks, promises, awaits, and closures.
This is the traditional way of writing a function.
const square = function(num) {
return num * num
}
console.log(square(4))
You can write the above function in a single line with the help of an arrow function.
const square = num => num * num
console.log(square(4))
Q20. What is the concept of the Destructuring assignment?
Answer: It is a feature that was introduced in ES6. It enables us to unpack values from an array, an object into separate variables.
var arr = ["Destructuring", "introduced", "in", "ES6"]
var [feature,,,when] = arr
console.log(feature) //Destructuring
console.log(when) //ES6
Q21. What is spread operator?
Answer: Spread operator is a new addition to the set of operators in JavaScript ES6. It is used for copying an array into another, concatenating two arrays etc.
//Concatenate two arrays
var new_js = ["Maps", "functions" , "filters" , "generators" , "loops"]
var old_js = ["functions" , "var" , "loops" , "this"]
var js = [...new_js, ...old_js]
console.log(js)
//Adding elements
var new_js = ["Maps", "functions" , "filters" , "generators" , "loops"]
var js = ["functions" , "var" , "loops" , "this", ...new_js]
console.log(js)
Q22. What is the difference between sets and array?
Answer: Both array and sets are used to store several values or items in a single variable. The main difference between them is array can contain duplicate values, whereas sets cannot have identical values.
Q23. How to insert one or more element anywhere in an array?
Answer: We can use the splice() method. Like this.
var apples = ["Red Delicious", "Gala", "Jonagold"]
apples.splice(2, 0, "Fuji", "McIntosh")
console.log(apples)
This will output:
[“Red Delicious”, “Gala”, “Fuji”, “McIntosh”, “Jonagold”]
Q24. Differentiate between for…of and for…in loop.
Answer: These loops give us a clean and compact way to iterate through iterables and enumerable. The for-in loop returns a list of keys if iterates on an object, whereas for…of returns a list of values.
var evenNo = [2, 4, 6, 8, 10]
for(const i of evenNo) {
console.log(i) //2, 4, 6, 8, 10
}
for(const i in evenNo) {
console.log(i) //0, 1, 2, 3, 4
}
Q25. What is the term hoisting means in JavaScript?
Answer: Hoisting is JavaScript default behavior of moving all the variable and function declaration at the top. It means that no matter where the variables and functions are declared, they have to move at the top at the compilation time.
Q26. Briefly tell the use of let and const.
Answer: let, and const are the new ways of declaring variables in ES6. Earlier, we had the only var for variables.
let: It is used to create a mutable variable. It means that its value can be changed just like var.
const: It is used to create an immutable variable. Its value cannot be changed throughout the program.
Q27. What is “this” keyword?
Answer: The “this” keyword refers to the object it belongs to.
Q28. Briefly explain the difference between .forEach() and .map() loop.
forEach: This iterates over a list and applies some operations to each list.
map: This iterates over a list, transforms each member of that list, and returns another list of the same size with the transformed members.
Q29. How to create a heading in the div having id “wrapper” through JavaScript?
<script>
var container = document.getElementById("wrapper")
var heading = document.createElement("h1")
var text = document.createTextNode("Title of the page")
heading.appendChild(text)
container.appendChild(heading)
</script>
Q30. Is JavaScript synchronous or asynchronous?
Answer: JavaScript is a synchronous language. It means that it is single threaded. Single threaded means only one command is being executed at a time. But yes, we can make our code asynchronous using callbacks.
Q31. What are callbacks?
Answer: As we know that JavaScript code runs from top to bottom sequentially. But in some cases, we may want to run a certain piece of code after something else happens. This is how we do asynchronous programming.
function functionOne(){
setTimeout( function(){
console.log("This is the first function");
}, 2000 );
}
function functionTwo(){
console.log("This is the second function");
}
functionOne();
functionTwo();
In this example, although we have called functionOne() first but still functionTwo will run first, and the first function will execute after 2 seconds. This is how we can achieve asynchronous programming in Js.
Q32. What is promise in JavaScript?
Answer: Promises are a way of handling asynchronous operation in JavaScript. Promises were made to solve the problem of dealing with async code, before promises we were using callbacks.
var promiseWorked;
promiseWorked = true;
promiseExample = new Promise(function(resolve, reject) {
if (promiseWorked) {
resolve("The man likes to keep his word");
} else {
reject("The man doesnt want to keep his word");
}
});
console.log(promiseExample);
Q33. In how many ways can you reverse a string?
Answer: There are five ways for doing so,
Using decrement for loop.
function reversingString(s) {
var revStr = ""
for(let i=(s.length-1); i>=0; i--) {
revStr += s[i]
}
document.write(revStr)
}
reversingString("Reversing String with decrement for loop")
Using Array.reverse method.
function reversingString(s) {
document.write( […s].reverse().join("") )
}
reversingString("Reversing with reverse() method ")
Using array.reduce() method.
function reversingString(s) {
const revStr = s.split("").reduce((reverse, char) => char + reverse , "")
document.write(revStr)
}
reversingString("Reversing string with reduce() method ")
Using array.unshift method.
function reversingString(s) {
var splitStr = s.split("")
var revStr = []
for(let char of splitStr) {
revStr.unshift(char)
}
document.write(revStr.join(""))
}
reversingString("Reversing string with unshift() method")
Using recursion.
function reversingString(s){
if(s === ""){
return s
} else{
return reversingString(s.substring(1)) + s[0]
}
}
var revStr = reversingString("Reversing string with recursion")
document.write(revStr)
Q34. What are the ways to deal with the Asynchronous code in JavaScript?
- Callbacks
- Promises
- Async/await
Q35. What are the differences between normal functions and arrow functions?
- Arrow functions are not hoisted.
- “this” keyword is not bound in arrow functions.
- We cannot use argument objects in arrow function, but we can use them in regular functions.
- We cannot call the arrow function with the “new” keyword.
Q36. why arrow functions are more preferred?
Answer: There are several reasons why developers prefer arrow functions over regular functions.
- They are easy to write because of their short syntax. Even they allowed implicit returns if there is no body block resulting in simpler code.
- You can write your code in a concise and more readable form because writing => is way simpler than writing a function
- They have properties that allow them to work correctly with callback functions.
- Arrow function automatically bounds this to the surrounding context.
Q37. What is the difference between local storage and session storage?
Answer: They are temporary storage on the client-side. In local storage, data is not sent to the server for every http request, so it reduced the amount of traffic between client and server. The stored data will stay until it is manually deleted from the setting or through coding.
Session storage is similar to local storage, except for one difference: that is, it is session-based. This means the data will clear when the browser is closed.
Q38. What is NAN in JavaScript?
Answer: The NAN represents “Not A Number”. This property indicated that a value is not a number. It is usually used to report an error condition for a function that should return a legal number. In JavaScript, we can use the property of isNan() to find whether a number is valid or not.
console.log(isNaN(6343)) //false
console.log(isNaN(“Hello”)) //true
console.log(isNaN(63.43)) //false
You can also learn one more error, JavaScript Errors database.
Q39. what will be the output for the following piece of code? Suppose you enter 4.
var num = prompt("Enter a number")
console.log(num + num)
Answer: if we enter 4 in this popup, it will result in 44 because prompt results in a string so the input 4 will be considered a string, so “4” + “4”is 44.
Q40. How can you convert the prompt input into a number so that we can perform some calculations?
Answer: We have some built-in methods available to do so.
It will convert the input into a number.
var num = parseInt(prompt(“Enter a Number”))
It will convert the floating point input to a float number.
var num = parseFloat(prompt(“Enter a Number”))
It will work for both integers and floating point numbers
var num = Number(prompt(“Enter a Number”))
or
var num = +prompt(“Enter a Number”))
Q41. What is setTimeOut?
Answer: The setTimeOut() is a method that sets a timer and executes a callback function after a specified period of time which we provide in milliseconds.
setTimeout(function(){
console.log("This text will print after 2 seconds");
}, 2000);
q42. What are template literals?
Answer: Template literal gives you more control over dynamic strings. It is enclosed in backticks. By declaring string like that, you can easily add a single quote or double quote without using an escape character.
var msg = `Hello welcome to "CodeLeaks"`
let firstName = "Code"
let lastName = "Leaks"
var greet = `Welcome to ${firstName,lastName}`
Q43. How to get all the keys of an object?
Answer: JavaScript has a method called Object.keys() which returns all the keys of the specified object.
var obj = {
1 : "One",
2 : "Two",
3 : "Three"
}
console.log(Object.keys(obj))
Q44. What will be the output of the following piece of code?
var obj = {
Name:"James",
age:50,
eyeColor:"grey"
}
var objCopy = obj
delete objCopy.age
console.log(obj)
Answer: The output will be {Name: “James”, eyeColor: “blue”}. When we directly copy an object to another, then the memory of both variables remains the same, so that’s why, when we altered the objCopy, the original obj also changed.
Q45. How can you copy an object?
Answer: The easiest way of copying an object is by using the spread operator.
var obj = {
Name:"James",
age:50,
eyeColor:"blue"
}
var objCopy = {...obj}
This way, when we change something in objCopy, the obj will remain the same.
Q46. What is the use of a super keyword?
Answer: In classes, the super method refers to the parent class. We use this keyword in a child class to call the parent constructor and to access its properties and methods
Q47. What is async and await?
Answer: async function enables us to write promises based code. It runs asynchronously. If we’re using async, then it simply implies that it will return a promise.
The await is used to wait for the promise. It makes JavaScript wait until the promise returns a value. It is only functional inside the async block.
Q48. What is the generator?
Answer: A normal function does not stop until it executes completely. Whereas generator is a function that can stop midway and then continue. It produces a sequence of results instead of a single value. For creating a generator function, we use function* syntax.
Q49. How to change the font size of a paragraph having an id of “para” through JavaScript?
document.getElementById(“para”).style.fontSize = “30px”;
Q50. What is variable typing in JavaScript?
Answer: Since JavaScript is a loosely types language, you can declare a variable, but later on in the same program, you can reassign the variable with the different data types.
var num = 5;
console.log(num);
num = "five";
console.log(num);
Conclusion:
In this article, you’ve learned different logical questions. We try to add questions from the new features because, as a web developer, you should know what they are and how to use them. Remember, keep calm and relax while giving the interview. Best of luck!