What is JavaScript?

JavaScript is a lightweight programming language. JavaScript is a platform-independent,event-driven, interpreted client-side scripting language developed by Netscape Communications Corp. and Sun Microsystems.
JavaScript is a general-purpose programming language designed to let programmers of all skill levels control the behavior of software objects. The language is used most widely today in Web browsers whose software objects tend to represent a variety of HTML elements in a document and the document itself.
But the language is used with other kinds of objects in other environments. For example, Adobe Acrobat Forms uses JavaScript as its underlying scripting language to glue together objects that are unique to the forms generated by Adobe Acrobat.
Therefore, it is important to distinguish JavaScript, the language, from the objects it can communicate with in any particular environment.
When used for Web documents, the scripts go directly inside the HTML documents and are downloaded to the browser with the rest of the HTML tags and content.
The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers.

How is JavaScript different from Java?

JavaScript was developed by Brendan Eich of Netscape; Java was developed at Sun Microsystems. While the two languages share some common syntax, they were developed independently of each other and for different audiences. Java is a full-fledged programming language tailored for network computing; it includes hundreds of its own objects, including objects for creating user interfaces that appear in Java applets (in Web browsers) or standalone Java applications. In contrast, JavaScript relies on whatever environment it's operating in for the user interface, such as a Web document's form elements.
JavaScript was initially called LiveScript at Netscape while it was under development. A licensing deal between Netscape and Sun at the last minute let Netscape plug the "Java" name into the name of its scripting language. Programmers use entirely different tools for Java and JavaScript. It is also not uncommon for a programmer of one language to be ignorant of the other. The two languages don't rely on each other and are intended for different purposes. In some ways, the "Java" name on JavaScript has confused the world's understanding of the differences between the two. On the other hand, JavaScript is much easier to learn than Java and can offer a gentle introduction for newcomers who want to graduate to Java and the kinds of applications you can develop with it.

What is the official JavaScript website?

This is a trick question used by interviewers to evaluate the candidate’s knowledge of JavaScript. Most people will simply say javascript.com is the official website.

The truth is- there is no official website for Javascript you can refer to. It was developed by Brendan Eich for Netscape. It was based on the ECMAScript language standard; ECMA-262 being the official JavaScript standard.

What’s relationship between JavaScript and ECMAScript?

ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3.

What are the various datatypes in javascript?

Below are the some datatypes in javascript
Number
String
Boolean
Function
Object
Null
Undefined

What boolean operators does JavaScript support?

&&, || and !

What is negative infinity?

It’s a number in JavaScript, derived by dividing negative number by zero

Is it possible to check if a variable is an object?

Yes, it is possible to do so. The following piece of code will help achieve the same.

if(abc && typeof abc === "object") {
  console.log('abc is an object and does not return null value');
}

 

What is the difference between “==” and “===”?

While “==” checks only for equality, “===” checks for equality as well as the type.

Below are some examples

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

 

What is the difference between undefined value and null value?

undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value.

Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
Unassigned variables are initialized by JavaScript with a default value of undefined. JavaScript never sets a value to null. That must be done programmatically.

Can you explain what isNaN function does?

isNaN function will check an argument and return TRUE (1) if the argument does not seem to be a number.
NaN is a short form of Not a Number. Since NaN always compares unequal to any number, including NaN, it is usually used to indicate an error condition for a function that should return a valid number. When a string or something else is being converted into a number and that cannot be done, then we get to see NaN.

Do you know what value will be printed on the console when the following piece of code will be executed?

var x = 10;
function test()
{
	var x = 20;
}

test();
console.log(x);

 

If your answer is 10, then you are right. Here the variable ‘x’ declared (and of course initialized) outside the function ‘test’ has a global scope and that’s why it is accessible anywhere in this scope globally. However, the one declared and initialized inside the ‘test’ function can be accessed only inside that function. So the below code snippet will print 20 on the console upon execution.

var x = 10;

function test()
{
	if (x > 20) {
		var x = 50;
	}

	console.log(x);
}

test();

Guess the output.

If you have guessed 10 following the scoping logic discussed in the previous examples, then you are unfortunate as 10 is not the correct answer. This time it will print ‘undefined’ on the console. This is because of the combined effect of variable scoping and variable hoisting.

What was the original name of JavaScript when it was discovered?

"Mocha" is the correct answer. When JavaScript was discovered, it was initially called Mocha, then renamed to LiveScript, and finally to JavaScript when Netscape and Sun did a license agreement. It was named JavaScript because, at that time, it was made as a scripting language complementary to Java.

What is the difference between setImmediate and setTimeout?

SetTimeOut is used to queue the events in such a way that the event will be processed once all the ongoing and scheduled events are completed, where the actual time cannot be estimated.
However, SetImmediate is used to queue the events in such a manner that the event is queued just after the last event and if there is no scheduled event, it will be processed instantly.

What is Hoisting in JavaScript?

In JavaScript, Hoisting is the default behavior of moving all the declarations at the top of the scope before code execution. Basically, it gives us an advantage that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.
It allows us to call functions before even writing them in our code.

Note: JavaScript only hoists declarations, not the initialisations.

Let us understand what exactly this is:
The following is the sequence in which variable declaration and initalisation occurs.

Declaration –> Initialisation/Assignment –> Usage

// Variable lifecycle
let a;        // Declaration
a = 100;      // Assignment
console.log(a);  // Usage

 

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.

  1. The keys of an Object are Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. A Map may perform better in scenarios involving frequent addition and removal of key pairs.

 

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 functions are best suited for non-method functions, and they cannot be used as constructors.

What is a first class functions?

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

 

What is a first-order function?

The 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!");

 

What is a higher order function?

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

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

 

What is a unary function?

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

 

What is the 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;
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.

 

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 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 Immutability concept of ES6 by giving preference to const over let usage.

 

How do you decode or encode a URL in JavaScript?

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 use encodeURIComponent().

let uri = "employeeDetails?name=john&occupation=manager";
let encoded_uri = encodeURI(uri);
let decoded_uri = decodeURI(encoded_uri);

 

What are closures in javascript?

A closure is the combination of a function and the 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. 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.

 

What are modules in JavaScript?

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

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.

Why do you need strict mode in javascript?

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.

How do you declare strict mode in javascript?

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
}

 

What is null value in javascript?

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

 

What is eval in javascript?

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

 

What are global variables in javascript?

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

 

What are the problems with global variables in javascript?

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.

How many keywords are there in JavaScript to declare variables or constants?

There are 3 ways / keywords to declare variables or constants, those are:

var
let
const

Which JavaScript method is used to call a function (a callback function) once for each array element?

The JavaScript method forEach() is used to call a function (a callback function) once for each array element.

What will be the output of the following JavaScript code?

try{
    const cars = {  
        company: 'Honda'
    };  
    
    Object.seal(cars);
    delete cars.company;
    document.write(cars.company);  
}
catch (err){
    document.write(err.message);
}

 

In the above JavaScript code, we have sealed the object and the seal property does not allow the object to be deleted. Hence, the property company will not be deleted.

What will be the output of the following JavaScript code?

<script>
	var x = 10 + 20 * 5;
	document.getElementById("tes").innerHTML = x;
</script>

The output of the above statement will be 110.
In the above code, the expression is 10 + 20 * 5. The precedence of multiplication operator (*) is higher than the addition operator (+). This 20 *5 will evaluate first.