Click ⭐if you like the project and follow @SudheerJonna for more updates. Coding questions available here. Check DataStructures and Algorithms for DSA related questions and ECMAScript for all ES features.).
💡 Nail JavaScript interviews with questions and solutions from ex-interviewers! Try GreatFrontEnd → 💡
🚀 Ace Javascript interview questions with solutions from FAANG+ companies! Try FrontendLead → 🚀
- Take this JavaScript Projects course to go from a JS beginner to confidently building your own projects
- Take this coding interview bootcamp if you’re serious about getting hired and don’t have a CS degree
- Take this Advanced JavaScript Course to learn advanced JS concepts and become a top JS developer
-
There are many ways to create objects in javascript as mentioned below:
-
Object literal syntax:
The object literal syntax (or object initializer), is a comma-separated set of name-value pairs wrapped in curly braces.
var object = { name: "Sudheer", age: 34 };
Object literal property values can be of any data type, including array, function, and nested object.
Note: This is one of the easiest ways to create an object.
Object constructor:
The simplest way to create an empty object is using the
Object
constructor. Currently this approach is not recommended.var object = new Object();
The
Object()
is a built-in constructor function so "new" keyword is not required. The above code snippet can be re-written as:var object = Object();
Object's create method:
The
create
method of Object is used to create a new object by passing the specified prototype object and properties as arguments, i.e., this pattern is helpful to create new objects based on existing objects. The second argument is optional and it is used to create properties on a newly created object.The following code creates a new empty object whose prototype is null.
var object = Object.create(null);
The following example creates an object along with additional new properties.
let vehicle = { wheels: '4', fuelType: 'Gasoline', color: 'Green' } let carProps = { type: { value: 'Volkswagen' }, model: { value: 'Golf' } } var car = Object.create(vehicle, carProps); console.log(car);
Function constructor:
In this approach, create any function and apply the new operator to create object instances.
function Person(name) { this.name = name; this.age = 21; } var object = new Person("Sudheer");
Function constructor with prototype:
This is similar to function constructor but it uses prototype for their properties and methods,
function Person() {} Person.prototype.name = "Sudheer"; var object = new Person();
This is equivalent to creating an instance with Object.create method with a function prototype and then calling that function with an instance and parameters as arguments.
function func() {} new func(x, y, z);
(OR)
// Create a new instance using function prototype. var newInstance = Object.create(func.prototype) // Call the function var result = func.call(newInstance, x, y, z), // If the result is a non-null object then use it otherwise just use the new instance. console.log(result && typeof result === 'object' ? result : newInstance);
Object's assign method:
The
Object.assign
method is used to copy all the properties from one or more source objects and stores them into a target object.The following code creates a new staff object by copying properties of his working company and the car he owns.
const orgObject = { company: 'XYZ Corp'}; const carObject = { name: 'Toyota'}; const staff = Object.assign({}, orgObject, carObject);
ES6 Class syntax:
ES6 introduces class feature to create objects.
class Person { constructor(name) { this.name = name; } } var object = new Person("Sudheer");
Singleton pattern:
A Singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance. This way one can ensure that they don't accidentally create multiple instances.
var object = new (function () { this.name = "Sudheer"; })();
Prototype chaining is used to build new types of objects based on existing ones. It is similar to inheritance in a class based language. i.e, When you create an object using a constructor function or a class, the created object inherits properties from a prototype object.
The prototype on object instance is available through Object.getPrototypeOf(object) or __proto__ property whereas prototype on constructor function is available through Object.prototype.
The difference between Call, Apply and Bind can be explained with below examples,
Call: The call() method invokes a function with a given
this
value and arguments provided one by onevar employee1 = { firstName: "John", lastName: "Rodson" }; var employee2 = { firstName: "Jimmy", lastName: "Baily" }; function invite(greeting1, greeting2) { console.log( greeting1 + " " + this.firstName + " " + this.lastName + ", " + greeting2 ); } invite.call(employee1, "Hello", "How are you?"); // Hello John Rodson, How are you? invite.call(employee2, "Hello", "How are you?"); // Hello Jimmy Baily, How are you?
Apply: Invokes the function with a given
this
value and allows you to pass in arguments as an arrayvar employee1 = { firstName: "John", lastName: "Rodson" }; var employee2 = { firstName: "Jimmy", lastName: "Baily" }; function invite(greeting1, greeting2) { console.log( greeting1 + " " + this.firstName + " " + this.lastName + ", " + greeting2 ); } invite.apply(employee1, ["Hello", "How are you?"]); // Hello John Rodson, How are you? invite.apply(employee2, ["Hello", "How are you?"]); // Hello Jimmy Baily, How are you?
Bind: returns a new function, allowing you to pass any number of arguments
var employee1 = { firstName: "John", lastName: "Rodson" }; var employee2 = { firstName: "Jimmy", lastName: "Baily" }; function invite(greeting1, greeting2) { console.log( greeting1 + " " + this.firstName + " " + this.lastName + ", " + greeting2 ); } var inviteEmployee1 = invite.bind(employee1); var inviteEmployee2 = invite.bind(employee2); inviteEmployee1("Hello", "How are you?"); // Hello John Rodson, How are you? inviteEmployee2("Hello", "How are you?"); // Hello Jimmy Baily, How are you?
Call and Apply are pretty much interchangeable. Both execute the current function immediately. You need to decide whether it’s easier to send in an array or a comma separated list of arguments. You can remember by treating Call is for comma (separated list) and Apply is for Array.
Bind creates a new function that will have
this
set to the first parameter passed to bind().JSON is a text-based data format following JavaScript object syntax, which was popularized by
Douglas Crockford
. It is useful when you want to transmit data across a network. It is basically just a text file with an extension of .json, and a MIME type of application/jsonParsing: Converting a string to a native object
JSON.parse(text);
Stringification: Converting a native object to a string so that it can be transmitted across the network
JSON.stringify(object);
The slice() method returns the selected elements in an array as a new array object. It selects the elements starting at the given start argument, and ends at the given optional end argument without including the last element. If you omit the second argument then it selects till the end of the array. This method can also accept negative index which counts back from the end of the array.
Some of the examples of this method are,
let arrayIntegers = [1, 2, 3, 4, 5]; let arrayIntegers1 = arrayIntegers.slice(0, 2); // returns [1,2] let arrayIntegers2 = arrayIntegers.slice(2, 3); // returns [3] let arrayIntegers3 = arrayIntegers.slice(4); //returns [5] let arrayIntegers4 = arrayIntegers.slice(-3, -1); //returns [3, 4]
Note: Slice method doesn't mutate the original array but it returns the subset as a new array.
The splice() method adds/removes items to/from an array, and then returns the removed item. The first argument specifies the array position/index for insertion or deletion whereas the optional second argument indicates the number of elements to be deleted. Each additional argument is added to the array.
Some of the examples of this method are:
let arrayIntegersOriginal1 = [1, 2, 3, 4, 5]; let arrayIntegersOriginal2 = [1, 2, 3, 4, 5]; let arrayIntegersOriginal3 = [1, 2, 3, 4, 5]; let arrayIntegers1 = arrayIntegersOriginal1.splice(0, 2); // returns [1, 2]; original array: [3, 4, 5] let arrayIntegers2 = arrayIntegersOriginal2.splice(3); // returns [4, 5]; original array: [1, 2, 3] let arrayIntegers3 = arrayIntegersOriginal3.splice(3, 1, "a", "b", "c"); //returns [4]; original array: [1, 2, 3, "a", "b", "c", 5]
Note: Splice method modifies the original array and returns the deleted array.
Some of the major differences in a tabular form:
Slice Splice Doesn't modify the original array(immutable) Modifies the original array(mutable) Returns the subset of original array Returns the deleted elements as array Used to pick the elements from array Used to insert/delete elements to/from array Objects are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Due to this reason, Objects have been used as Maps historically. But there are important differences that make using a Map preferable in certain cases:
- The keys of an Object can be Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive type.
- The keys in a Map are ordered while keys added to Object are not. Thus, when iterating over it, a Map object returns keys in the order of insertion.
- You can get the size of a Map easily with the size property, while the number of properties in an Object must be determined manually.
- A Map is an iterable and can thus be directly iterated, whereas iterating over an Object requires obtaining its keys in some fashion and iterating over them.
- An Object has a prototype, so there are default keys in an object that could collide with your keys if you're not careful. As of ES5 this can be bypassed by creating an object(which can be called a map) using
Object.create(null)
, but this practice is seldom done. - A Map may perform better in scenarios involving frequent addition and removal of key pairs.
JavaScript provides both strict(===, !==) and type-converting(==, !=) equality comparison. The strict operators take type of variable in consideration, while non-strict operators make type correction/conversion based upon values of variables. The strict operators follow the below conditions for different types,
- Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
- Two numbers are strictly equal when they are numerically equal, i.e., having the same number value.
There are two special cases in this,
- NaN is not equal to anything, including NaN.
- Positive and negative zeros are equal to one another.
- Two Boolean operands are strictly equal if both are true or both are false.
- Two objects are strictly equal if they refer to the same Object.
- Null and Undefined types are not equal with ===, but equal with == .
i.e,
null===undefined --> false
, butnull==undefined --> true
Some of the example which covers the above cases:
0 == false // true 0 === false // false 1 == "1" // true 1 === "1" // false null == undefined // true null === undefined // false '0' == false // true '0' === false // false NaN == NaN or NaN === NaN // false []==[] or []===[] //false, refer different objects in memory {}=={} or {}==={} //false, refer different objects in memory
An arrow function is a shorter/concise syntax for a function expression and does not have its own this, arguments, super, or new.target. These functions are best suited for non-method functions, and they cannot be used as constructors.
Some of the examples of arrow functions are listed as below,
const arrowFunc1 = (a, b) => a + b; // Multiple parameters const arrowFunc2 = a => a * 10; // Single parameter const arrowFunc3 = () => {} // no parameters
In Javascript, functions are first class objects. First-class functions means when functions in that language are treated like any other variable.
For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. For example, in the below example, handler functions assigned to a listener
const handler = () => console.log("This is a click handler function"); document.addEventListener("click", handler);
A first-order function is a function that doesn’t accept another function as an argument and doesn’t return a function as its return value.
const firstOrder = () => console.log("I am a first order function!");
A higher-order function is a function that accepts another function as an argument or returns a function as a return value or both. The syntactic structure of higher order function will be as follows,
const firstOrderFunc = () => console.log("Hello, I am a First order function"); const higherOrder = (ReturnFirstOrderFunc) => ReturnFirstOrderFunc(); higherOrder(firstOrderFunc);
You can also call the function which you are passing to higher order function as callback function.
The higher order function is helpful to write the modular and reusable code.
A unary function (i.e. monadic) is a function that accepts exactly one argument. It stands for a single argument accepted by a function.
Let us take an example of unary function,
const unaryFunction = (a) => console.log(a + 10); // Add 10 to the given argument and display the value
Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument. Currying is named after a mathematician Haskell Curry. By applying currying, an n-ary function turns into a unary function.
Let's take an example of n-ary function and how it turns into a currying function,
const multiArgFunction = (a, b, c) => a + b + c; console.log(multiArgFunction(1, 2, 3)); // 6 const curryUnaryFunction = (a) => (b) => (c) => a + b + c; curryUnaryFunction(1); // returns a function: b => c => 1 + b + c curryUnaryFunction(1)(2); // returns a function: c => 3 + c curryUnaryFunction(1)(2)(3); // returns the number 6
Curried functions are great to improve code reusability and functional composition.
A Pure function is a function where the return value is only determined by its arguments without any side effects. i.e, If you call a function with the same arguments 'n' number of times and 'n' number of places in the application then it will always return the same value.
Let's take an example to see the difference between pure and impure functions,
//Impure let numberArray = []; const impureAddNumber = (number) => numberArray.push(number); //Pure const pureAddNumber = (number) => (argNumberArray) => argNumberArray.concat([number]); //Display the results console.log(impureAddNumber(6)); // returns 1 console.log(numberArray); // returns [6] console.log(pureAddNumber(7)(numberArray)); // returns [6, 7] console.log(numberArray); // returns [6]
As per the above code snippets, the Push function is impure itself by altering the array and returning a push number index independent of the parameter value, whereas Concat on the other hand takes the array and concatenates it with the other array producing a whole new array without side effects. Also, the return value is a concatenation of the previous array.
Remember that Pure functions are important as they simplify unit testing without any side effects and no need for dependency injection. They also avoid tight coupling and make it harder to break your application by not having any side effects. These principles are coming together with the Immutability concept of ES6: giving preference to const over let usage.
The
let
statement declares a block scope local variable. Hence the variables defined with let keyword are limited in scope to the block, statement, or expression on which it is used. Whereas variables declared with thevar
keyword used to define a variable globally, or locally to an entire function regardless of block scope.Let's take an example to demonstrate the usage,
let counter = 30; if (counter === 30) { let counter = 31; console.log(counter); // 31 } console.log(counter); // 30 (because the variable in if block won't exist here)
You can list out the differences in a tabular format
var let It has been available from the beginning of JavaScript Introduced as part of ES6 It has function scope It has block scope Variable declaration will be hoisted, initialized as undefined Hoisted but not initialized It is possible to re-declare the variable in the same scope It is not possible to re-declare the variable Let's take an example to see the difference,
function userDetails(username) { if (username) { console.log(salary); // undefined due to hoisting console.log(age); // ReferenceError: Cannot access 'age' before initialization let age = 30; var salary = 10000; } console.log(salary); //10000 (accessible due to function scope) console.log(age); //error: age is not defined(due to block scope) } userDetails("John");
let
is a mathematical statement that was adopted by early programming languages like Scheme and Basic. It has been borrowed from dozens of other languages that uselet
already as a traditional keyword as close tovar
as possible.If you try to redeclare variables in a
switch block
then it will cause errors because there is only one block. For example, the below code block throws a syntax error as below,let counter = 1; switch (x) { case 0: let name; break; case 1: let name; // SyntaxError for redeclaration. break; }
To avoid this error, you can create a nested block inside a case clause and create a new block scoped lexical environment.
let counter = 1; switch (x) { case 0: { let name; break; } case 1: { let name; // No SyntaxError for redeclaration. break; } }
The Temporal Dead Zone(TDZ) is a specific period or area of a block where a variable is inaccessible until it has been initialized with a value. This behavior in JavaScript that occurs when declaring a variable with the let and const keywords, but not with var. In ECMAScript 6, accessing a
let
orconst
variable before its declaration (within its scope) causes a ReferenceError.Let's see this behavior with an example,
function somemethod() { console.log(counter1); // undefined console.log(counter2); // ReferenceError var counter1 = 1; let counter2 = 2; }
IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The signature of it would be as below,
(function () { // logic here })();
The primary reason to use an IIFE is to obtain data privacy because any variables declared within the IIFE cannot be accessed by the outside world. i.e, If you try to access variables from the IIFE then it throws an error as below,
(function () { var message = "IIFE"; console.log(message); })(); console.log(message); //Error: message is not defined
encodeURI()
function is used to encode an URL. This function requires a URL string as a parameter and return that encoded string.decodeURI()
function is used to decode an URL. This function requires an encoded URL string as parameter and return that decoded string.Note: If you want to encode characters such as
/ ? : @ & = + $ #
then you need to useencodeURIComponent()
.let uri = "employeeDetails?name=john&occupation=manager"; let encoded_uri = encodeURI(uri); let decoded_uri = decodeURI(encoded_uri);
Memoization is a functional programming technique which attempts to increase a function’s performance by caching its previously computed results. Each time a memoized function is called, its parameters are used to index the cache. If the data is present, then it can be returned, without executing the entire function. Otherwise the function is executed and then the result is added to the cache. Let's take an example of adding function with memoization,
const memoizAddition = () => { let cache = {}; return (value) => { if (value in cache) { console.log("Fetching from cache"); return cache[value]; // Here, cache.value cannot be used as property name starts with the number which is not a valid JavaScript identifier. Hence, can only be accessed using the square bracket notation. } else { console.log("Calculating result"); let result = value + 20; cache[value] = result; return result; } }; }; // returned function from memoizAddition const addition = memoizAddition(); console.log(addition(20)); //output: 40 calculated console.log(addition(20)); //output: 40 cached
Hoisting is a JavaScript mechanism where variables, function declarations and classes are moved to the top of their scope before code execution. Remember that JavaScript only hoists declarations, not initialisation. Let's take a simple example of variable hoisting,
console.log(message); //output : undefined var message = "The variable Has been hoisted";
The above code looks like as below to the interpreter,
var message; console.log(message); message = "The variable Has been hoisted";
In the same fashion, function declarations are hoisted too
message("Good morning"); //Good morning function message(name) { console.log(name); }
This hoisting makes functions to be safely used in code before they are declared.
In ES6, Javascript classes are primarily syntactic sugar over JavaScript’s existing prototype-based inheritance. For example, the prototype based inheritance written in function expression as below,
function Bike(model, color) { this.model = model; this.color = color; } Bike.prototype.getDetails = function () { return this.model + " bike has" + this.color + " color"; };
Whereas ES6 classes can be defined as an alternative
class Bike { constructor(color, model) { this.color = color; this.model = model; } getDetails() { return this.model + " bike has" + this.color + " color"; } }
A closure is the combination of a function bundled(enclosed) together with its lexical environment within which that function was declared. i.e, It is an inner function that has access to the outer or enclosing function’s variables, functions and other data even after the outer function has finished its execution. The closure has three scope chains.
- Own scope where variables defined between its curly brackets
- Outer function's variables
- Global variables
Let's take an example of closure concept,
function Welcome(name) { var greetingInfo = function (message) { console.log(message + " " + name); }; return greetingInfo; } var myFunction = Welcome("John"); myFunction("Welcome "); //Output: Welcome John myFunction("Hello Mr."); //output: Hello Mr. John
As per the above code, the inner function(i.e, greetingInfo) has access to the variables in the outer function scope(i.e, Welcome) even after the outer function has returned.
Modules refer to small units of independent, reusable code and also act as the foundation of many JavaScript design patterns. Most of the JavaScript modules export an object literal, a function, or a constructor
Below are the list of benefits using modules in javascript ecosystem
- Maintainability
- Reusability
- Namespacing
Scope is the accessibility of variables, functions, and objects in some particular part of your code during runtime. In other words, scope determines the visibility of variables and other resources in areas of your code.
A Service worker is basically a script (JavaScript file) that runs in the background, separate from a web page and provides features that don't need a web page or user interaction. Some of the major features of service workers are Rich offline experiences(offline first web application development), periodic background syncs, push notifications, intercept and handle network requests and programmatically managing a cache of responses.
Service worker can't access the DOM directly. But it can communicate with the pages it controls by responding to messages sent via the
postMessage
interface, and those pages can manipulate the DOM.The problem with service worker is that it gets terminated when not in use, and restarted when it's next needed, so you cannot rely on global state within a service worker's
onfetch
andonmessage
handlers. In this case, service workers will have access to IndexedDB API in order to persist and reuse across restarts.IndexedDB is a low-level API for client-side storage of larger amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data.
Web storage is an API that provides a mechanism by which browsers can store key/value pairs locally within the user's browser, in a much more intuitive fashion than using cookies. The web storage provides two mechanisms for storing data on the client.
- Local storage: It stores data for current origin with no expiration date.
- Session storage: It stores data for one session and the data is lost when the browser tab is closed.
Post message is a method that enables cross-origin communication between Window objects.(i.e, between a page and a pop-up that it spawned, or between a page and an iframe embedded within it). Generally, scripts on different pages are allowed to access each other if and only if the pages follow same-origin policy(i.e, pages share the same protocol, port number, and host).
A cookie is a piece of data that is stored on your computer to be accessed by your browser. Cookies are saved as key/value pairs. For example, you can create a cookie named username as below,
document.cookie = "username=John";
Cookies are used to remember information about the user profile(such as username). It basically involves two steps,
- When a user visits a web page, the user profile can be stored in a cookie.
- Next time the user visits the page, the cookie remembers the user profile.
There are few below options available for a cookie,
- By default, the cookie is deleted when the browser is closed but you can change this behavior by setting expiry date (in UTC time).
document.cookie = "username=John; expires=Sat, 8 Jun 2019 12:00:00 UTC";
- By default, the cookie belongs to a current page. But you can tell the browser what path the cookie belongs to using a path parameter.
document.cookie = "username=John; path=/services";
You can delete a cookie by setting the expiry date as a passed date. You don't need to specify a cookie value in this case. For example, you can delete a username cookie in the current page as below.
document.cookie = "username=; expires=Fri, 07 Jun 2019 00:00:00 UTC; path=/;";
Note: You should define the cookie path option to ensure that you delete the right cookie. Some browsers doesn't allow to delete a cookie unless you specify a path parameter.
Below are some of the differences between cookie, local storage and session storage,
Feature Cookie Local storage Session storage Accessed on client or server side Both server-side & client-side. The set-cookie
HTTP response header is used by server inorder to send it to user.client-side only client-side only Expiry Manually configured using Expires option Forever until deleted until tab is closed SSL support Supported Not supported Not supported Maximum data size 4KB 5 MB 5MB Accessible from Any window Any window Same tab Sent with requests Yes No No LocalStorage is the same as SessionStorage but it persists the data even when the browser is closed and reopened(i.e it has no expiration time) whereas in sessionStorage data gets cleared when the page session ends.
The Window object implements the
WindowLocalStorage
andWindowSessionStorage
objects which haslocalStorage
(window.localStorage) andsessionStorage
(window.sessionStorage) properties respectively. These properties create an instance of the Storage object, through which data items can be set, retrieved and removed for a specific domain and storage type (session or local). For example, you can read and write on local storage objects as belowlocalStorage.setItem("logo", document.getElementById("logo").value); localStorage.getItem("logo");
The session storage provided methods for reading, writing and clearing the session data
// Save data to sessionStorage sessionStorage.setItem("key", "value"); // Get saved data from sessionStorage let data = sessionStorage.getItem("key"); // Remove saved data from sessionStorage sessionStorage.removeItem("key"); // Remove all saved data from sessionStorage sessionStorage.clear();
The StorageEvent is an event that fires when a storage area has been changed in the context of another document. Whereas onstorage property is an EventHandler for processing storage events. The syntax would be as below
window.onstorage = functionRef;
Let's take the example usage of onstorage event handler which logs the storage key and it's values
window.onstorage = function (e) { console.log( "The " + e.key + " key has been changed from " + e.oldValue + " to " + e.newValue + "." ); };
Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance. Also, the information is never transferred to the server. Hence this is a more recommended approach than Cookies.
You need to check browser support for localStorage and sessionStorage before using web storage,
if (typeof Storage !== "undefined") { // Code for localStorage/sessionStorage. } else { // Sorry! No Web Storage support.. }
You need to check browser support for web workers before using it
if (typeof Worker !== "undefined") { // code for Web worker support. } else { // Sorry! No Web Worker support.. }
You need to follow below steps to start using web workers for counting example
- Create a Web Worker File: You need to write a script to increment the count value. Let's name it as counter.js
let i = 0; function timedCount() { i = i + 1; postMessage(i); setTimeout("timedCount()", 500); } timedCount();
Here postMessage() method is used to post a message back to the HTML page
- Create a Web Worker Object: You can create a web worker object by checking for browser support. Let's name this file as web_worker_example.js
if (typeof w == "undefined") { w = new Worker("counter.js"); }
and we can receive messages from web worker
w.onmessage = function (event) { document.getElementById("message").innerHTML = event.data; };
- Terminate a Web Worker: Web workers will continue to listen for messages (even after the external script is finished) until it is terminated. You can use the terminate() method to terminate listening to the messages.
w.terminate();
- Reuse the Web Worker: If you set the worker variable to undefined you can reuse the code
w = undefined;
WebWorkers don't have access to below javascript objects since they are defined in an external files
- Window object
- Document object
- Parent object
A promise is an object that may produce a single value some time in the future with either a resolved value or a reason that it’s not resolved(for example, network error). It will be in one of the 3 possible states: fulfilled, rejected, or pending.
The syntax of Promise creation looks like below,
const promise = new Promise(function (resolve, reject) { // promise description });
The usage of a promise would be as below,
const promise = new Promise( (resolve) => { setTimeout(() => { resolve("I'm a Promise!"); }, 5000); }, (reject) => {} ); promise.then((value) => console.log(value));
The action flow of a promise will be as below,
Promises are used to handle asynchronous operations. They provide an alternative approach for callbacks by reducing the callback hell and writing the cleaner code.
Promises have three states:
- Pending: This is an initial state of the Promise before an operation begins
- Fulfilled: This state indicates that the specified operation was completed.
- Rejected: This state indicates that the operation did not complete. In this case an error value will be thrown.
A callback function is a function passed into another function as an argument. This function is invoked inside the outer function to complete an action. Let's take a simple example of how to use callback function
function callbackFunction(name) { console.log("Hello " + name); } function outerFunction(callback) { let name = prompt("Please enter your name."); callback(name); } outerFunction(callbackFunction);
The callbacks are needed because javascript is an event driven language. That means instead of waiting for a response javascript will keep executing while listening for other events. Let's take an example with the first function invoking an API call(simulated by setTimeout) and the next function which logs the message.
function firstFunction() { // Simulate a code delay setTimeout(function () { console.log("First function called"); }, 1000); } function secondFunction() { console.log("Second function called"); } firstFunction(); secondFunction(); Output; // Second function called // First function called
As observed from the output, javascript didn't wait for the response of the first function and the remaining code block got executed. So callbacks are used in a way to make sure that certain code doesn’t execute until the other code finishes execution.
Callback Hell is an anti-pattern with multiple nested callbacks which makes code hard to read and debug when dealing with asynchronous logic. The callback hell looks like below,
async1(function(){ async2(function(){ async3(function(){ async4(function(){ .... }); }); }); });
Server-sent events (SSE) is a server push technology enabling a browser to receive automatic updates from a server via HTTP connection without resorting to polling. These are a one way communications channel - events flow from server to client only. This has been used in Facebook/Twitter updates, stock price updates, news feeds etc.
The EventSource object is used to receive server-sent event notifications. For example, you can receive messages from server as below,
if (typeof EventSource !== "undefined") { var source = new EventSource("sse_generator.js"); source.onmessage = function (event) { document.getElementById("output").innerHTML += event.data + "<br>"; }; }
You can perform browser support for server-sent events before using it as below,
if (typeof EventSource !== "undefined") { // Server-sent events supported. Let's have some code here! } else { // No server-sent events supported }
Below are the list of events available for server sent events
Event Description onopen It is used when a connection to the server is opened onmessage This event is used when a message is received onerror It happens when an error occurs A promise must follow a specific set of rules:
- A promise is an object that supplies a standard-compliant
.then()
method - A pending promise may transition into either fulfilled or rejected state
- A fulfilled or rejected promise is settled and it must not transition into any other state.
- Once a promise is settled, the value must not change.
You can nest one callback inside in another callback to execute the actions sequentially one by one. This is known as callbacks in callbacks.
loadScript("/script1.js", function (script) { console.log("first script is loaded"); loadScript("/script2.js", function (script) { console.log("second script is loaded"); loadScript("/script3.js", function (script) { console.log("third script is loaded"); // after all scripts are loaded }); }); });
The process of executing a sequence of asynchronous tasks one after another using promises is known as Promise chaining. Let's take an example of promise chaining for calculating the final result,
new Promise(function (resolve, reject) { setTimeout(() => resolve(1), 1000); }) .then(function (result) { console.log(result); // 1 return result * 2; }) .then(function (result) { console.log(result); // 2 return result * 3; }) .then(function (result) { console.log(result); // 6 return result * 4; });
In the above handlers, the result is passed to the chain of .then() handlers with the below work flow,
- The initial promise resolves in 1 second,
- After that
.then
handler is called by logging the result(1) and then return a promise with the value of result * 2. - After that the value passed to the next
.then
handler by logging the result(2) and return a promise with result * 3. - Finally the value passed to the last
.then
handler by logging the result(6) and return a promise with result * 4.
Promise.all is a promise that takes an array of promises as an input (an iterable), and it gets resolved when all the promises get resolved or any one of them gets rejected. For example, the syntax of promise.all method is below,
Promise.all([Promise1, Promise2, Promise3]) .then(result) => { console.log(result) }) .catch(error => console.log(`Error in promises ${error}`))
Note: Remember that the order of the promises(output the result) is maintained as per input order.
Promise.race() method will return the promise instance which is firstly resolved or rejected. Let's take an example of race() method where promise2 is resolved first
var promise1 = new Promise(function (resolve, reject) { setTimeout(resolve, 500, "one"); }); var promise2 = new Promise(function (resolve, reject) { setTimeout(resolve, 100, "two"); }); Promise.race([promise1, promise2]).then(function (value) { console.log(value); // "two" // Both promises will resolve, but promise2 is faster });
Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. This way it prevents certain actions from being taken and throws more exceptions. The literal expression
"use strict";
instructs the browser to use the javascript code in the Strict mode.Strict mode is useful to write "secure" JavaScript by notifying "bad syntax" into real errors. For example, it eliminates accidentally creating a global variable by throwing an error and also throws an error for assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object.
The strict mode is declared by adding "use strict"; to the beginning of a script or a function. If declared at the beginning of a script, it has global scope.
"use strict"; x = 3.14; // This will cause an error because x is not declared
and if you declare inside a function, it has local scope
x = 3.14; // This will not cause an error. myFunction(); function myFunction() { "use strict"; y = 3.14; // This will cause an error }
The double exclamation or negation(!!) ensures the resulting type is a boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, it will be true. For example, you can test IE version using this expression as below,
let isIE8 = false; isIE8 = !!navigator.userAgent.match(/MSIE 8.0/); console.log(isIE8); // returns true or false
If you don't use this expression then it returns the original value.
console.log(navigator.userAgent.match(/MSIE 8.0/)); // returns either an Array or null
Note: The expression !! is not an operator, but it is just twice of ! operator.
The delete operator is used to delete the property as well as its value.
var user = { firstName: "John", lastName:"Doe", age: 20 }; delete user.age; console.log(user); // {firstName: "John", lastName:"Doe"}
You can use the JavaScript typeof operator to find the type of a JavaScript variable. It returns the type of a variable or an expression.
typeof "John Abraham"; // Returns "string" typeof (1 + 2); // Returns "number" typeof [1, 2, 3]; // Returns "object" because all arrays are also objects
The undefined property indicates that a variable has not been assigned a value, or declared but not initialized at all. The type of undefined value is undefined too.
var user; // Value is undefined, type is undefined console.log(typeof user); //undefined
Any variable can be emptied by setting the value to undefined.
user = undefined;
The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values. The type of null value is object. You can empty the variable by setting the value to null.
var user = null; console.log(typeof user); //object
Below are the main differences between null and undefined,
Null Undefined It is an assignment value which indicates that variable points to no object. It is not an assignment value where a variable has been declared but has not yet been assigned a value. Type of null is object Type of undefined is undefined The null value is a primitive value that represents the null, empty, or non-existent reference. The undefined value is a primitive value used when a variable has not been assigned a value. Indicates the absence of a value for a variable Indicates absence of variable itself Converted to zero (0) while performing primitive operations Converted to NaN while performing primitive operations The eval() function evaluates JavaScript code represented as a string. The string can be a JavaScript expression, variable, statement, or sequence of statements.
console.log(eval("1 + 2")); // 3
Below are the main differences between window and document,
Window Document It is the root level element in any web page It is the direct child of the window object. This is also known as Document Object Model(DOM) By default window object is available implicitly in the page You can access it via window.document or document. It has methods like alert(), confirm() and properties like document, location It provides methods like getElementById, getElementsByTagName, createElement etc The window.history object contains the browser's history. You can load previous and next URLs in the history using back() and next() methods.
function goBack() { window.history.back(); } function goForward() { window.history.forward(); }
Note: You can also access history without window prefix.
The
mouseEvent getModifierState()
is used to return a boolean value that indicates whether the specified modifier key is activated or not. The modifiers such as CapsLock, ScrollLock and NumLock are activated when they are clicked, and deactivated when they are clicked again.Let's take an input element to detect the CapsLock on/off behavior with an example,
<input type="password" onmousedown="enterInput(event)" /> <p id="feedback"></p> <script> function enterInput(e) { var flag = e.getModifierState("CapsLock"); if (flag) { document.getElementById("feedback").innerHTML = "CapsLock activated"; } else { document.getElementById("feedback").innerHTML = "CapsLock not activated"; } } </script>
The isNaN() function is used to determine whether a value is an illegal number (Not-a-Number) or not. i.e, This function returns true if the value equates to NaN. Otherwise it returns false.
isNaN("Hello"); //true isNaN("100"); //false
Below are the major differences between undeclared(not defined) and undefined variables,
undeclared undefined These variables do not exist in a program and are not declared These variables declared in the program but have not assigned any value If you try to read the value of an undeclared variable, then a runtime error is encountered If you try to read the value of an undefined variable, an undefined value is returned. Global variables are those that are available throughout the length of the code without any scope. The var keyword is used to declare a local variable but if you omit it then it will become global variable
msg = "Hello"; // var is missing, it becomes global variable
The problem with global variables is the conflict of variable names of local and global scope. It is also difficult to debug and test the code that relies on global variables.
The NaN property is a global property that represents "Not-a-Number" value. i.e, It indicates that a value is not a legal number. It is very rare to use NaN in a program but it can be used as return value for few cases
Math.sqrt(-1); parseInt("Hello");
The isFinite() function is used to determine whether a number is a finite, legal number. It returns false if the value is +infinity, -infinity, or NaN (Not-a-Number), otherwise it returns true.
isFinite(Infinity); // false isFinite(NaN); // false isFinite(-Infinity); // false isFinite(100); // true
Event flow is the order in which event is received on the web page. When you click an element that is nested in various other elements, before your click actually reaches its destination, or target element, it must trigger the click event for each of its parent elements first, starting at the top with the global window object.
There are two ways of event flow
- Top to Bottom(Event Capturing)
- Bottom to Top (Event Bubbling)
Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element(i.e, global window object).
By default, event handlers triggered in event bubbling phase as shown below,
<div> <button class="child">Hello</button> </div> <script> const parent = document.querySelector("div"); const child = document.querySelector(".child"); parent.addEventListener("click", function () { console.log("Parent"); } ); child.addEventListener("click", function () { console.log("Child"); }); </script> // Child // Parent
Event capturing is a type of event propagation where the event is first captured by the outermost element, and then successively triggers on the descendants (children) of the target element in the same nesting hierarchy till it reaches the innermost target DOM element.
You need to pass
true
value foraddEventListener
method to trigger event handlers in event capturing phase.<div> <button class="child">Hello</button> </div> <script> const parent = document.querySelector("div"); const child = document.querySelector(".child"); parent.addEventListener("click", function () { console.log("Parent"); }, true ); child.addEventListener("click", function () { console.log("Child"); }); </script> // Parent // Child
You can submit a form using
document.forms[0].submit()
. All the form input's information is submitted using onsubmit event handlerfunction submit() { document.forms[0].submit(); }
The window.navigator object contains information about the visitor's browser OS details. Some of the OS properties are available under platform property,
console.log(navigator.platform);
The
DOMContentLoaded
event is fired when the initial HTML document has been completely loaded and parsed, without waiting for assets(stylesheets, images, and subframes) to finish loading. Whereas The load event is fired when the whole page has loaded, including all dependent resources(stylesheets, images).Native objects
are 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 objects
are objects provided by the browser or runtime environment (Node).For example, window, XmlHttpRequest, DOM nodes etc are considered as host objects.
User objects
are 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
react
on 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 calledLiveScript
when 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 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
location
property 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.includes
method 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.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);
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.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
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
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
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
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 ... } }
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 off-by-one 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 '\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.
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 };
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.
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.
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>"; }
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"
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
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
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 () {};
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"} ]
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)
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
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
.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.
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.
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;
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"]
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
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
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+/
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
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]
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";
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
.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 }
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.
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
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; };
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; } }
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";
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; }
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); }
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
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;
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
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; } }
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();">
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 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.
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.
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.
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.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);
-