JavaScript

1. What is Javascript ?

JavaScript is a scripting language used for programming web pages as well as server systems. It is an object-oriented, interpreted, lightweight and powerful programming language, made up of first-class functions. The JavaScript can update the content dynamically for web pages.

Javascript is not specifically HTML related, but interacts with HTML and DHTML when used in a browser. It’s a more traditional programming language, in that you can write a series of instructions to compute what kinds of actions should be taken based on various conditions, repeat things a variable number of times, and just generally take more complex and sophisticated actions. Small applications and games have been written entirely in Javascript.

2. Difference between java and javascript.

JavaJavascript
Java is considered a compiled programming language.Java is compiled into bytecode and run on a virtual machine.JavaScript is considered an interpreted scripting language.Javascript can be interpreted directly by a browser in the syntax it is written.
Java uses static type checking, where type of a variable is checked at compile-time.The programmer must specify the type(integer, double, string, and so on) of any variable they create.Javascript, like most scripting language, uses dynamic typing, where they safely is verified at runtime.It is not required for a programmer to specify the type of any variable they create.
Java makes use of multiple threads to perform concurrency. avaScript, particularly as it exists as Node.js in server-side applications, handles concurrency on one main thread of execution via a queue system called the event loop, and a forking system called Node Clustering.
Java follows class based inheritance—a top down, hierarchical, class-based relationship whereby properties are defined in a class and inherited by an instance of that class (one of its members).In JavaScript, inheritance is prototypal—all objects can inherit directly from other objects. Hierarchy is accomplished in JavaScript by assigning an object as a prototype with a constructor function.

3. How Javascript works ?

Every browser has three prime components to work. The first one is the DOM (Document Object Model) interpreter. This will take your HTML document and convert and displays in the browser. The other small program that is the part of the browser is CSS interpreter, which will style the page and make it look better. The last one is a mini program in the browser called the JS engine.

Browser loads the HTML file/JS file

JavaScript is an interpreted language(means no compilation required)

Browser(JavaScript engine) executes line by line and waits for events(like clicks, mouseovers etc) to happen

4. List down types of Javascript data.

  • String
  • Function
  • Boolean
  • Object
  • Number
  • Null

5. What is an Object in JavaScript and How do we create them ?

A JavaScript object is an entity having state and behavior (properties and   method). Since JavaScript is an object-based language, it treats everything as an object.

JavaScript is a template-based language. It doesn’t need to define a class for creating an object instead creates it directly

JavaScript supports the following three ways to create objects.

1.By Object Literal

Object = {property1:value1, property2:value2. . . . propertyN:valueN}

Here, property and value get separated by a colon “:” sign.

Example:

<script>
std={id:11, name:”Raj Mehta”, subject:”Maths”}
document.write(std.id+” “+std.name+” “+std.subject);
</script>

2. Creating an instance of the Object (Using new keyword)

var objectname = new Object();

Here, the new keyword is used to create the object.

  Example:

<script>
var std=new Object();
std.id=11;
std.name=”Raj Mehta”;
std.subject=”Maths”;
document.write(std.id+” “+std.name+” “+std.subject);
</script>

3. Using an Object Constructor.

In this method, we create a function with arguments. The value of each of these arguments can be assigned to the current object by using this keyword.

This keyword refers to the current object.

Let’s take an example of creating an object using the object constructor technique.

<script>
function std(id,name,subject){
this.id=id;
this.name=name;
this.subject=subject;
}
s=new std(11,,”Raj Metha”,”Maths”);
document.write(s.id+” “+s.name+” “+s.subject);
</script>

6. What is Scope Means in Javascript ?

The scope determines the accessibility of variables, objects, and functions in particular part of your code.

In JavaScript, the scope is of two types.

1. Global Scope.

A variable defined outside a function comes under the Global scope. Variables defined inside the Global scope are accessible from any part of the code. Let’s see an example.

var name = ‘Kodnest’;
console.log(name); // logs ‘Kodnest’
function logName() {
console.log(name); // ‘name’ is accessible here and everywhere else
}
logName(); // logs ‘Kodnest’

