Table of contents
- Who created javascript
- What is the use of preventDefault method
- What is the use of stopPropagation method
- What are the steps involved in return false usage
- What is BOM
- What is the use of setTimeout
- What is the use of setInterval
- Why is JavaScript treated as Single threaded
- What is an event delegation
- What is ECMAScript
- What is JSON
- What are the syntax rules of JSON
- What is the purpose JSON stringify
- How do you parse JSON string
- Why do you need JSON
- What are PWAs
- What is the purpose of clearTimeout method
- What is the purpose of clearInterval method
- How do you redirect new page in javascript
- How do you check whether a string contains a substring
- How do you validate an email in javascript
- How do you get the current url with javascript
- What are the various url properties of location object
- How do get query string values in javascript
- How do you check if a key exists in an object
- How do you loop through or enumerate javascript object
- How do you test for an empty object
- What is an arguments object
- How do you make first letter of the string in an uppercase
- What are the pros and cons of for loops
- How do you display the current date in javascript
- How do you compare two date objects
- How do you check if a string starts with another string
- How do you trim a string in javascript
- How do you add a key value pair in javascript
- Is the !-- notation represents a special operator
- How do you assign default values to variables
- How do you define multiline strings
- What is an app shell model
- Can we define properties for functions
- What is the way to find the number of parameters expected by a function
- What is a polyfill
- What are break and continue statements
- What are js labels
- What are the benefits of keeping declarations at the top
- What are the benefits of initializing variables
- What are the recommendations to create new object
- How do you define JSON arrays
- How do you generate random integers
- Can you write a random integers function to print integers within a range
- What is tree shaking
- What is the need of tree shaking
- Is it recommended to use eval
- What is a Regular Expression
- What are the string methods that accept Regular expression
- What are modifiers in regular expression
- What are regular expression patterns
- What is a RegExp object
- How do you search a string for a pattern
- What is the purpose of exec method
- How do you change the style of a HTML element
- What would be the result of 1+2+'3'
- What is a debugger statement
- What is the purpose of breakpoints in debugging
- Can I use reserved words as identifiers
- How do you detect a mobile browser
- How do you detect a mobile browser without regexp
- How do you get the image width and height using JS
- How do you make synchronous HTTP request
- How do you make asynchronous HTTP request
- How do you convert date to another timezone in javascript
- What are the properties used to get size of window
- What is a conditional operator in javascript
- Can you apply chaining on conditional operator
- What are the ways to execute javascript after page load
- What is the difference between proto and prototype
- Can you give an example of when you really need a semicolon
- What is a freeze method
- What is the purpose of freeze method
- Why do I need to use freeze method
- How do you detect a browser language preference
- How to convert string to title case with javascript
- How do you detect javascript disabled in the page
- What are various operators supported by javascript
- What is a rest parameter
- What happens if you do not use rest parameter as a last argument
- What are the bitwise operators available in javascript
- What is a spread operator
- How do you determine whether object is frozen or not
- How do you determine two values same or not using object
- What is the purpose of using object is method
- How do you copy properties from one object to other
- What are the applications of assign method
- What is a proxy object
- What is the purpose of seal method
- What are the applications of seal method
- What are the differences between freeze and seal methods
- How do you determine if an object is sealed or not
- How do you get enumerable key and value pairs
- What is the main difference between Object.values and Object.entries method
Welcome back to the series on 500 JavaScript Interview Questions!
In the first part, we explored key concepts that interviewers frequently ask about, such as IIFE, Hoisting, Currying, and more. If you haven’t checked it out yet, feel free to catch up here.
In today’s post, we’re continuing with another set of foundational JavaScript questions that every developer should be prepared for. Whether you’re gearing up for your next interview or just honing your skills, these questions will challenge your understanding of JavaScript at a deeper level.
Let's jump right in!
Who created javascript
JavaScript was created by Brendan Eich in 1995 during his time at Netscape Communications. Initially it was developed under the name
Mocha
, but later the language was officially calledLiveScript
when it first shipped in beta releases of Netscape.What is the use of preventDefault method
The preventDefault() method cancels the event if it is cancelable, meaning that the default action or behaviour that belongs to the event will not occur. For example, prevent form submission when clicking on submit button and prevent opening the page URL when clicking on hyperlink are some common use cases.
document .getElementById("link") .addEventListener("click", function (event) { event.preventDefault(); });
Note: Remember that not all events are cancelable.
What is the use of stopPropagation method
The stopPropagation method is used to stop the event from bubbling up the event chain. For example, the below nested divs with stopPropagation method prevents default event propagation when clicking on nested div(Div1)
<p>Click DIV1 Element</p> <div onclick="secondFunc()">DIV 2 <div onclick="firstFunc(event)">DIV 1</div> </div> <script> function firstFunc(event) { alert("DIV 1"); event.stopPropagation(); } function secondFunc() { alert("DIV 2"); } </script>
What are the steps involved in return false usage
The return false statement in event handlers performs the below steps,
First it stops the browser's default action or behaviour.
It prevents the event from propagating the DOM
Stops callback execution and returns immediately when called.
What is BOM
The Browser Object Model (BOM) allows JavaScript to "talk to" the browser. It consists of the objects navigator, history, screen, location and document which are children of the window. The Browser Object Model is not standardized and can change based on different browsers.
What is the use of setTimeout
The setTimeout() method is used to call a function or evaluate an expression after a specified number of milliseconds. For example, let's log a message after 2 seconds using setTimeout method.
setTimeout(function () { console.log("Good morning"); }, 2000);
What is the use of setInterval
The setInterval() method is used to call a function or evaluate an expression at specified intervals (in milliseconds). For example, let's log a message after 2 seconds using setInterval method,
setInterval(function () { console.log("Good morning"); }, 2000);
Why is JavaScript treated as Single threaded
JavaScript is a single-threaded language. Because the language specification does not allow the programmer to write code so that the interpreter can run parts of it in parallel in multiple threads or processes. Whereas languages like java, go, C++ can make multi-threaded and multi-process programs.
What is an event delegation
Event delegation is a technique for listening to events where you delegate a parent element as the listener for all of the events that happen inside it.
For example, if you wanted to detect field changes inside a specific form, you can use event delegation technique,
var form = document.querySelector("#registration-form"); // Listen for changes to fields inside the form form.addEventListener( "input", function (event) { // Log the field that was changed console.log(event.target); }, false );
What is ECMAScript
ECMAScript is the scripting language that forms the basis of JavaScript. ECMAScript standardized by the ECMA International standards organization in the ECMA-262 and ECMA-402 specifications. The first edition of ECMAScript was released in 1997.
What is JSON
JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language in the way objects are built in JavaScript.
What are the syntax rules of JSON
Below are the list of syntax rules of JSON
The data is in name/value pairs
The data is separated by commas
Curly braces hold objects
Square brackets hold arrays
What is the purpose JSON stringify
When sending data to a web server, the data has to be in a string format. You can achieve this by converting JSON object into a string using stringify() method.
var userJSON = { name: "John", age: 31 }; var userString = JSON.stringify(userJSON); console.log(userString); //"{"name":"John","age":31}"
How do you parse JSON string
When receiving the data from a web server, the data is always in a string format. But you can convert this string value to a javascript object using parse() method.
var userString = '{"name":"John","age":31}'; var userJSON = JSON.parse(userString); console.log(userJSON); // {name: "John", age: 31}
Why do you need JSON
When exchanging data between a browser and a server, the data can only be text. Since JSON is text only, it can easily be sent to and from a server, and used as a data format by any programming language.
What are PWAs
Progressive web applications (PWAs) are a type of mobile app delivered through the web, built using common web technologies including HTML, CSS and JavaScript. These PWAs are deployed to servers, accessible through URLs, and indexed by search engines.
What is the purpose of clearTimeout method
The clearTimeout() function is used in javascript to clear the timeout which has been set by setTimeout()function before that. i.e, The return value of setTimeout() function is stored in a variable and it’s passed into the clearTimeout() function to clear the timer.
For example, the below setTimeout method is used to display the message after 3 seconds. This timeout can be cleared by the clearTimeout() method.
<script> var msg; function greeting() { alert('Good morning'); } function start() { msg =setTimeout(greeting, 3000); } function stop() { clearTimeout(msg); } </script>
What is the purpose of clearInterval method
The clearInterval() function is used in javascript to clear the interval which has been set by setInterval() function. i.e, The return value returned by setInterval() function is stored in a variable and it’s passed into the clearInterval() function to clear the interval.
For example, the below setInterval method is used to display the message for every 3 seconds. This interval can be cleared by the clearInterval() method.
<script> var msg; function greeting() { alert('Good morning'); } function start() { msg = setInterval(greeting, 3000); } function stop() { clearInterval(msg); } </script>
How do you redirect new page in javascript
In vanilla javascript, you can redirect to a new page using the
location
property of window object. The syntax would be as follows,function redirect() { window.location.href = "newPage.html"; }
How do you check whether a string contains a substring
There are 3 possible ways to check whether a string contains a substring or not,
- Using includes: ES6 provided
String.prototype.includes
method to test a string contains a substring
- Using includes: ES6 provided
var mainString = "hello",
subString = "hell";
mainString.includes(subString);
- Using indexOf: In an ES5 or older environment, you can use
String.prototype.indexOf
which returns the index of a substring. If the index value is not equal to -1 then it means the substring exists in the main string.
var mainString = "hello",
subString = "hell";
mainString.indexOf(subString) !== -1;
- Using RegEx: The advanced solution is using Regular expression's test method(
RegExp.test
), which allows for testing for against regular expressions
var mainString = "hello",
regex = /hell/;
regex.test(mainString);
How do you validate an email in javascript
You can validate an email in javascript using regular expressions. It is recommended to do validations on the server side instead of the client side. Because the javascript can be disabled on the client side.
function validateEmail(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); }
The above regular expression accepts unicode characters.
How do you get the current url with javascript
You can use
window.location.href
expression to get the current url path and you can use the same expression for updating the URL too. You can also usedocument.URL
for read-only purposes but this solution has issues in FF.console.log("location.href", window.location.href); // Returns full URL
What are the various url properties of location object
The below
Location
object properties can be used to access URL components of the page,href - The entire URL
protocol - The protocol of the URL
host - The hostname and port of the URL
hostname - The hostname of the URL
port - The port number in the URL
pathname - The path name of the URL
search - The query portion of the URL
hash - The anchor portion of the URL
How do get query string values in javascript
You can use URLSearchParams to get query string values in javascript. Let's see an example to get the client code value from URL query string,
const urlParams = new URLSearchParams(window.location.search); const clientCode = urlParams.get("clientCode");
How do you check if a key exists in an object
You can check whether a key exists in an object or not using three approaches,
Using in operator: You can use the in operator whether a key exists in an object or not
"key" in obj;
and If you want to check if a key doesn't exist, remember to use parenthesis,
!("key" in obj);
Using hasOwnProperty method: You can use
hasOwnProperty
to particularly test for properties of the object instance (and not inherited properties)obj.hasOwnProperty("key"); // true
Using undefined comparison: If you access a non-existing property from an object, the result is undefined. Let’s compare the properties against undefined to determine the existence of the property.
const user = { name: "John", }; console.log(user.name !== undefined); // true console.log(user.nickName !== undefined); // false
How do you loop through or enumerate javascript object
You can use the
for-in
loop to loop through javascript object. You can also make sure that the key you get is an actual property of an object, and doesn't come from the prototype usinghasOwnProperty
method.var object = { k1: "value1", k2: "value2", k3: "value3", }; for (var key in object) { if (object.hasOwnProperty(key)) { console.log(key + " -> " + object[key]); // k1 -> value1 ... } }
How do you test for an empty object
There are different solutions based on ECMAScript versions
- Using Object entries(ECMA 7+): You can use object entries length along with constructor type.
Object.entries(obj).length === 0 && obj.constructor === Object; // Since date object length is 0, you need to check constructor check as well
- Using Object keys(ECMA 5+): You can use object keys length along with constructor type.
Object.keys(obj).length === 0 && obj.constructor === Object; // Since date object length is 0, you need to check constructor check as well
- Using for-in with hasOwnProperty(Pre-ECMA 5): You can use a for-in loop along with hasOwnProperty.
function isEmpty(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
return JSON.stringify(obj) === JSON.stringify({});
}
What is an arguments object
The arguments object is an Array-like object accessible inside functions that contains the values of the arguments passed to that function. For example, let's see how to use arguments object inside sum function,
function sum() { var total = 0; for (var i = 0, len = arguments.length; i < len; ++i) { total += arguments[i]; } return total; } sum(1, 2, 3); // returns 6
Note: You can't apply array methods on arguments object. But you can convert into a regular array as below.
var argsArray = Array.prototype.slice.call(arguments);
How do you make first letter of the string in an uppercase
You can create a function which uses a chain of string methods such as charAt, toUpperCase and slice methods to generate a string with the first letter in uppercase.
function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); }
What are the pros and cons of for loops
The for-loop is a commonly used iteration syntax in javascript. It has both pros and cons
Pros
Works on every environment
You can use break and continue flow control statements
Cons
Too verbose
Imperative
You might face off-by-one errors.
How do you display the current date in javascript
You can use
new Date()
to generate a new Date object containing the current date and time. For example, let's display the current date in mm/dd/yyyyvar today = new Date(); var dd = String(today.getDate()).padStart(2, "0"); var mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0! var yyyy = today.getFullYear(); today = mm + "/" + dd + "/" + yyyy; document.write(today);
How do you compare two date objects
You need to use date.getTime() method to compare date values instead of comparison operators (==, !=, ===, and !== operators)
var d1 = new Date(); var d2 = new Date(d1); console.log(d1.getTime() === d2.getTime()); //True console.log(d1 === d2); // False
How do you check if a string starts with another string
You can use ECMAScript 6's
String.prototype.startsWith()
method to check if a string starts with another string or not. But it is not yet supported in all browsers. Let's see an example to see this usage,"Good morning".startsWith("Good"); // true "Good morning".startsWith("morning"); // false
How do you trim a string in javascript
JavaScript provided a trim method on string types to trim any whitespaces present at the beginning or ending of the string.
" Hello World ".trim(); //Hello World
If your browser(<IE9) doesn't support this method then you can use below polyfill.
if (!String.prototype.trim) { (function () { // Make sure we trim BOM and NBSP var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; String.prototype.trim = function () { return this.replace(rtrim, ""); }; })(); }
How do you add a key value pair in javascript
There are two possible solutions to add new properties to an object.
Let's take a simple object to explain these solutions.
var object = { key1: value1, key2: value2, };
- Using dot notation: This solution is useful when you know the name of the property
object.key3 = "value3";
- Using square bracket notation: This solution is useful when the name of the property is dynamically determined.
obj["key3"] = "value3";
Is the !-- notation represents a special operator
No,that's not a special operator. But it is a combination of 2 standard operators one after the other,
A logical not (!)
A prefix decrement (--)
At first, the value decremented by one and then tested to see if it is equal to zero or not for determining the truthy/falsy value.
How do you assign default values to variables
You can use the logical or operator
||
in an assignment expression to provide a default value. The syntax looks like as below,var a = b || c;
As per the above expression, variable 'a 'will get the value of 'c' only if 'b' is falsy (if is null, false, undefined, 0, empty string, or NaN), otherwise 'a' will get the value of 'b'.
How do you define multiline strings
You can define multiline string literals using the '\n' character followed by line terminator('').
var str = "This is a \n\ very lengthy \n\ sentence!"; console.log(str);
But if you have a space after the '\n' character, there will be indentation inconsistencies.
What is an app shell model
An application shell (or app shell) architecture is one way to build a Progressive Web App that reliably and instantly loads on your users' screens, similar to what you see in native applications. It is useful for getting some initial HTML to the screen fast without a network.
Can we define properties for functions
Yes, We can define properties for functions because functions are also objects.
fn = function (x) { //Function code goes here }; fn.name = "John"; fn.profile = function (y) { //Profile code goes here };
What is the way to find the number of parameters expected by a function
You can use
function.length
syntax to find the number of parameters expected by a function. Let's take an example ofsum
function to calculate the sum of numbers,function sum(num1, num2, num3, num4) { return num1 + num2 + num3 + num4; } sum.length; // 4 is the number of parameters expected.
What is a polyfill
A polyfill is a piece of JS code used to provide modern functionality on older browsers that do not natively support it. For example, Silverlight plugin polyfill can be used to mimic the functionality of an HTML Canvas element on Microsoft Internet Explorer 7.
There are two main polyfill libraries available,
Core.js: It is a modular javascript library used for cutting-edge ECMAScript features.
Polyfill.io: It provides polyfills that are required for browser needs.
What are break and continue statements
The break statement is used to "jump out" of a loop. i.e, It breaks the loop and continues executing the code after the loop.
for (i = 0; i < 10; i++) { if (i === 5) { break; } text += "Number: " + i + "<br>"; }
The continue statement is used to "jump over" one iteration in the loop. i.e, It breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
for (i = 0; i < 10; i++) { if (i === 5) { continue; } text += "Number: " + i + "<br>"; }
What are js labels
The label statement allows us to name loops and blocks in JavaScript. We can then use these labels to refer back to the code later. For example, the below code with labels avoids printing the numbers when they are same,
var i, j; loop1: for (i = 0; i < 3; i++) { loop2: for (j = 0; j < 3; j++) { if (i === j) { continue loop1; } console.log("i = " + i + ", j = " + j); } } // Output is: // "i = 1, j = 0" // "i = 2, j = 0" // "i = 2, j = 1"
What are the benefits of keeping declarations at the top
It is recommended to keep all declarations at the top of each script or function. The benefits of doing this are,
Gives cleaner code
It provides a single place to look for local variables
Easy to avoid unwanted global variables
It reduces the possibility of unwanted re-declarations
What are the benefits of initializing variables
It is recommended to initialize variables because of the below benefits,
It gives cleaner code
It provides a single place to initialize variables
Avoid undefined values in the code
What are the recommendations to create new object
It is recommended to avoid creating new objects using
new Object()
. Instead you can initialize values based on it's type to create the objects.Assign {} instead of new Object()
Assign "" instead of new String()
Assign 0 instead of new Number()
Assign false instead of new Boolean()
Assign [] instead of new Array()
Assign /()/ instead of new RegExp()
Assign function (){} instead of new Function()
You can define them as an example,
var v1 = {};
var v2 = "";
var v3 = 0;
var v4 = false;
var v5 = [];
var v6 = /()/;
var v7 = function () {};
How do you define JSON arrays
JSON arrays are written inside square brackets and arrays contain javascript objects. For example, the JSON array of users would be as below,
"users":[ {"firstName":"John", "lastName":"Abrahm"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Shane", "lastName":"Warn"} ]
How do you generate random integers
You can use Math.random() with Math.floor() to return random integers. For example, if you want generate random integers between 1 to 10, the multiplication factor should be 10,
Math.floor(Math.random() * 10) + 1; // returns a random integer from 1 to 10 Math.floor(Math.random() * 100) + 1; // returns a random integer from 1 to 100
Note: Math.random() returns a random number between 0 (inclusive), and 1 (exclusive)
Can you write a random integers function to print integers within a range
Yes, you can create a proper random function to return a random number between min and max (both included)
function randomInteger(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } randomInteger(1, 100); // returns a random integer from 1 to 100 randomInteger(1, 1000); // returns a random integer from 1 to 1000
What is tree shaking
Tree shaking is a form of dead code elimination. It means that unused modules will not be included in the bundle during the build process and for that it relies on the static structure of ES2015 module syntax,( i.e. import and export). Initially this has been popularized by the ES2015 module bundler
rollup
.What is the need of tree shaking
Tree Shaking can significantly reduce the code size in any application. i.e, The less code we send over the wire the more performant the application will be. For example, if we just want to create a “Hello World” Application using SPA frameworks then it will take around a few MBs, but by tree shaking it can bring down the size to just a few hundred KBs. Tree shaking is implemented in Rollup and Webpack bundlers.
Is it recommended to use eval
No, it allows arbitrary code to be run which causes a security problem. As we know that the eval() function is used to run text as code. In most of the cases, it should not be necessary to use it.
What is a Regular Expression
A regular expression is a sequence of characters that forms a search pattern. You can use this search pattern for searching data in a text. These can be used to perform all types of text search and text replace operations. Let's see the syntax format now,
/pattern/modifiers;
For example, the regular expression or search pattern with case-insensitive username would be,
/John/i;
What are the string methods that accept Regular expression
There are six string methods: search(), replace(), replaceAll(), match(), matchAll(), and split().
The search() method uses an expression to search for a match, and returns the position of the match.
var msg = "Hello John"; var n = msg.search(/John/i); // 6
The replace() and replaceAll() methods are used to return a modified string where the pattern is replaced.
var msg = "ball bat"; var n1 = msg.replace(/b/i, "c"); // call bat var n2 = msg.replaceAll(/b/i, "c"); // call cat
The match() and matchAll() methods are used to return the matches when matching a string against a regular expression.
var msg = "Hello John"; var n1 = msg.match(/[A-Z]/g); // ["H", "J"] var n2 = msg.matchAll(/[A-Z]/g); // this returns an iterator
The split() method is used to split a string into an array of substrings, and returns the new array.
var msg = "Hello John"; var n = msg.split(/\s/); // ["Hello", "John"]
What are modifiers in regular expression
Modifiers can be used to perform case-insensitive and global searches. Let's list down some of the modifiers,
| Modifier | Description | | --- | --- | | i | Perform case-insensitive matching | | g | Perform a global match rather than stops at first match | | m | Perform multiline matching |
Let's take an example of global modifier,
var text = "Learn JS one by one"; var pattern = /one/g; var result = text.match(pattern); // one,one
What are regular expression patterns
Regular Expressions provide a group of patterns in order to match characters. Basically they are categorized into 3 types,
Brackets: These are used to find a range of characters. For example, below are some use cases,
[abc]: Used to find any of the characters between the brackets(a,b,c)
[0-9]: Used to find any of the digits between the brackets
(a|b): Used to find any of the alternatives separated with |
Metacharacters: These are characters with a special meaning. For example, below are some use cases,
\d: Used to find a digit
\s: Used to find a whitespace character
\b: Used to find a match at the beginning or ending of a word
Quantifiers: These are useful to define quantities. For example, below are some use cases,
n+: Used to find matches for any string that contains at least one n
n*: Used to find matches for any string that contains zero or more occurrences of n
n?: Used to find matches for any string that contains zero or one occurrences of n
What is a RegExp object
RegExp object is a regular expression object with predefined properties and methods. Let's see the simple usage of RegExp object,
var regexp = new RegExp("\\w+"); console.log(regexp); // expected output: /\w+/
How do you search a string for a pattern
You can use the test() method of regular expression in order to search a string for a pattern, and return true or false depending on the result.
var pattern = /you/; console.log(pattern.test("How are you?")); //true
What is the purpose of exec method
The purpose of exec method is similar to test method but it executes a search for a match in a specified string and returns a result array, or null instead of returning true/false.
var pattern = /you/; console.log(pattern.exec("How are you?")); //["you", index: 8, input: "How are you?", groups: undefined]
How do you change the style of a HTML element
You can change inline style or classname of a HTML element using javascript
- Using style property: You can modify inline style using style property
document.getElementById("title").style.fontSize = "30px";
- Using ClassName property: It is easy to modify element class using className property
document.getElementById("title").className = "custom-title";
What would be the result of 1+2+'3'
The output is going to be
33
. Since1
and2
are numeric values, the result of the first two digits is going to be a numeric value3
. The next digit is a string type value because of that the addition of numeric value3
and string type value3
is just going to be a concatenation value33
.What is a debugger statement
The debugger statement invokes any available debugging functionality, such as setting a breakpoint. If no debugging functionality is available, this statement has no effect. For example, in the below function a debugger statement has been inserted. So execution is paused at the debugger statement just like a breakpoint in the script source.
function getProfile() { // code goes here debugger; // code goes here }
What is the purpose of breakpoints in debugging
You can set breakpoints in the javascript code once the debugger statement is executed and the debugger window pops up. At each breakpoint, javascript will stop executing, and let you examine the JavaScript values. After examining values, you can resume the execution of code using the play button.
Can I use reserved words as identifiers
No, you cannot use the reserved words as variables, labels, object or function names. Let's see one simple example,
var else = "hello"; // Uncaught SyntaxError: Unexpected token else
How do you detect a mobile browser
You can use regex which returns a true or false value depending on whether or not the user is browsing with a mobile.
window.mobilecheck = function () { var mobileCheck = false; (function (a) { if ( /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test( a ) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test( a.substr(0, 4) ) ) mobileCheck = true; })(navigator.userAgent || navigator.vendor || window.opera); return mobileCheck; };
How do you detect a mobile browser without regexp
You can detect mobile browsers by simply running through a list of devices and checking if the useragent matches anything. This is an alternative solution for RegExp usage,
function detectmob() { if ( 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) ) { return true; } else { return false; } }
How do you get the image width and height using JS
You can programmatically get the image and check the dimensions(width and height) using Javascript.
var img = new Image(); img.onload = function () { console.log(this.width + "x" + this.height); }; img.src = "http://www.google.com/intl/en_ALL/images/logo.gif";
How do you make synchronous HTTP request
Browsers provide an XMLHttpRequest object which can be used to make synchronous HTTP requests from JavaScript
function httpGet(theUrl) { var xmlHttpReq = new XMLHttpRequest(); xmlHttpReq.open("GET", theUrl, false); // false for synchronous request xmlHttpReq.send(null); return xmlHttpReq.responseText; }
How do you make asynchronous HTTP request
Browsers provide an XMLHttpRequest object which can be used to make asynchronous HTTP requests from JavaScript by passing the 3rd parameter as true.
function httpGetAsync(theUrl, callback) { var xmlHttpReq = new XMLHttpRequest(); xmlHttpReq.onreadystatechange = function () { if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) callback(xmlHttpReq.responseText); }; xmlHttpReq.open("GET", theUrl, true); // true for asynchronous xmlHttpReq.send(null); }
How do you convert date to another timezone in javascript
You can use the toLocaleString() method to convert dates in one timezone to another. For example, let's convert current date to British English timezone as below,
console.log(event.toLocaleString("en-GB", { timeZone: "UTC" })); //29/06/2019, 09:56:00
What are the properties used to get size of window
You can use innerWidth, innerHeight, clientWidth, clientHeight properties of windows, document element and document body objects to find the size of a window. Let's use them combination of these properties to calculate the size of a window or document,
var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
What is a conditional operator in javascript
The conditional (ternary) operator is the only JavaScript operator that takes three operands which acts as a shortcut for if statements.
var isAuthenticated = false; console.log( isAuthenticated ? "Hello, welcome" : "Sorry, you are not authenticated" ); //Sorry, you are not authenticated
Can you apply chaining on conditional operator
Yes, you can apply chaining on conditional operators similar to if … else if … else if … else chain. The syntax is going to be as below,
function traceValue(someParam) { return condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : value4; } // The above conditional operator is equivalent to: function traceValue(someParam) { if (condition1) { return value1; } else if (condition2) { return value2; } else if (condition3) { return value3; } else { return value4; } }
What are the ways to execute javascript after page load
You can execute javascript after page load in many different ways,
- window.onload:
window.onload = function ...
- document.onload:
document.onload = function ...
- body onload:
<body onload="script();">
What is the difference between proto and prototype
The
__proto__
object is the actual object that is used in the lookup chain to resolve methods, etc. Whereasprototype
is the object that is used to build__proto__
when you create an object with new.new Employee().__proto__ === Employee.prototype; new Employee().prototype === undefined;
There are few more differences,
| feature | Prototype | proto | | --- | --- | --- | | Access | All the function constructors have prototype properties. | All the objects have __proto__ property | | Purpose | Used to reduce memory wastage with a single copy of function | Used in lookup chain to resolve methods, constructors etc. | | ECMAScript | Introduced in ES6 | Introduced in ES5 | | Usage | Frequently used | Rarely used |
Can you give an example of when you really need a semicolon
It is recommended to use semicolons after every statement in JavaScript. For example, in the below case it throws an error ".. is not a function" at runtime due to missing semicolon.
// define a function var fn = (function () { //... })( // semicolon missing at this line // then execute some code inside a closure function () { //... } )();
and it will be interpreted as
var fn = (function () { //... })(function () { //... })();
In this case, we are passing the second function as an argument to the first function and then trying to call the result of the first function call as a function. Hence, the second function will fail with a "... is not a function" error at runtime.
What is a freeze method
The freeze() method is used to freeze an object. Freezing an object does not allow adding new properties to an object, prevents removing, and prevents changing the enumerability, configurability, or writability of existing properties. i.e. It returns the passed object and does not create a frozen copy.
const obj = { prop: 100, }; Object.freeze(obj); obj.prop = 200; // Throws an error in strict mode console.log(obj.prop); //100
Remember freezing is only applied to the top-level properties in objects but not for nested objects. For example, let's try to freeze user object which has employment details as nested object and observe that details have been changed.
const user = { name: "John", employment: { department: "IT", }, }; Object.freeze(user); user.employment.department = "HR";
Note: It causes a TypeError if the argument passed is not an object.
What is the purpose of freeze method
Below are the main benefits of using freeze method,
It is used for freezing objects and arrays.
It is used to make an object immutable.
Why do I need to use freeze method
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. Hence it works as the
final
keyword which is used in various languages.How do you detect a browser language preference
You can use navigator object to detect a browser language preference as below,
var language = (navigator.languages && navigator.languages[0]) || // Chrome / Firefox navigator.language || // All browsers navigator.userLanguage; // IE <= 10 console.log(language);
How to convert string to title case with javascript
Title case means that the first letter of each word is capitalized. You can convert a string to title case using the below function,
function toTitleCase(str) { return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase(); }); } toTitleCase("good morning john"); // Good Morning John
How do you detect javascript disabled in the page
You can use the
<noscript>
tag to detect javascript disabled or not. The code block inside<noscript>
gets executed when JavaScript is disabled, and is typically used to display alternative content when the page generated in JavaScript.<script type="javascript"> // JS related code goes here </script> <noscript> <a href="next_page.html?noJS=true">JavaScript is disabled in the page. Please click Next Page</a> </noscript>
What are various operators supported by javascript
An operator is capable of manipulating(mathematical and logical computations) a certain value or operand. There are various operators supported by JavaScript as below,
Arithmetic Operators: Includes + (Addition), – (Subtraction), * (Multiplication), / (Division), % (Modulus), ++ (Increment) and – – (Decrement)
Comparison Operators: Includes == (Equal), != (Not Equal), === (Equal with type), > (Greater than), >= (Greater than or Equal to), < (Less than), <= (Less than or Equal to)
Logical Operators: Includes && (Logical AND), || (Logical OR), ! (Logical NOT)
Assignment Operators: Includes = (Assignment Operator), += (Add and Assignment Operator), –= (Subtract and Assignment Operator), *= (Multiply and Assignment), /= (Divide and Assignment), %= (Modules and Assignment)
Ternary Operators: It includes conditional(: ?) Operator
typeof Operator: It uses to find type of variable. The syntax looks like
typeof variable
What is a rest parameter
Rest parameter is an improved way to handle function parameters which allows us to represent an indefinite number of arguments as an array. The syntax would be as below,
function f(a, b, ...theArgs) { // ... }
For example, let's take a sum example to calculate on dynamic number of parameters,
function sum(...args) { let total = 0; for (const i of args) { total += i; } return total; } console.log(sum(1, 2)); //3 console.log(sum(1, 2, 3)); //6 console.log(sum(1, 2, 3, 4)); //10 console.log(sum(1, 2, 3, 4, 5)); //15
Note: Rest parameter is added in ES2015 or ES6
What happens if you do not use rest parameter as a last argument
The rest parameter should be the last argument, as its job is to collect all the remaining arguments into an array. For example, if you define a function like below it doesn’t make any sense and will throw an error.
function someFunc(a,…b,c){ //You code goes here return; }
What are the bitwise operators available in javascript
Below are the list of bitwise logical operators used in JavaScript
Bitwise AND ( & )
Bitwise OR ( | )
Bitwise XOR ( ^ )
Bitwise NOT ( ~ )
Left Shift ( << )
Sign Propagating Right Shift ( >> )
Zero fill Right Shift ( >>> )
What is a spread operator
Spread operator allows iterables( arrays / objects / strings ) to be expanded into single arguments/elements. Let's take an example to see this behavior,
function calculateSum(x, y, z) { return x + y + z; } const numbers = [1, 2, 3]; console.log(calculateSum(...numbers)); // 6
How do you determine whether object is frozen or not
Object.isFrozen() method is used to determine if an object is frozen or not.An object is frozen if all of the below conditions hold true,
If it is not extensible.
If all of its properties are non-configurable.
If all its data properties are non-writable. The usage is going to be as follows,
const object = {
property: "Welcome JS world",
};
Object.freeze(object);
console.log(Object.isFrozen(object));
How do you determine two values same or not using object
The Object.is() method determines whether two values are the same value. For example, the usage with different types of values would be,
Object.is("hello", "hello"); // true Object.is(window, window); // true Object.is([], []); // false
Two values are the same if one of the following holds:
both undefined
both null
both true or both false
both strings of the same length with the same characters in the same order
both the same object (means both object have same reference)
both numbers and both +0 both -0 both NaN both non-zero and both not NaN and both have the same value.
What is the purpose of using object is method
Some of the applications of Object's
is
method are follows,It is used for comparison of two strings.
It is used for comparison of two numbers.
It is used for comparing the polarity of two numbers.
It is used for comparison of two objects.
How do you copy properties from one object to other
You can use the Object.assign() method which is used to copy the values and properties from one or more source objects to a target object. It returns the target object which has properties and values copied from the source objects. The syntax would be as below,
Object.assign(target, ...sources);
Let's take example with one source and one target object,
const target = { a: 1, b: 2 }; const source = { b: 3, c: 4 }; const returnedTarget = Object.assign(target, source); console.log(target); // { a: 1, b: 3, c: 4 } console.log(returnedTarget); // { a: 1, b: 3, c: 4 }
As observed in the above code, there is a common property(
b
) from source to target so it's value has been overwritten.What are the applications of assign method
Below are the some of main applications of Object.assign() method,
It is used for cloning an object.
It is used to merge objects with the same properties.
What is a proxy object
The Proxy object is used to define custom behavior for fundamental operations such as property lookup, assignment, enumeration, function invocation, etc.
A proxy is created with two parameters: a target object which you want to proxy and a handler object which contains methods to intercept fundamental operations. The syntax would be as follows,
var p = new Proxy(target, handler);
Let's take a look at below examples of proxy object and how the get method which customize the lookup behavior,
//Example1: const person = { name: 'Sudheer Jonna', age: 35 }; const handler = { get(target, prop) { if (prop === 'name') { return 'Mr. ' + target[prop]; } return target[prop]; } }; const proxy = new Proxy(person, handler); //Example2: var handler1 = { get: function (obj, prop) { return prop in obj ? obj[prop] : 100; }, }; var p = new Proxy({}, handler1); p.a = 10; p.b = null; console.log(p.a, p.b); // 10, null console.log("c" in p, p.c); // false, 100
In the above code, it uses
get
handler which define the behavior of the proxy when an operation is performed on it. These proxies are mainly used for some of the below cross-cutting concerns.Logging
Authentication or Authorization
Data binding and observables
Function parameter validation
Note: This is a new feature in ES6.
What is the purpose of seal method
The Object.seal() method is used to seal an object, by preventing new properties from being added to it and marking all existing properties as non-configurable. But values of present properties can still be changed as long as they are writable. Let's see the below example to understand more about seal() method
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
What are the applications of seal method
Below are the main applications of Object.seal() method,
It is used for sealing objects and arrays.
It is used to make an object immutable.
What are the differences between freeze and seal methods
If an object is frozen using the Object.freeze() method then its properties become immutable and no changes can be made in 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.
How do you determine if an object is sealed or not
The Object.isSealed() method is used to determine if an object is sealed or not. An object is sealed if all of the below conditions hold true
If it is not extensible.
If all of its properties are non-configurable.
If it is not removable (but not necessarily non-writable). Let's see it in the action
const object = {
property: "Hello, Good morning",
};
Object.seal(object); // Using seal() method to seal the object
console.log(Object.isSealed(object)); // checking whether the object is sealed or not
How do you get enumerable key and value pairs
The Object.entries() method is used to return an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop. Let's see the functionality of object.entries() method in an example,
const object = { a: "Good morning", b: 100, }; for (let [key, value] of Object.entries(object)) { console.log(`${key}: ${value}`); // a: 'Good morning' // b: 100 }
Note: The order is not guaranteed as object defined.
What is the main difference between Object.values and Object.entries method
The Object.values() method's behavior is similar to Object.entries() method but it returns an array of values instead [key,value] pairs.
const object = {
a: "Good morning",
b: 100,
};
for (let value of Object.values(object)) {
console.log(`${value}`); // 'Good morning \n100'
}
In conclusion, mastering JavaScript is essential for any developer aiming to excel in web development. This series of JavaScript interview questions provides a comprehensive overview of fundamental concepts and advanced techniques that are crucial for both interviews and practical application.
By understanding topics such as event handling, JSON manipulation, and the intricacies of the language's syntax and features, developers can enhance their problem-solving skills and write more efficient, effective code.
Continuous learning and practice with these concepts will not only prepare you for interviews but also empower you to build robust and dynamic web applications. Keep exploring and experimenting with JavaScript to stay updated with the latest advancements and best practices in the field.