-
Native objectsare objects that are part of the JavaScript language defined by the ECMAScript specification. For example, String, Math, RegExp, Object, Function etc core objects defined in the ECMAScript spec.Host objectsare objects provided by the browser or runtime environment (Node). For example, window, XmlHttpRequest, DOM nodes etc are considered as host objects.User objectsare objects defined in the javascript code. For example, User objects created for profile information. -
You can use below tools or techniques for debugging javascript
- Chrome Devtools
- debugger statement
- Good old console.log statement
-
Below are the list of pros and cons of promises over callbacks,
Pros:
- It avoids callback hell which is unreadable
- Easy to write sequential asynchronous code with .then()
- Easy to write parallel asynchronous code with Promise.all()
- Solves some of the common problems of callbacks(call the callback too late, too early, many times and swallow errors/exceptions)
Cons:
- It makes little complex code
- You need to load a polyfill if ES6 is not supported
-
Attributes are defined on the HTML markup whereas properties are defined on the DOM. For example, the below HTML element has 2 attributes type and value,
<input type="text" value="Name:">
You can retrieve the attribute value as below,
const input = document.querySelector("input"); console.log(input.getAttribute("value")); // Good morning console.log(input.value); // Good morning
And after you change the value of the text field to "Good evening", it becomes like
console.log(input.getAttribute("value")); // Good evening console.log(input.value); // Good evening
-
The same-origin policy is a policy that prevents JavaScript from making requests across domain boundaries. An origin is defined as a combination of URI scheme, hostname, and port number. If you enable this policy then it prevents a malicious script on one page from obtaining access to sensitive data on another web page using Document Object Model(DOM).
-
Void(0) is used to prevent the page from refreshing. This will be helpful to eliminate the unwanted side-effect, because it will return the undefined primitive value. It is commonly used for HTML documents that use href="JavaScript:Void(0);" within an
<a>element. i.e, when you click a link, the browser loads a new page or refreshes the same page. But this behavior will be prevented using this expression. For example, the below link notify the message without reloading the page<a href="JavaScript:void(0);" onclick="alert('Well done!')"> Click Me! </a>
-
JavaScript is an interpreted language, not a compiled language. An interpreter in the browser reads over the JavaScript code, interprets each line, and runs it. Nowadays modern browsers use a technology known as Just-In-Time (JIT) compilation, which compiles JavaScript to executable bytecode just as it is about to run.
-
Yes, JavaScript is a case sensitive language. The language keywords, variables, function & object names, and any other identifiers must always be typed with a consistent capitalization of letters.
-
No, they are entirely two different programming languages and have nothing to do with each other. But both of them are Object Oriented Programming languages and like many other languages, they follow similar syntax for basic features(if, else, for, switch, break, continue etc).
-
Events are "things" that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can
reacton these events. Some of the examples of HTML events are,- Web page has finished loading
- Input field was changed
- Button was clicked
Let's describe the behavior of click event for button element,
<!doctype html> <html> <head> <script> function greeting() { alert('Hello! Good morning'); } </script> </head> <body> <button type="button" onclick="greeting()">Click me</button> </body> </html>
-
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 calledLiveScriptwhen it first shipped in beta releases of Netscape. -
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.
-
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>
-
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.
-
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.
-
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);
-
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);
-
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.
-
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 in 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 );
-
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.
-
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.
-
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
-
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}"
-
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}
-
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.
-
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.
-
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>
-
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>
-
In vanilla javascript, you can redirect to a new page using the
locationproperty of window object. The syntax would be as follows,function redirect() { window.location.href = "newPage.html"; }
-
There are 3 possible ways to check whether a string contains a substring or not,
- Using includes: ES6 provided
String.prototype.includesmethod to test a string contains a substring
var mainString = "hello", subString = "hell"; mainString.includes(subString);
- Using indexOf: In an ES5 or older environment, you can use
String.prototype.indexOfwhich 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);
- Using includes: ES6 provided
-
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.
-
You can use
window.location.hrefexpression to get the current url path and you can use the same expression for updating the URL too. You can also usedocument.URLfor read-only purposes but this solution has issues in FF.console.log("location.href", window.location.href); // Returns full URL
-
The below
Locationobject 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
-
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");
-
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
hasOwnPropertyto 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
-
You can use the
for-inloop 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 usinghasOwnPropertymethod.var object = { k1: "value1", k2: "value2", k3: "value3", }; for (var key in object) { if (object.hasOwnProperty(key)) { console.log(key + " -> " + object[key]); // k1 -> value1 ... } }
-
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({}); }
-
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);
-
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); }
-
The for-loop is a commonly used iteration syntax in javascript. It has both pros and cons
- Works on every environment
- You can use break and continue flow control statements
- Too verbose
- Imperative
- You might face one-by-off errors
-
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);
-
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
-
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
-
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, ""); }; })(); }
-
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";
-
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.
-
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'.
-
You can define multiline string literals using the '\' character followed by line terminator.
var str = "This is a \ very lengthy \ sentence!";
But if you have a space after the '\' character, the code will look exactly the same, but it will raise a SyntaxError.
-
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.
-
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 };