2. Local Scope.

Variables defined inside a function comes under the Local scope. Different functions can use a variable with the same name. It is because these variables are strictly bound to the function that defines it (each having different scopes) and is not accessible in other functions. Let’s see an example.

// Global Scope
function sampleFunction() {
    // Local Scope #1
    function sample2Function() {
        // Local Scope #2
    }
}
// Global Scope
function sample3Function() {
    // Local Scope #3
}
// Global Scope

7. What is the purpose of let keyword ?

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 the var 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 if block variable won’t exist here)

8. Difference between let and var ?

varlet
It is been available from the beginning of JavaScript Introduced as part of ES6

It has function scopeIt has block scope
Variables will be hoistedHoisted but not initialized

Example:

function userDetails(username) {
   if(username) {
     console.log(salary); // undefined(due to hoisting)
     console.log(age); // error: age is not defined
     let age = 30;
     var salary = 10000;
   }
   console.log(salary); //10000 (accessible to due function scope)
   console.log(age); //error: age is not defined(due to block scope)
}

9. What are various operators supported by javascript?

An operator is capable of manipulating(mathematical and logical computations) a certain value or operand. There are various operators supported by JavaScript as below,

Arithmetic Operators: Includes + (Addition),– (Subtraction), * (Multiplication), / (Division), % (Modulus), + + (Increment) and – – (Decrement)

Comparison Operators: Includes = =(Equal),!= (Not Equal), ===(Equal with type), > (Greater than),> = (Greater than or Equal to),< (Less than),<= (Less than or Equal to)

Logical Operators: Includes &&(Logical AND),||(Logical OR),!(Logical NOT)

Assignment Operators: Includes = (Assignment Operator), += (Add and Assignment Operator), – = (Subtract and Assignment Operator), *= (Multiply and Assignment), /= (Divide and Assignment), %= (Modules and Assignment)

Ternary Operators: It includes conditional(: ?) Operator

typeof Operator: It uses to find type of variable. The syntax looks like typeof variable

10. What are the bitwise operators available in javascript ?

Below are the list of bit-wise logical operators used in JavaScript

  • Bit-wise AND ( & )
  • Bit-Wise OR ( | )
  • Bit-Wise XOR ( ^ )
  • Bit-Wise NOT ( ~ )
  • Sign Propagating Right Shift ( >> )
  • Zero fill Right Shift ( >>> )

11. What is prompt box ?

The Input provided by any user in the JavaScript is entered with the help of a prompt box. While putting forward the data or the input, the prompt box allows the user to do this with the help of a text box. To include the number, label box is also used.

12. What is global variable? In what way, these variables are declared.

A global variable is a special kind of variable in JavaScript. This variable is easy to use and also available across the entire length of the JavaScript code. Mainly, the var keyword is used whether to declare a global or local variable.

13. What is closure in JavaScript ?

A closure is a JavaScript function defined inside another function. And that’s why it gets a special privilege to access three types of scope which are as follows.

Internal Scope, i.e., the variables defined between its curly brackets

Outer Function Scope, i.e., the variables of the enclosing function

Global Scope, i.e., variables defined as globals

Code example describing closure by adding a function inside another function.

function outerFunc(arg1, arg2) {
​var param = “I’m closure. “;
// Inner function accessing outer function variables and parameter​s
​function innerFunc() {
​ return arg1 + arg2 + ” ” + param;
}
​ ​return innerFunc();
}
outerFunc(“arg1”, “arg2”);

14.  Which company developed JavaScript ?

Netscape company had developed the JavaScript Programming Language.

15. Difference between undefined and not defined.

var x;
console.log(x);

Now in the console, we will get a message x is ‘undefined’ which means the variable is declared and memory is created but the value is not assigned to it.

console.log(y);

In this case, you will get a message like ‘not defined’ because the variable y is not created, and memory is not allocated for it and we try to reference the variable.

16. What is the use of typeof operator ?

The typeof is a unary operator which means it takes a single operand in a statement or expression, it is used to check the data type of its operand in the form of a string.

