Last Updated On By Khizer Ali
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
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.
Answer: There are seven data types available in JavaScript:
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.
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.
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
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))
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”.
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.
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.
Answer: 793, because after the string, all the + operator will be treated as a concatenation operator, not a binary addition operator.
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.
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.
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.
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.
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”
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
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.
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))
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
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)
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.
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”]
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
}
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.
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.
Answer: The “this” keyword refers to the object it belongs to.
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.
<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>
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.
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.
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);
Answer: There are five ways for doing so,
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")
function reversingString(s) {
document.write( […s].reverse().join("") )
}
reversingString("Reversing with reverse() method ")
function reversingString(s) {
const revStr = s.split("").reduce((reverse, char) => char + reverse , "")
document.write(revStr)
}
reversingString("Reversing string with reduce() 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")
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)
Answer: There are several reasons why developers prefer arrow functions over regular functions.
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.
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.
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.
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”))
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);
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}`
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))
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.
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.
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
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.
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.
document.getElementById(“para”).style.fontSize = “30px”;
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);
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!