JavaScript is one of the most popular programming languages basically used for frontend development. It was developed by Brendan Eich in 1995 to create dynamic web pages. Since then, it has been widely used to develop web applications and is an essential skill for front-end developers. Therefore, to build a career in front-end development, you need to understand JavaScript in detail. Have a look at our compiled list of basic JavaScript interview questions and answers to help you understand the language well.
JavaScript is a high-level, scripting language that can be used to create interactive and dynamic web pages. It can be written to HTML pages, enclosed in script tags, and the web browsers function as per the script. The scripting language can also act like an object-oriented language. However, it is not based on classes.
The language can be chosen for development for multiple reasons.
JavaScript has two main Data Types.
The primitive data types in JavaScript are:
Primitive Datatypes | Non-Primitive Datatypes |
The string data type represents a sequence of characters or a combination of characters, For example the string “Hello World”. | Object data type represents instances through which we all can access members. |
Boolean data type represents a Boolean value that can be either true or false. | RegExp represents a Regular Expression. |
The number data type represents numeral values. like 2000, 500, etc. | Arrays represent a group of similar types of data. |
Undefined:-it Represents undefined value or not defined values. |
Undefined and Null are both used to represent empty values in JavaScript, but they are not the same. Undefined is a value that represents the absence of any value. Whereas, null is a value that represents the absence of any object value.
The function will return true if the argument is not a number. However, if the argument is a number, then it returns as false.
The named container can hold any value in JavaScript. A variable is used to store data that can be accessed and manipulated by the program.
There are namely three main types of variables can be used in Javascript.
Each has their own scope and reason for usage.
All three are used to declare variables in JavaScript, but they have different scoping rules. Var has a function scope, i.e. it can be accessed anywhere within the function it is declared in. Let and const have block-scope, i.e. they can only be accessed within the block they are declared in. Moreover, Const is a constant variable whose value cannot be changed once it is declared.
A function declaration is a statement that declares a named function, whereas a function expression is an expression that creates an unnamed function. Therefore, the main difference between the two is that function declaration are hoisted, while function expressions are not.
Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their respective scopes before the code is executed. This allows variables and functions to be used before they are declared.
Undeclared Variables are the ones not declared in a program. This often leads to runtime errors. When a variable that is not declared is used in a program.
Undefined variables are the ones that are declared but hold no value. This happens when no value is passed to a variable. It may result in an ‘Undefined Variable’ error when the program wants to read the variables’ value.
The powerful feature of JavaScript allows a function to access variables from its outer scope, even after the outer function has returned. Closures are useful for creating private variables and functions that cannot be accessed from outside the function.
The call and apply methods are used to invoke a function with a specific value for the “this” keyword. The main difference between the two is that call takes individual arguments, while apply takes an array of arguments.
The variable which is not bound to any scope or is available throughout the length of the code is called the Global variable.
For declaring a local variable, a var keyword is used. It is also applicable for declaring an object. When there is the commission of the var keyword, then the global variable is declared. It is preferable to declare global variables on top of a program.
The ‘this’ keyword is used to point to the current object in Java. However, in JavaScript, the ‘this’ keyword refers to the object from where it is called. Therefore, it refers to the object it belongs to.
The ‘this’ keyword has different values according to or depending upon where it is used.
Call() and apply() method refer ‘this’ to any object.
Timers are used to execute specific code snippets at a set time and repeat the bit of code in a given interval.
This is done by using the setTimeout, setInterval, and clear interval functions in JavaScript.
The setTimeout function has a syntax like setTimeout(function, delay)
, and is used to start a timer, then call a particular function after the mentioned time delay.
The setInterval function has a syntax like setInterval(function, delay)
, and is used to repeatedly execute the given function inside with the mentioned time delay and only stops when it is canceled.
The clearInterval function has a syntax like clearInterval(id)
, and instructs or indicates the timer to stop (for stopping the given or mentioned function).
Single line comments: “//”.
Multi-line comments can be enclosed in: “/* commented code */”.
JavaScript has numerous functions for arrays. The ones to remove elements from an array are slice and spice. They may sound similar but have a different purposes.
Slice returns a shallow copy of a portion of an array, while splice removes or replaces elements of an array in place.
The scripting language used the basic looping structure, i.e for
, while
, and do-while
loop. Moreover, we can use a foreach
loop to go through each element in an array, and a for-in
loop to iterate over an object.
A for
loop iterates over a block of code a specified number of times, while a for-in
loop iterates over the properties of an object.
A while
loop checks the condition before the loop is executed, while a do-while
loop executes the loop at least once before checking the condition.
A promise is an object that represents a value that may not be available yet, while a callback is a function that is passed as an argument to another function and is executed when the other function is finished.
Synchronous code execution means that the code is executed in a linear fashion, while asynchronous code execution means that the code is executed out of order, allowing other code to run in the meantime.
Event bubbling is a behavior in which an event that is triggered on a child element is also triggered on its parent elements.
Event delegation is a technique in which events are handled by a parent element, rather than individual child elements.
JavaScript has two equality operators, i.e. == and ===. Operators with three equals sign, i.e. === or !=== are called strict comparison operators. The strict operators take the type of variable into consideration, while non-strict operators make type corrections/conversions based on the values of variables. Find more details on the difference between the == and === operators.
We can use the encodeURI() function to encode a URL. The function takes in a string URL as the parameter and returns an encoded string.
We can use the decodeURI() function to decode a URL. The function takes in an encoded URL string as the parameter and returns a decoded string.
JavaScript supports Object concepts and allows you to create an object using the object literal as shown below.
var emp = {name: "Mary",age: 22};
You can define arrays using the array literal as shown below.
var a = [];
var b = [10, 22, 35, 48, 52];
The JavaScript built-in length() function can be used to find the length of a string or the number of elements in an array. Consider the code snippet below.
var b = [10, 22, 35, 48, 52];
console.log(b.length);
// outputs: 5
The type of operator can be used to get the data type of its operand. The operand can either be a literal or a data structure such as a function, variable, or object. The unary operator is placed before its single operand, that can be of any type.
A simple way is to assign a value using the document.cookie object as shown below.
document.cookie = "key1 = a; key2 = b; expires = date";
We can simply read a cookie similar to how we write it. We can use the document.cookie object to read or write a cookie.
We can use different methods to access HTML elements as shown below.
innerHTML: processes an HTML tag if found in a string.
innerText: will not process an HTML tag if found in a string
The parseInt() function converts numbers between different bases in JavaScript. It takes the first parameter as the string to be converted, while the second is the base of the string.
The export declaration can be used to export values from JavaScript. module. These values can then be imported into other programs using the import declaration.
A promise is an object that can produce a single value at times in the future whereas a resolved value or a reason that it’s not resolved(for instance, a network error). A promise can be in either of one state, fulfilled, rejected, or pending.
Promises can handle asynchronous operations. They give an alternative approach for callbacks as they reduce the callback hell and write a cleaner code.
Callback Hell makes an anti-pattern with multiple nested callbacks that makes the code harder to read and debug when it deals with asynchronous logic.
Window | Document |
The root level element of any page. | The direct child of the window object. Also referred to as the DOM (Document Object Model). |
Window object is available implicitly on the page. | You can access it via window.document or document method. |
Uses methods like window.alert()or window.confirm and has properties like window.location. | It has methods like document.getElementById, document.getElementsByTagName, or document.getElementsByClassName. |
The mode is useful to write ‘secure’ JavaScript code and makes bad syntax turn into real errors.
51. What is the purpose of the delete operator in JavaScript?
The delete keyword helps to delete a property and its value. Consider the code snippet below.
var user = { name: "Alice", age: 25 };
delete user.age;
console.log(user); // {name: "Alice"}
Let’s have a look at some Advanced JavaScript Questions and Answers that will help you crack your interview!
Strict Mode is a new JavaScript feature that allows one to place a program, or a function, in a “strict” operating context. Therefore, it prevents taking some actions and throws exceptions. The “use strict
” expression is used for this.
JavaScript escape characters enable us to write special characters without breaking an application. You can use Escape characters (Backslash) when working with special characters like single quotes, double quotes, apostrophes, and ampersands. Placing a backslash before the characters can help them display without breaks.
We can use two different ways to create key-value pairs in JavaScript. Consider the code snippets below.
Method 1:
var object = {
key1: v1,
key2: v2,
};
Method 2:
Using the dot notation
object.key3 = "v3";
Method 3:
Using the square bracket notation.
obj["key3"] = "v3";
The Math.random() and Math.floor()functions. helps return random integers.
A regular expression defines a sequence of characters that helps match a specific pattern. We can use it to validate a string. Most useful to validate emails and contact details.
The two string methods of search()
and replace()
can be used with regular expressions. The search()
method uses an expression to search for a match while the replace method returns a modified string while replacing the pattern.
Modifiers are useful to perform case-insensitive and global searches. Consider the modifiers as shown below.
Modifier | Detail |
g | For a global match rather than stopping at the first match |
i | For case-insensitive matching |
m | For multiline matching |
Regular Expressions contain a group of patterns to match characters. They are categorized into 3 main types.
The exec method is similar to test methods, but it also does a search to find a match for a specific string pattern or a result array.
We can refer to the element by using the document.getElementById method and apply any styling as shown below.
document.getElementById("title").style.fontSize = "25px";
We can pass styling for an element in JavaScript and create a styling node in JavaScript for that element.
We can detect mobile browsers by running through a list of devices and checking if a user agent matches anything. Consider the code snippet as shown below.
navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPad/i) ||
navigator.userAgent.match(/iPod/i) ||
navigator.userAgent.match(/BlackBerry/i) ||
navigator.userAgent.match(/Windows Phone/i)
An XMLHttpRequest object can be used to make synchronous HTTP requests in JavaScript. Consider the code snippet as shown below.
function httpGet(theUrl) {
var xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.open("GET", theUrl, false); // false for synchronous request
xmlHttpReq.send(null);
return xmlHttpReq.responseText;
}
An XMLHttpRequest object can be used to make an asynchronous HTTP request in JavaScript by passing a 3rd parameter as true. Consider the code snippet as shown below.
function httpGetAsync(theUrl, callback) {
var xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.onreadystatechange = function () {
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
callback(xmlHttpReq.responseText);
};
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
The toLocaleString() method converts dates from one timezone to another. For example, to convert the current date to British English timezone, you can write the code as shown below.
console.log(event.toLocaleString("en-GB", { timeZone: "UTC" })); //29/06/2019, 09:56:00
The innerWidth, innerHeight, clientWidth, and clientHeight of windows, document body objects, or document element helps find the size of a window or a document.
The only JavaScript operator that takes three operands and acts as a shortcut for if statements. Consider the code snipper below.
var isAuthenticated = false;
console.log(
isAuthenticated ? "Hello, welcome" : "Sorry, you are not authenticated"
); //Sorry, you are not authenticated
We can define whether to load a script before or after a page or browser loads. To make a JavaScript code snippet load before page load, write the code as shown below.
window.onload = code snippet ...
The method helps to freeze an object and allows the addition of new properties to an object. In addition, it also helps remove. and prevent changing reconfigurability, enumerability, or writability. or any other existing properties.
In the Object-oriented paradigm, an existing API contains certain elements that are not intended to be extended, modified, or re-used outside of their current context. Therefore, it works as the final
keyword which is used in various languages.
The main applications of Object.assign() method are:
The Proxy object helps define custom behavior for fundamental operations like property lookup, enumeration, assignment, function invocation, etc. Consider the code snippet below to use a proxy object.
The Object.seal() method helps to seal an object, prevents new properties from being added to it, and marks all existing properties as non-configurable. For example, consider the code snippet below on how to use the sealing method in JavaScript.
const object = {
property: "Welcome JS world",
};
Object.seal(object);
object.property = "Welcome to object world";
console.log(Object.isSealed(object)); // true
delete object.property; // You cannot delete when sealed
console.log(object.property); //Welcome to object world
The main applications of Object.seal() method in JavaScript are as follows.
If an object is frozen using the Object.freeze() method then its properties become immutable and no changes can be made to them whereas if an object is sealed using the Object.seal() method then the changes can be made in the existing properties of the object.
Let’s have a look at some Coding related JavaScript Questions and Answers that will help you practice your practical questions!
Suppose ‘Welcome to this Javascript Guide’ should become ‘olleH dlroW’. You will write the code snippet as shown below.
var string = "Welcome to this Javascript Guide!";
// Output becomes !ediuG tpircsavaJ siht ot emocleW
var reverseString = reverseBySeparator(string, "");
// Output becomes emocleW ot siht tpircsavaJ !ediuG
var reverseEachWord = reverseBySeparator(reverseString, " ");
function reverseBySeparator(string, separator) {
return string.split(separator).reverse().join(separator);
}
The simple code snippet is to divide a decimal or integer by 1 and check the remainder left behind, as shown below.
function isInt(num) {
return no % 1 === 0;
}
console.log(isInt(4)); // true
console.log(isInt(12.2)); // false
console.log(isInt(0.3)); // false
(function() {
var a = b = 15;
})();
console.log(b);
The above code will give an output of 15 even though it seems as if the variable was declared within a function and can’t be accessed outside of it. This is because var a. = b = 15 is interpreted as var a = b, which makes b = 15. Even though b
is not declared anywhere in the function using var or any other keyword, it is declared as a global variable with a value of 15.
We can write a closure function that returns a specific value. We will write two functions, one inner and one outer as shown in the code snippet below.
function multiply(x) {
return function(y) {
return x * y;
}
}
multiply(10)(2);
Consider the code snippet as shown below.
var array = ["10","12","18","20"];
var newArray = array;
console.log(newArray); // ["10","12","18","20"]
array = []; // empties the array
OR
array.length = 0; // empties the array
OR
<html>
<head>
<title>t1</title>
<script type="text/javascript">
function addNode() {
var newElem = document.createElement("p");
var textNode = document.createTextNode("This is a new text node");
newElem.appendChild(textNode); document.getElementById("firstElem").appendChild(newElem); }
</script>
</head>
<body>
<p id="firstElem">First Element<p>
</body>
</html>
<script language="JavaScript" type="text/javascript" >
<!-- location. href="https://www.scratchcoding.dev/javascript-interview-questions-answers.html"; //-->
</script>
document.write "I m a "good" programmer."
document.write "I m a \"good\" programmer.
Escape characters (Backslash) work with special characters like single quotes, double quotes, ampersands, and apostrophes. You can place a backslash before the characters to make it display properly.
var subjects = ["Maths", "Science", "English"];
subjects.pop();
//Now subjects will have Maths, Science
We can either use the dot or bracket notation to assign properties to an object. For example, consider the code snippet below.
objectA ["class"] = 12;
or
objectA.class = 12;
The status variable returns true if the checkbox with id ‘elementCheck’ is checked or else false.
var status = document.getElementById('elementCheck').checked;
var name = ["alice", "mary"];
name.unshift("charlie");
console.log(name);
// outputs ["alice", "mary", "charlie"];
A variable may contain a null value or even some whitespaces. This can affect validation and variable values. Therefore, it is a good practice to add a check for both null and whitespaces as shown below.
if((source_name != "") && (source_name != " ")){
console.log("a valid source name is entered");
// do something
}
Here are more details to handle nulls and white spaces.
The DataTimeFormat()
function as shown below helps retrieve a user’s current time zone.
const current_timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(current_timezone); // example Asia/Dubai
Find here complete details to retrieve the current timezone.
The function below func_name
, will accept arguments arg1..argN
, and then evaluate the expression on the right side using the arguments and returns a result.
const func_name = (arg1, arg2, ..., argN) => expression;
Find here complete details on how to use arrow functions.
push()
in JavaScript?We can add new elements to an array using the push
or unshift
methods. The code snippet below shows how we can use the push method.
const subjects = ["English", "Maths"]
subjects.push("Science");
console.log(subjects);
// prints ["English", "Maths", "Science"] now
The fill method passes (fills) to all elements in an array with a static value and returns the new modified array. For example, when creating a new array, you may fill all positions with the same value as shown below.
const arr = new Array(5)
console.log(arr);
// prints ['', '', '', '', ''] initially
arr.fill(8);
console.log(arr);
// prints ['8', '8', '8', '8', '8'] now
The join
method concatenates all array methods to make a new string. For example, consider the code snippet below.
const arr = ["c", "a", "d", "s", "l", "i", "s", "t"]
arr.join('');
console.log(arr)
// prints cadslist
The method checks if an array includes an element that has a specific value passed in the include function, and returns Boolean results. For example, consider the code sample given below.
const arr = ["c", "a", "d", "s", "l", "i", "s", "t"]
arr.includes(c); // returns true
arr.includes(r); // returns false
We can use the map function for this, as shown below.
const arr = ["10", "90", "18", "7", "6", "3"];
const mapped_arr = arr.map(element => element - 10);
console.log(mapped_arr);
// prints [0, 80, 8, -3, -4, -7]
The filter method searches specific results from an array and creates a new array with the filtered results.
const arr = ["10", "90", "18", "7", "6", "3"];
const filtered_arr = arr.filter(element => element < 10 || element === 90);
console.log(filtered_arr);
// prints [7, 6, 3, 90]
Memoization is a caching technique that will return the value of a function based on its parameters.
function addTo500(num){
return num + 256;
}
addTo500(20); // Returns 520
addTo500(40); // Returns 540
addTo500(20); // Returns 520
var x = 23;
(function(){
var x = 43;
(function random(){
x++;
console.log(x);
var x = 21;
})();
})();
The output of this function is NaN.
The random() function has a functional scope of x. You can declare and hoist it in the functional scope.
Find Interview Questions for Laravel here.
A list of the best spas in Dubai that will relax your body and mind…
Canada is a majestically beautiful country full of natural wonders and is also home to…
Here is a list of the Best USA Makeup Brands in 2023, that are safe…
Here is a list of the Best Australian Makeup Brands in 2023, that are safe…
Content creators always try hard to make their content reach a large number of followers…
Truck companies are constantly searching for people to fulfill their logistics, transportation, and supply chain…