var x= 20;
console.log(typeof (x))

It will print number in the console.

var x = 20;
console.log(typeof (x) == ‘number’ )

From the above code if the typeof x is number, so from the expression it will print true in the console.

17. What is the instanceof operator ?

instanceof operator checks whether the object is a instance of a class or not.

function Continents(name){this.name=name};
var continents = new Contients(“Asia”);
console.log(country instanceof Country) // return true
It will also consider inheritance
let fruit = [‘apple’, ‘orange’, ‘mango’];
console.log(fruit instanceof Array); // prints true in console
console.log(fruit instanceof Object); // prints true in console

fruit  is an array, but is also belongs to object, because array prototypal inherits from objects.

18. How to create array in JavaScript ?

Arrays are used to store various values in the single variables.

var  fruits = [“Apple”, “Orange”, “Mango”]

By using new keyword:

var fruits = new array(“Apple”, “Orang”, “Mango”)

19. Explain String in JavaScript ?

The group of character or textual data is called string, in JavaScript, there is no separate type for the character, even a single character will be stored as a string. In JavaScript, the string can be enclosed with single quotes or double quotes.

var  str = ‘hello’;
console.log(str) // print hello

20. Difference between search() and indexOf().

search()indexOf()
It is used to find a specified value and returns the position of the match, the value can be a string or regular expression.It is used to find a specified value and returns the position of the match, the value should be a string, it won’t accept a regular expression
var m = /g/var m = /n/
var str = “orange”;str.search(m) // return 4var str = “mango”;str.indexOf(m) // return -1

21. Difference between indexOf() and lastIndexOf().

indexOf()lastIndexOf()
It will return the index of the first occurrence of specific text in a string.It will return the index of the last occurrence of specific text in a string
var str= ‘Hello World learning javascript’;str.indexOf(‘learning’) // return 12var str= ‘Hello World learning JavaScript’;str.lastIndexOf(‘learning’) // return 12

22. Difference between Array and Object.

ArrayObject
The array uses the numbered indexes to access the element in it.The object uses the named indexes to access the members in it.
You should use an array when you want the element name to be number.You should use an object when you want the element name to be a string.
It is an ordered collectionIt is a collection of unorder properties

23. Difference between substr() and substring().

