Table of Contents
JavaScript, made by Brendan Eich in 1995, is one of the foremost broadly utilized web advancement dialects. It was planned to construct energetic web pages at first. A script could be a JS program which will be included to the HTML of any web page. When the page loads, these scripts execute consequently.
A dialect that was initially outlined to construct energetic web pages may presently be run on the server and on nearly any gadget that has the JavaScript Engine installed.
After HTML and CSS, JavaScript is the third greatest web innovation. JavaScript may be a scripting language which will be utilized to build online and versatile apps, web servers, diversions, and more. JavaScript is an object-oriented programming dialect that’s used to produce websites and applications. It was made with the purposeful of being utilized in a browser. Indeed nowadays, the server-side form of JavaScript known as Node.js may be utilized to make online and portable apps, real-time applications, online gushing applications, and videogames. Javascript systems, frequently known as inbuilt libraries, may be utilized to develop desktop and versatile programs. Engineers may spare a parcel of time on dull programming occupations by utilizing these code libraries, permitting them to center on the generation work of development.
Experience the power of our full stack development course with a free demo – enroll now!
JavaScript Interview Questions for Freshers
1. What are the different data types present in javascript?
1. Primitive types
- String – It represents a string of characters and is written with double quotes. A string can be represented with either single quotes or double quotes.
Example :
var str = "Vivek Singh Bisht"; //using double quotes
var str2 = 'John Doe'; //using single quotes
- Number – It represents a number and can be written with or without decimal places.
Example :
var x = 3; //without decimal
var y = 3.6; //with decimal
- BigInt -This data type is used to store numbers that exceed the limits of the Number data type. It can store large integers and is represented by adding “n” to an integer.
Example :
var bigInteger = 234567890123456789012345678901234567890;
- Boolean – It represents a logical entity and can only have two values: true or false. Booleans are often used for conditional testing.
Example :
var a = 2;
var b = 3;
var c = 2;
(a == b) // returns false
(a == c) //returns true
- Undefined – When a variable is declared but not assigned, it has an undefined value and its type is also undetermined.
Example :
var x; // value of x is undefined
var y = undefined; // we can also set the value of a variable as undefined
- Null – It represents a value that does not exist or is invalid.
Example :
var z = null;
- Symbol – This is a new data type introduced in the ES6 version of javascript. It is used to store an anonymous and unique value.
Example :
var symbol1 = Symbol('symbol');
- typeof of primitive types :
typeof "John Doe" // Returns "string"
typeof 3.14 // Returns "number"
typeof true // Returns "boolean"
typeof 234567890123456789012345678901234567890n // Returns bigint
typeof undefined // Returns "undefined"
typeof null // Returns "object" (kind of a bug in JavaScript)
typeof Symbol('symbol') // Returns Symbol
2. Non-primitive types
- Primitive data types can only store a single value.
To store multiple complex values, non-primitive data types are used. - Purpose – Used to store collected data.
- Example:
// Collection of data in key-value pairs
var obj1 = {
x: 43,
y: "Hello world!",
z: function(){
return this.x;
}
}
// Collection of data as an ordered list
var array1 = [5, "Hello", true, 4.1];
2. Explain Hoisting in javascript.
Example 1:
hoistedVariable = 3;
console.log(hoistedVariable); // outputs 3 even when the variable is declared after it is initialized
var hoistedVariable;
Example 2:
hoistedFunction(); // Outputs " Hello world! " even when the function is declared after calling
function hoistedFunction(){
console.log(" Hello world! ");
}
Example 3:
// Hoisting takes place in the local scope as well
function doSomething(){
x = 33;
console.log(x);
var x;
}
doSomething(); // Outputs 33 since the local variable “x” is hoisted inside the local scope
Note – Variable initializations are not hoisted, only variable declarations are hoisted:
var x;
console.log(x); // Outputs "undefined" since the initialization of "x" is not hoisted
x = 23;
Note – To avoid hoisting, you can run javascript in strict mode by using “use strict” on top of the code:
"use strict";
x = 23; // Gives an error since 'x' is not declared
var x;
3. Why do we use the word “debugger” in javascript?
The difference between the two operators is that “==” is used to compare values while “===” is used to compare both value and type.Example:
var x = 2;
var y = "2";
(x == y) // Returns true since the value of both x and y is the same
(x === y) // Returns false since the typeof x is "number" and typeof y is "string"
5. Difference between var and let keyword in javascript.
- Since the beginning, the keyword ‘var’ has been used in JavaScript programming whereas the keyword ‘let’ was added in 2015.
- The keyword ‘Var’ has functional scope .
- At any place in the function, the variable specified with var can be accessed but in ‘let’, the scope of the variable declared with the ‘let’ keyword is limited to the block in which it is declared .
- Let’s start with block scope. In ECMAScript 2015, let and const are hoisted but not initialized.
- Referencing a variable in a block before declaring it will result in a ReferenceError because the variable is in a “temporary dead zone” from the beginning of the block until the declaration is processed.
6. Explain implicit type coercion in javascript.
Implicit type coercion in javascript is to automatically convert a value from one data type to another. This happens when the operands of an expression have different data types.
- String coercion
String coercion occurs when using the ‘ + ‘ operator. When a number is added to a string, the number type is always converted to string type.
var x = 3;
var y = "3";
x + y // Returns "33"
Example 2:
var x = 24;
var y = "Hello";
x + y // Returns "24Hello";
Note – ‘ + ‘ operator when used to add two numbers, outputs a number. The same ‘ + ‘ operator when used to add two strings, outputs the concatenated string:
var name = "Vivek";
var surname = " Bisht";
name + surname // Returns "Vivek Bisht"
Let’s understand both the examples where we have added a number to a string,
When JavaScript sees that the operands of the expression x + y have different types (one is a number and one is a string), it converts the number to a string and then performs the operation. Since after conversion, both variables are of type string, the ‘ + ‘ operator creates the concatenated string “33” in the first example and “24Hello” in the second example.
Note – Type coercion also takes place when using the ‘ – ‘ operator, but the difference while using ‘ – ‘ operator is that, a string is converted to a number and then subtraction takes place.
var x = 3;
Var y = "3";
x - y //Returns 0 since the variable y (string type) is converted to a number type
- Boolean Coercion
Boolean coercion occurs using logical operators, ternary operators, if statements, and loop checking. To understand Boolean coercion in if statements and operators, we need to understand the values true and false.
Truthy values are those which will be converted (coerced) to true. Falsy values are those which will be converted to false.
All values except false, 0, 0n, -0, “”, null, undefined, and NaN are truthy values.
If statements:
Example:
var x = 0;
var y = 23;
if(x) { console.log(x) } // The code inside this block will not run since the value of x is 0(Falsy)
if(y) { console.log(y) } // The code inside this block will run since the value of y is 23 (Truthy)
- Logical operators:
Logical operators in JavaScript, unlike operators in other programming languages, do not return true or false. They always return one of the operands.
OR Operator ( | | ) – If the first value is true, the first value is returned. Otherwise, the second value is always returned.
AND Operator ( && ) – If both values are true, the second value is always returned. If the first value is false then the first value is returned or if the second value is false then the second value is returned.
Example:
var x = 220;
var y = "Hello";
var z = undefined;
x | | y // Returns 220 since the first value is truthy
x | | z // Returns 220 since the first value is truthy
x && y // Returns "Hello" since both the values are truthy
y && z // Returns undefined since the second value is falsy
if( x && y ){
console.log("Code runs" ); // This block runs because x && y returns "Hello" (Truthy)
}
if( x || z ){
console.log("Code runs"); // This block runs because x || y returns 220(Truthy)
}
- Equality Coercion
Enforcing equality takes place when using the ‘==’ operator.
As we said The ‘ == ‘ operator compares values, not types.
Although the above statement is a simple way to explain the == operator, it is not entirely correct.
In fact, when using the ‘==’ operator, coercion takes place.
The ‘==’ operator converts two operands to the same type and then compares them.
Example:
var a = 12;
var b = "12";
a == b // Returns true because both 'a' and 'b' are converted to the same type and then compared. Hence the operands are equal.
Coercion does not take place when using the ‘===’ operator. Both operands are not converted to the same type in the case of ‘===’ operator.
Example:
var a = 226;
var b = "226";
a === b // Returns false because coercion does not take place and the operands are of different types. Hence they are not equal.
7. Is javascript a statically typed or a dynamically typed language?
var a = 23;
var a = "Hello World!";
isNaN("Hello") // Returns true
isNaN(345) // Returns false
isNaN('1') // Returns false, since '1' is converted to Number type which results in 0 ( a number)
isNaN(true) // Returns false, since true converted to Number type results in 1 ( a number)
isNaN(false) // Returns false
isNaN(undefined) // Returns true
9. Explain passed by value and passed by reference.
var x = 2;
In the above example, we have created a variable x and assigned it the value “2”. Behind the scenes, the “=” (assignment operator) allocates space in memory, stores the value “2” and returns the location of the allocated memory space. Hence, the variable x in the above code points to the memory space location instead of pointing directly to the value 2.
Assign operator behaves differently when dealing with primitive and non-primitive data types,
Assign operator dealing with primitive types:
var y = 234;
var z = y;
In the example above, the assignment operator knows that the value assigned to y is a primitive type (numeric type in this case), so when the second line of code runs, where the value of y is assigned to z, the operator The assignment operator takes the value of y (234) and allocates a new space in memory and returns the address. Therefore, variable z does not point to the location of variable y but points to a new location in memory.
var y = #8454; // y pointing to address of the value 234
var z = y;
var z = #5411; // z pointing to a completely new address of the value 234
// Changing the value of y
y = 23;
console.log(z); // Returns 234, since z points to a new address in the memory so changes in y will not effect z
From the above example, we can see that primitive data types when passed to another variable, are passed by value. Instead of just assigning the same address to another variable, the value is passed and new space of memory is created.
Assign operator dealing with non-primitive types:
var obj = { name: "Vivek", surname: "Bisht" };
var obj2 = obj;
In the above example, the assign operator directly passes the location of the variable obj to the variable obj2. In other words, the reference of the variable obj is passed to the variable obj2.
var obj = #8711; // obj pointing to address of { name: "Vivek", surname: "Bisht" }
var obj2 = obj;
var obj2 = #8711; // obj2 pointing to the same address
// changing the value of obj1
obj.name = "Akki";
console.log(obj2);
// Returns {name:"Akki", surname:"Bisht"} since both the variables are pointing to the same address.
From the above example, we can see that while passing non-primitive data types, the assigned operator directly passes the address (reference).
Therefore, non-primitive data types are always passed by reference.
9. What is an Immediately Invoked Function in JavaScript?
(function(){
// Do something;
})();
To understand IIFE, we need to understand the two sets of parentheses that are added while creating an IIFE :
The first set of parenthesis:
(function (){
//Do something;
})
When running javascript code, whenever the compiler sees the word “function”, it assumes that we are declaring a function in the code. Therefore, if we do not use the first set of parentheses, the compiler will throw an error because it thinks that we are declaring a function and according to the function declaration syntax, the function should always have a name.
function() {
//Do something;
}
// Compiler gives an error since the syntax of declaring a function is wrong in the code above.
To remove this error, we add the first set of parenthesis that tells the compiler that the function is not a function declaration, instead, it’s a function expression.
The second set of parenthesis:
(function (){
//Do something;
})();
From the definition of an IIFE, we know that our code should run as soon as it is defined. A function runs only when it is invoked. If we do not invoke the function, the function declaration is returned:
(function (){
// Do something;
})
// Returns the function declaration
Therefore to invoke the function, we use the second set of parenthesis.
10. What do you mean by strict mode in javascript and characteristics of javascript strict-mode?
- Developers do not allow duplicate arguments.
- In strict mode, you will not be able to use JavaScript keywords as parameters or function names.
- The ‘use strict’ keyword is used to set strict mode at the start of a script.
- Strict mode is supported by all browsers.
- Engineers will not be allowed to create global variables in “strict mode”.
11. Explain Higher Order Functions in javascript.
function higherOrder(fn) {
fn();
}
higherOrder(function() { console.log("Hello world") });
function higherOrder2() {
return function() {
return "Do something";
}
}
var x = higherOrder2();
x() // Returns "Do something"
12. What is the difference between exec () and test () methods in javascript?
test () and exec () are RegExp expression methods used in javascript.
- We will use exec () to search a string for a specific pattern and if it finds it, it returns the pattern directly; otherwise it will return “empty” result.
- We will use test() to find the string for a particular pattern. It will return the boolean value “true” when finding the given text, otherwise it will return “false”.
13. What are some advantages of using External JavaScript?
- It allows web designers and developers to collaborate on HTML and javascript files.
- We can reuse code.
- Very simple code readability in external javascript.
14. Mention some advantages of javascript.
- Javascript is also executed on the client side as well as the server side. There are many user interface frameworks that you can research and use. However, if you want to use JavaScript in the backend, you will need to learn NodeJS. It is currently the only JavaScript framework that can be used in the backend.
- Javascript is an easy language to learn.
- Websites are now more functional thanks to Javascript.
- For the end user, Javascript is fast enough
JavaScript Interview Questions for Experienced
1: Which of the following is a JavaScript framework/library?
1. What are arrow functions?
// Traditional Function Expression
var add = function(a,b){
return a + b;
}
// Arrow Function Expression
var arrowAdd = (a,b) => a + b;
Arrow functions are declared without the function keyword. If there is only one return expression, we do not need to use the return keyword in the arrow function, as in the example above. Additionally, for functions with only one line of code, curly braces { } can be omitted.
// Traditional function expression
var multiplyBy2 = function(num){
return num * 2;
}
// Arrow function expression
var arrowMultiplyBy2 = num => num * 2;
If the function takes in only one argument, then the parenthesis () around the parameter can be omitted as shown in the code above.
var obj1 = {
valueOfThis: function(){
return this;
}
}
var obj2 = {
valueOfThis: ()=>{
return this;
}
}
obj1.valueOfThis(); // Will return the object obj1
obj2.valueOfThis(); // Will return window/global object
Rather, it inherits its value from the parent scope, which is the window object in this case. Therefore, in the above code, obj2.valueOfThis() returns the window object.
2. What does prototype design model mean?
The prototype model creates different objects, but instead of returning uninitialized objects, it creates objects whose values are copied from a model – or template – object. Also known as the Attribute model, the Prototype model is used to create prototypes.
Introducing business objects with parameters that match database defaults is a good example of the usefulness of the Prototype pattern.
The default settings of the newly created business object will be stored in the prototype object. The Prototype Model is rarely used in traditional languages, however, it is used to develop new objects and models in JavaScript, a prototype language.
3. Difference between declaring variables with var, let and const.
Before the ES6 version of javascript, only the var keyword was used to declare variables. With the ES6 release, let and const keywords were introduced to declare variables.
keyword | const | let | var |
global scope | no | no | yes |
function scope | yes | yes | yes |
block scope | yes | yes | no |
can be reassigned | no | yes | yes |
Let’s understand the differences with examples:
var variable1 = 23;
let variable2 = 89;
function catchValues(){
console.log(variable1);
console.log(variable2);
// Both the variables can be accessed anywhere since they are declared in the global scope
}
window.variable1; // Returns the value 23
window.variable2; // Returns undefined
- Variables declared with the let keyword in the global scope behave exactly like variables declared with the var keyword in the global scope. Any variable declared in the global scope with the var keyword and the let keyword are accessible from any position in code. But there is a difference!
- Variables declared with the var keyword in the global scope will be added to the window/global object. Therefore, they are accessed using window.variableName.
- Although variables declared with the let keyword are not added to the global object, trying to access these variables using window.variableName will result in an error.
var vs let in functional scope
function varVsLetFunction(){
let awesomeCar1 = "Audi";
var awesomeCar2 = "Mercedes";
}
console.log(awesomeCar1); // Throws an error
console.log(awesomeCar2); // Throws an error
Variables are declared in a functional/local scope using var and let keywords behave exactly the same, meaning, they cannot be accessed from outside of the scope.
{
var variable3 = [1, 2, 3, 4];
}
console.log(variable3); // Outputs [1,2,3,4]
{
let variable4 = [6, 55, -1, 2];
}
console.log(variable4); // Throws error
for(let i = 0; i < 2; i++){
//Do something
}
console.log(i); // Throws error
for(var j = 0; j < 2; i++){
// Do something
}
console.log(j) // Outputs 2
- In javascript, a block refers to code written between curly braces {}.
- Variables declared with the var keyword are not block scoped.
- This means that a variable declared in block scope {} with the var keyword is equivalent to declaring the variable in the global scope.
- Variables declared with the let keyword inside a block scope cannot be accessed from outside the block.
Const keyword
- Variables with const keyword behave exactly like a variable declared with let keyword with only one difference, any variable declared with const keyword cannot be assigned again.
- Example:
const x = {name:"Vivek"};
x = {address: "India"}; // Throws an error
x.name = "Nikhil"; // No error is thrown
const y = 23;
y = 44; // Throws an error
4. What are the remaining parameters and the propagation operator?
Rest parameter and spread operator were introduced in ES6 version of javascript.
Remaining parameters (…):
- It provides an improved way to handle function parameters.
- By using the rest parameter syntax, we can create functions that can take a variable number of arguments.
- Any number of arguments will be converted to an array using the remaining parameter.
- This also helps extract all or part of the argument.
- The remaining parameter can be used by applying three dots (…) before the parameter.
function extractingArgs(...args){
return args[1];
}
// extractingArgs(8,9,1); // Returns 9
function addAllArgs(...args){
let sumOfArgs = 0;
let i = 0;
while(i < args.length){
sumOfArgs += args[i];
i++;
}
return sumOfArgs;
}
addAllArgs(6, 5, 7, 99); // Returns 117
addAllArgs(1, 3, 4); // Returns 8
**Note- Rest parameter should always be used at the last parameter of a function:
// Incorrect way to use rest parameter
function randomFunc(a,...args,c){
//Do something
}
// Correct way to use rest parameter
function randomFunc2(a,b,...args){
//Do something
}
- Spread operator (…): Although the syntax of the spread operator is exactly the same as the rest parameter, the spread operator is used to spreading an array, and object literals. We also use spread operators where one or more arguments are expected in a function call.
function addFourNumbers(num1,num2,num3,num4){
return num1 + num2 + num3 + num4;
}
let fourNumbers = [5, 6, 7, 8];
addFourNumbers(...fourNumbers);
// Spreads [5,6,7,8] as 5,6,7,8
let array1 = [3, 4, 5, 6];
let clonedArray1 = [...array1];
// Spreads the array into 3,4,5,6
console.log(clonedArray1); // Outputs [3,4,5,6]
let obj1 = {x:'Hello', y:'Bye'};
let clonedObj1 = {...obj1}; // Spreads and clones obj1
console.log(obj1);
let obj2 = {z:'Yes', a:'No'};
let mergedObj = {...obj1, ...obj2}; // Spreads both the objects and merges it
console.log(mergedObj);
// Outputs {x:'Hello', y:'Bye',z:'Yes',a:'No'};
5. In JavaScript, how many different methods can you make an object?
- Object.
- using Class.
- create Method.
- Object Literals.
- using Function.
- Object Constructor.
6. What is the use of promises in javascript?
Promises are employed in javascript to manage asynchronous operations.
Before promises, callbacks are used to handle asynchronous operations. But because callback functionality is limited, using multiple callbacks to handle asynchronous code can lead to unmanageable code.
The Promise object has four states –
- Pending – The initial state of the promise. This status means that the promise has not been kept or rejected, it is in a pending state.
- Completed – This status indicates that the promise has been fulfilled, meaning the asynchronous operation has completed.
- Rejected: This status indicates that the promise was rejected for some reason, meaning the asynchronous operation failed.
- Resolved – This status means the promise has been rejected or fulfilled. A promise created using the Promise constructor supports a callback function with two parameters: resolve and reject respectively.
Experience the power of our full stack development course with a free demo – enroll now!
Tips to prepare for a JavaScript coding interview
There are 5 tips candidates should keep in mind when attending a JavaScript coding interview:
- Master JavaScript basics: Candidates should have a solid understanding of the fundamentals of JavaScript, including variables, loops, conditions, objects, and data types. Additionally, practicing coding skills is also important.
- Explore popular libraries and frameworks: Get familiar with the most popular JavaScript libraries and frameworks like Vue.js, React, and more. Helps understand key concepts.
- Practice Java Coding on a Whiteboard: Java Coding skills can be perfected by practicing whiteboard coding. Candidates must solve coding problems and clearly explain their thought process. They should primarily focus on simplicity, clarity, and efficiency.
- Test code: After writing Java solutions, test them with a variety of inputs and make sure they work correctly and can handle difficult cases. Consider the time complexity of solutions and aim for efficiency.
- JavaScript Projects Review: It is essential to discuss JavaScript projects during the interview.
The interviewee should clearly explain their approach and how they overcame the challenge.
Red Flags
There are a few red flags that hiring managers should look out for in a JavaScript coding interview:
- Lack of basic JavaScript knowledge
- Providing inefficient solutions
- Lack of practical problem-solving skills
- Limited knowledge of asynchronous programming
- Copying and pasting code
- Inability to articulate thought processes or provide a clear explanation of their approach to a proble
- Lack of knowledge of modern JavaScript
- Failure to handle errors and account for extreme cases
Candidates are judged primarily on their understanding of basic JavaScript concepts and skills. By mastering the fundamentals and practicing, candidates can ace their interviews. In addition, it is important to strive to be clear, precise, and honest throughout the interview.