substr()substring()
It is used to return the characters in a string beginning at the specified index and returns the number of characters based on length providedIt is used to return the characters in a string beginning at the specified index and returns the number of characters based on length provided-1
var x = “world”;console.log((x.substr(1,4)== “orld”) // return  truevar x=”world”;console.log((x.substring(1,4)==”orld”)) // return false
var x=”world”;console.log((x.substring(1,5)==”orld”)) // return true 

24. What is destructuring assignment?

The destructuring assignment is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables. Let’s get the month values from an array using destructuring assignment

var [one, two, three] = [‘JAN’, ‘FEB’, ‘MARCH’];
console.log(one); // “JAN”
console.log(two); // “FEB”
console.log(three); // “MARCH”
and you can get user properties of an object using destructuring assignment,
var {name, age} = {name: ‘John’, age: 32};
console.log(name); // John
console.log(age); // 32

25. What are default values in destructuring assignment?

A variable can be assigned a default value when the value unpacked from the array or object is undefined during destructuring assignment. It helps to avoid setting default values separately for each assignment. Let’s take an example for both arrays and object usecases, Arrays destructuring:

var x, y, z;
[x=2, y=4, z=6] = [10];
console.log(x); // 10
console.log(y); // 4
console.log(z); // 6
Objects destructuring:
var {x=2, y=4, z=6} = {x: 10};
console.log(x); // 10
console.log(y); // 4
console.log(z); // 6

26. What are typed arrays?

Typed arrays are array-like objects from ECMAScript 6 API for handling binary data. JavaScript provides 8 Typed array types,

Int8Array: An array of 8-bit signed integers

Int16Array: An array of 16-bit signed integers

Int32Array: An array of 32-bit signed integers

Uint8Array: An array of 8-bit unsigned integers

Uint16Array: An array of 16-bit unsigned integers

Uint32Array: An array of 32-bit unsigned integers

Float32Array: An array of 32-bit floating point numbers

Float64Array: An array of 64-bit floating point numbers

For example, you can create an array of 8-bit signed integers as below

const a = new Int8Array();
// You can pre-allocate n bytes
const bytes = 1024
const a = new Int8Array(bytes)

27. What is collation ?

Collation is used for sorting a set of strings and searching within a set of strings. It is parameterized by locale and aware of Unicode. Let’s take comparision and sorting features,

Comparison:

var list = [ “ä”, “a”, “z” ]; // In German,  “ä” sorts with “a” Whereas in Swedish, “ä” sorts after “z”
var l10nDE = new Intl.Collator(“de”);
var l10nSV = new Intl.Collator(“sv”);
console.log(l10nDE.compare(“ä”, “z”) === -1); // true
console.log(l10nSV.compare(“ä”, “z”) === +1); // true

Sorting:

var list = [ “ä”, “a”, “z” ]; // In German,  “ä” sorts with “a” Whereas in Swedish, “ä” sorts after “z”
var l10nDE = new Intl.Collator(“de”);
var l10nSV = new Intl.Collator(“sv”);
console.log(list.sort(l10nDE.compare)) // [ “a”, “ä”, “z” ]
console.log(list.sort(l10nSV.compare)) // [ “a”, “z”, “ä” ]

28. What is an arrow function ?

The arrow function will support in JavaScript only after ES6 or above, it is a short way to write function expression. The conventional way of writing a function

function sub(a, b) {
return a-b;
}
console.log(sub(10,5)) //5
Using arrow function
sub = (a,b) => {
return a – b
}
console.log(sub(10,5));//5

29. What is ArrayBuffer?

An ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. You can create it as below,

let buffer = new ArrayBuffer(16); // create a buffer of length 16
alert(buffer.byteLength); // 16
To manipulate an ArrayBuffer, we need to use a “view” object.
//Create a DataView referring to the buffer
 let view = new DataView(buffer);

30. Define common error which occurs in JavaScript.

In general, there are 3 types of error we find in JS which are as follow.

Runtime error: this is the outcome of the misuse of the commands within the HTML language

Load tie error: this is syntax error and is generated dynamically

Logical error: this error occurs when the logic of the functions are badly performed.

31. Is JavaScript support Automatic type conversion ?

Automatic type conversion is supported by javascript and usually, the developers of javascript use the automatic type conversion method.

32. What is BOM and DOM in JavaScript ?

BOM- BOM is a Browser Object Model, in which the window object is supported by all the browsers. The JavaScript objects, variables and functions also become the members of the window object. This model deals with the objects of browsers like location, navigator, history, and screen.

DOM- DOM is a Document Object Model in a JavaScript helps to access document and HTML elements. When a web page is loaded the browser creates a DOM for the page. All the objects on the page all arranged in an order.

33. What is prototype chain ?

Prototype chaining is used to build new types of objects based on existing ones. It is similar to inheritance in a class based language. The prototype on object instance is available through Object.getPrototypeOf(object) or proto property whereas prototype on constructors function is available through object.prototype.

34. Difference between Call, Apply and Bind.

Call: The call() method invokes a function with a given this value and arguments provided one by one.

var employee1 = {firstName: ‘Raj’, lastName: ‘Mehta’’};
var employee2 = {firstName: ‘Abhishek’, lastName: ‘Khanna’};
function invite(greeting1, greeting2) {
    console.log(greeting1 + ‘ ‘ + this.firstName + ‘ ‘ + this.lastName+ ‘, ‘+ greeting2);
}
invite.call(employee1, ‘Hello’, ‘How are you?’); // Hello Raj Mehta, How are you?
invite.call(employee2, ‘Hello’, ‘How are you?’); // Hello Abhishek Khanna, How are you?

Apply: Invokes the function and allows you to pass in arguments as an array

var employee1 = {firstName: ‘Raj’, lastName: ‘Mehta’};
var employee2 = {firstName: ‘Abhishek’, lastName: ‘Khana’};
function invite(greeting1, greeting2) {
    console.log(greeting1 + ‘ ‘ + this.firstName + ‘ ‘ + this.lastName+ ‘, ‘+ greeting2);
}
invite.apply(employee1, [‘Hello’, ‘How are you?’]); // Hello Raj Mehta, How are you?
invite.apply(employee2, [‘Hello’, ‘How are you?’]); // Hello Abhishek Khana, How are you?

35. What is JSON and its common operations ?

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 and it is basically just a text file with an extension of .json, and a MIME type of application/json Parsing: Converting a string to a native object

JSON.parse(text)

Stringification:converting a native object to a string so it can be transmitted across the network

JSON.stringify(object)

36. What is the purpose of array slice method ?

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. 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]

37. What is the purpose of array splice method ?

The splice() method is used either adds/removes items to/from an array, and then returns the removed item. The first argument specifies the array position for insertion or deletion whereas the option 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]

38. How do you compare Object and Map?

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 are Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive.

The keys in Map are ordered while keys added to object are not. Thus, when iterating over it, a Map object returns keys in 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 the map that could collide with your keys if you’re not careful. As of ES5 this can be bypassed by using map = Object.create(null), but this is seldom done.

A Map may perform better in scenarios involving frequent addition and removal of key pairs.

39. What is the difference between == and === operators?

JavaScript provides both strict(===, !==) and type-converting(==, !=) equality comparison. The strict operators takes 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 but null==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
[]==[] or []===[] //false, refer different objects in memory
{}=={} or {}==={} //false, refer different objects in memory

40. What are lambda or arrow functions?

An arrow function is a shorter syntax for a function expression and does not have its own this, arguments, super, or new.target. These function are best suited for non-method functions, and they cannot be used as constructors.

41. What is a first class function?

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);

42. What is a first order function?

First-order function is a function that doesn’t accept other function as an argument and doesn’t return a function as its return value.

const firstOrder = () => console.log ('Iam a first order functionn!');

43. What is a higher order function?

Higher-order function is a function that accepts other function as an argument or returns a function as a return value.

const firstOrderFunc = () => console.log (‘Hello I’am a First order function’);
const higherOrder = ReturnFirstOrderFunc => ReturnFirstOrderFunc ();
higherOrder (firstOrderFunc);

44. What is a unary function?

Unary function (i.e. monadic) is a function that accepts exactly one argument. Let us take an example of unary function. It stands for single argument accepted by a function.

const unaryFunction = a => console.log (a + 10); //Add 10 to the given argument and display the value

45. What is currying function?

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, a n-ary function turns it 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;
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

46. What is a pure function?

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 6
console.log (numberArray); // returns [6]
console.log (pureAddNumber (7) (numberArray)); // returns [6, 7]
console.log (numberArray); // returns [6]

47. What is Hoisting?

Hoisting is a JavaScript mechanism where variables and function declarations 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’;

48. What is a service worker?

A Service worker is basically a script (JavaScript file) that runs in background, separate from a web page and provide 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.

49. What is indexedDB ?

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.

50. What is a post message ?

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).

51. What is a Cookie?

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=raj";

52. Why do you need a Cookie ?

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, user profile can be stored in a cookie.

Next time the user visits the page, the cookie remembers user profile.

53. What are the options in a cookie ?

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=raj 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=raj path=/services";

54.  How do you delete a cookie ?

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=/;";

55. Why do you need web storage ?

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 recommended approach than Cookies.

56. How to check web storage browser support ?

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..
}

57. What is a promise ?

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 would be as below

const promise = new Promise(function(resolve, reject) {
  // promise description
})

58. Why do you need a promise ?

Promises are used to handle asynchronous operations. They provide an alternative approach for callbacks by reducing the callback hell and writing the cleaner code.

59. What is a callback function ?

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);

60. What is a callback hell?

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(){
                 ….
            });
        });
    });
});

61. What is a strict mode in javascript ?

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.

62. How do you declare strict mode ?

The strict mode is declared by adding “use strict”; to the beginning of a script or a function. If declare 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
}

63. What is eval ?

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('2 + 2')); //  4

64. Difference between window and document.

WindowDocument
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 pageYou can access it via window.document or document.
It has methods like alert(), confirm() and properties like document, locationIt provides methods like getElementById, getElementByTagName, createElement etc

65. How do you access history in javascript ?

The window.history object contains the browsers 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()
}

66. What is NaN ?

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

67. What is NaN property ?

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”)

68. What is the purpose of isfinite function ?

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

69. What is 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.

70. What is same-origin policy ?

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).

71. What is even delegation ?

Event delegation is a technique for listening to events where you delegate a parent element as the listener for all of the events that happen inside it. For example, if you wanted to detect field changes 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);

72. What is the purpose of clearTimeout method ?

The clearTimeout() function is used in javascript to clear the timeout which has been set by setTimeout()function before that. i.e, The return value of setTimeout() function is stored in a variable and it’s passed into the clearTimeout() function to clear the timer. For example, the below setTimeout method is used to display the message after 3 seconds. This timeout can be cleared by clearTimeout() method.

<script>
var msg;
function greeting() {
   alert(‘Good morning’);
}
function start() {
  msg =setTimeout(greeting, 3000);
}
function stop() {
    clearTimeout(msg);
}
</script>

73. How do you validate an email in javascript?

You can validate an email in javascript using regular expressions. It is recommended to do validations on the server side instead 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());
}

74. How do you get the current url with javascript?

You can use window.location.href expression to get the current url path and you can use the same expression for updating the URL too. You can also use document.URL for read-only purpose but this solution has issues in FF.

console.log('location.href', window.location.href); // Returns full URL

75. What are the various url properties of location object?

The below Location object properties can be used to access URL components of the page,

  • href – The entire URL
  • protocol – The protocol of the URL
  • host – The hostname and port of the URL
  • hostname – The hostname of the URL
  • port – The port number in the URL
  • pathname – The path name of the URL
  • search – The query portion of the URL
  • hash – The anchor portion of the URL

76. What is an app shell model ?

An application shell (or app shell) architecture is one way to build a Progressive Web App that reliably and instantly loads on your users’ screens, similar to what you see in native applications. It is useful for getting some initial HTML to the screen fast without a network.

77. What is the way to find the number of parameters expected by a function ?

You can use function.length syntax to find the number of parameters expected by a function. Let’s take an example of sum 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.

78. What is polyfill ?

A polyfill is a piece of JS code used to provide modern functionality on older browsers that do not natively support it. For example, Silverlight plugin polyfill can be used to mimic the functionality of an HTML Canvas element on Microsoft Internet Explorer 7.

79. How to generate random integers ?

You can use Math.random() with Math.floor() to return random integers. For example, if you want generate random integers between 1 to 10, the multiplication factor should be 10,

Math.floor(Math.random() * 10) + 1;     // returns a random integer from 1 to 10
Math.floor(Math.random() * 100) + 1;     // returns a random integer from 1 to 100

80. What is tree shaking?

Tree shaking is a form of dead code elimination. It means that unused modules will not be included in the bundle during the build process and for that it relies on the static structure of ES2015 module syntax,( i.e. import and export). Initially this has been popularized by the ES2015 module bundler rollup.

81. What is a Regular Expression?

A regular expression is a sequence of characters that forms a search pattern. You can use this search pattern for searching data in a text. These can be used to perform all types of text search and text replace operations. Let’s see the syntax format now,

/pattern/modifiers;

For example, the regular expression or search pattern with case-insensitive username would be,

/John/i

82. What would be the result of 1+2+’3′?

The output is going to be 33. Since 1 and 2 are numeric values, the result of first two digits is going to be a numeric value 3. The next digit is a string type value because of that the addition of numeric value 3 and string type value 3 is just going to be a concatenation value 33.

83. How do you get the image width and height using JS?

You can programmatically get the image and check the dimensions(width and height) using Javascript.

var img = new Image();
img.onload = function() {
  console.log(this.width + ‘x’ + this.height);
}
img.src = ‘http://www.google.com/intl/en_ALL/images/logo.gif’;

84. How to convert date to another timezone in javascript ?

You can use toLocaleString() method to convert date 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

85. What is a freeze method ?

The freeze() method is used to freeze an object. Freezing an object does’nt allow adding new properties to an object,prevents from 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

86. What is the purpose of freeze method ?

Below are the main benefits of using freeze method,

It is used for freezing objects and arrays.

It is used to make an object immutable.

87. What is a Weak set ?

WeakSet is used to store a collection of weakly(weak references) held objects. The syntax would be as follows,

new WeakSet([iterable]);
Let’s see the below example to explain it’s behavior,
var ws = new WeakSet();
var user = {};
ws.add(user);
ws.has(user);    // true
ws.delete(user); // removes user from the set
ws.has(user);    // false, user has been removed

88. Difference between WeakSet and Set ?

The main difference is that references to objects in Set are strong while references to objects in WeakSet are weak. i.e, An object in WeakSet can be garbage collected if there is no other reference to it. Other differences are,

Sets can store any value Whereas WeakSets can store only collections of objects

WeakSet does not have size property unlike Set

WeakSet does not have methods such as clear, keys, values, entries, forEach.

WeakSet is not iterable.

89. List down the methods of collection available in WeakSet ?

Below are the list of methods available on WeakSet,

add(value): A new object is appended with the given value to the weakset

delete(value): Deletes the value from the WeakSet collection.

has(value): It returns true if the value is present in the WeakSet Collection, otherwise it returns false.

length(): It returns the length of weakSetObject Let’s see the functionality of all the above methods in an example,

var weakSetObject = new WeakSet();
var firstObject = {};
var secondObject = {};
// add(value)
weakSetObject.add(firstObject);
weakSetObject.add(secondObject);
console.log(weakSetObject.has(firstObject)); //true
console.log(weakSetObject.length()); //2
weakSetObject.delete(secondObject);

90. What is WeakMap ?

The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. In this case, keys must be objects and the values can be arbitrary values. The syntax is looking like as below,

new WeakMap([iterable])
Let's see the below example to explain it's behavior,
 var ws = new WeakMap();
 var user = {};
 ws.set(user);
 ws.has(user);    // true
 ws.delete(user); // removes user from the map
 ws.has(user);    // false, user has been removed

91. Difference between WeakMap and Map.

The main difference is that references to key objects in Map are strong while references to key objects in WeakMap are weak. i.e, A key object in WeakMap can be garbage collected if there is no other reference to it. Other differences are,

Maps can store any key type Whereas WeakMaps can store only collections of key objects

WeakMap does not have size property unlike Map

WeakMap does not have methods such as clear, keys, values, entries, forEach.

WeakMap is not iterable.

92. List down the collection of methods available on WeakMap?

Below are the list of methods available on WeakMap,

set(key, value): Sets the value for the key in the WeakMap object. Returns the WeakMap object.

delete(key): Removes any value associated to the key.

has(key): Returns a Boolean asserting whether a value has been associated to the key in the WeakMap object or not.

get(key): Returns the value associated to the key, or undefined if there is none. Let’s see the functionality of all the above methods in an example,

var weakMapObject = new WeakMap();
var firstObject = {};
var secondObject = {};
// set(key, value)
weakMapObject.set(firstObject, ‘John’);
weakMapObject.set(secondObject, 100);
console.log(weakMapObject.has(firstObject)); //true
console.log(weakMapObject.get(firstObject)); // John
weakMapObject.delete(secondObject);

93. What is an anonymous function ?

An anonymous function is a function without a name! Anonymous functions are commonly assigned to a variable name or used as a callback function. The syntax would be as below,

function (optionalParameters) {
  //do something
}
const myFunction = function(){ //Anonymous function assigned to a variable
  //do something
};
[1, 2, 3].map(function(element){ //Anonymous function used as a callback function
  //do something
});
Let’s see the above anonymous function in an example,
var x = function (a, b) {return a * b};
var z = x(5, 10);
console.log(z); // 50

94.What are the advantages of Getters and Setters?

Below are the list of benefits of Getters and Setters,

They provide simpler syntax

They are used for defining computed properties, or accessors in JS.

Useful to provide equivalence relation between properties and methods

They can provide better data quality

Useful for doing things behind the scenes with the encapsulated logic.

95. What is an Intl object?

The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. It provides an access to several constructors and language sensitive functions.

96. What are the properties of Intl object?

Below are the list of properties available on Intl object,

Collator: These are the objects that enable language-sensitive string comparison.

DateTimeFormat: These are the objects that enable language-sensitive date and time formatting.

ListFormat: These are the objects that enable language-sensitive list formatting.

NumberFormat: Objects that enable language-sensitive number formatting.

PluralRules: Objects that enable plural-sensitive formatting and language-specific rules for plurals.

RelativeTimeFormat: Objects that enable language-sensitive relative time formatting.

97. What is a comma operator?

The comma operator is used to evaluate each of its operands from left to right and returns the value of the last operand. This is totally different from comma usage within arrays, objects, and function arguments and parameters. For example, the usage for numeric expressions would be as below,

var x = 1;
x = (x++, x);
console.log(x); // 2

98. Difference between javascript and typescript.

Featuretypescriptjavascript
Language paradigmObject oriented programming language Scripting Language
Typing supportSupport static typingIt has dynamic typing
ModulesSuppportedNot Supported
InterfaceIt has interfaces conceptDoesn’t support interfaces
Optional parametersFunctions support optional parametersNo support of optional parameters for functions

99. How to perform form validation using javascript ?

JavaScript can be used to perform HTML form validation. For example, if form field is empty, the function needs to notify, and return false, to prevent the form being submitted. Lets’ perform user login in an html form,

<form name=”myForm” onsubmit=”return validateForm()” method=”post”>
User name: <input type=”text” name=”uname”>
<input type=”submit” value=”Submit”>
</form>

And the validation on user login is below,

function validateForm() {
  var x = document.forms[“myForm”][“uname”].value;
  if (x == “”) {
    alert(“The username shouldn’t be empty”);
    return false;
  }
}

100. How to get the value from get parameter ?

The new URL() object accepts url string and searchParams property of this object can be used to access the get parameters. Remember that you may need to use polyfill or window.location to access the URL in older browsers(including IE).

let urlString = “http://www.some-domain.com/about.html?x=1&y=2&z=3”; //window.location.href
let url = new URL(urlString);
let parameterZ = url.searchParams.get(“z”);
console.log(parameterZ); // 3

101. What is JQuery ?

jQuery is a popular cross-browser JavaScript library that provides Document Object Model (DOM) traversal, event handling, animations and AJAX interactions by minimizing the discrepancies across browsers. It is widely famous with its philosophy of “Write less, do more”. For example, you can display welcome message on the page load using jQuery as below,

$(document).ready(function(){ // It selects the document and apply the function on page load
    alert(‘Welcome to jQuery world’);
});

102. How to set the cursor to wait ?

The cursor can be set to wait in JavaScript by using the property “cursor”. Let’s perform this behavior on page load using the below function.

function myFunction() {
window.document.body.style.cursor = “wait”;
}
and this function invoked on page load
<body onload=”myFunction()”>

Related Articles

Core Java

1. What are primitive types in Java ? byte, short, int, long, float, double, char, boolean… 2. What are tokens? Name the 5 types of tokens available in Java with an example…

Hackerearth-Java

     1. Challenge : Welcome to Java! Welcome to the world of Java! In this challenge, we practice printing to stdout. The code stubs…

Advance Java

1. Write an Example Snippet to Connect Java Application with mysql database. 2. Wap to get the object of ResultSetMetaData. The getMetaData() method of ResultSet…

Responses

Your email address will not be published. Required fields are marked *

KodNest Training New Batch is starting on 5th October 2020. Attend one week free demo classes.Register Now

New Report

Close