If you have taken up a course in JavaScript in our web design and development institute, by now you have hands-on experience, have built some dummy projects and now you are ready to take it up professionally! You have career choices corresponding JavaScript Programmer, JavaScript Developer, OOJS Professional, JSON Expert, Ajax Developer, etc.
To build a career and land a job in any technology one has to go through a series of rounds of interviews in any company. One of such rounds is the technical round that tests your in-depth knowledge of technology. Mostly these interviews cover the most used aspects of a technology or a framework. In this blog, we will discuss the most popular questions and their answers that can help you crack an interview in JavaScript.
Beginner and Intermediate Level Interview Q&A of JavaScript
Q1. Name the data types in JavaScript?
JavaScript has two types of data types:
-> PRIMITIVE
- String
- Number
- Boolean
- Null and undefined
-> NON- PRIMITIVE
- Arrays
- Objects
Want to know more about Data Types? Read out the Common and very Important Terms to Learn in JavaScript
Q2. Specify 2 ways to create an object in JavaScript?
-> Object.create
var obj= Object.create(null);
-> Object literal
var obj={}
Q3. How do you access DOM elements in JavaScript?
The DOM is accessed using the “document” object which represents the web page. It has various methods to access elements by ID, class, tag and other selectors.
Eg: to get an element with ID “topNode” we will write the following code:
var elem=document.getElemntById(‘topNode’);
Some of the other methods are:
- getElementByClassName()
- getElementByTagName()
- getElementById()
- createElement()
- appendChild()
Explore more about JavaScript and DOM Concept
Q4. What is the typeOf operator used for?
TypeOf is used to identify the “data type” of a variable. It returns the value in a string format
E.g.:
var x = 'abc'; typeof(x); //this will return ‘string’
Become more familiar with Operators in JavaScript
Q5. Explain ‘this’ keyword in JavaScript
In JavaScript ‘this’ refers to ‘context’ of the current execution. ‘this’ points to an object of the current context. If the program is executing in a global context ‘this’ points to the global object (window object). The value for ‘this’ is computed every time the course of execution changes or every time a function is called.
Example:
var employee = { firstname = 'raveen', lastname = 'anand', fullname = function() { return(this.firstname + " " + this.lastname); } }
Here ‘this’ points to the object named “employee”.
Q6. Explain scope in JavaScript
Scope determines the accessibility of functions, variables & objects during runtime. Basically, we can categorize scopes into two main parts in JavaScript:
- Global scope: Any variable or object declared outside a function is in the global scope. These can be accessed and modified from other local scopes.
- Local scope: Variable or objects declared inside a function are considered in local scope which can be created with a function. You need to create functions first in order to create local scope. The variables in a local scope can only be accessed and modified within the scope and cannot be accessed by other scopes.
Read more about –
Pop-ups, Variables, Functions, and Scope in JavaScript
Q7. Is ‘==’ same as ‘===’ in an equation?
No. ‘==’ and ‘===’ are not the same. ‘==’ stands for equality whereas ‘===’ stands for strict equality. With ‘==’ operator we compare two values but with ‘===’ it compares not only values but also the type of data.
Example:
var num=2;var str=’2’ if(num==str) { return true; //This will return true as ‘==’ operator considers 2=’2’; } else { return false; } if(num===str) { return true; } else { return false; }
Line 12 will return false as ‘===’ operator does not consider 2=’2’ because the data type of both variables is different. One being a string and the other being a number.
Q8. Write a program to reverse a string in JavaScript
var str=’raveen’; str.split(“”); //convert str to an array str.reverse(); // method to reverse array contents str.join(“”); // convert back to a string console.log(str); // RESULT: neevar
Q9. Is null same as undefined?
No. Null is an assignment value, it indicates that a variable holds no value. When the variable is either undeclared or unassigned to any value then this scenario is called Undefined.
Both Null and Undefined are different as the first one is an object and the former is type itself.
Q10. What is closure?
Closure is a local variable in a function and is accessible even after the function has returned. An inner function is created within an outer function. When the outer function returns a reference to the inner function, the returned reference can still access the local data from the outer function.
function greetVisitor(phrase) { var welcome = phrase + "Folks!"; // Local variable var sayWelcome = function() { alert(welcome); }; return sayWelcome; } var personalGreeting = greetVisitor('Hi'); personalGreeting(); // alerts "Hi Folks!"
Become more familiar with the Closures in JavaScript – Learn in Easy Steps with Examples
Q11. What is an anonymous function?
As the name suggests ‘anonymous’ functions are not assigned a name. Instead, the function is assigned to a variable and is invoked using the function name. These functions are created using function expressions and not a declaration.
Syntax:
function (optionalParameters) { //code }
Function Assigned to a variable:
var myFunction = function() { //code };
Anonymous functions are passed as arguments to other functions and also used in closures.
Q12. What does a for-in loop do?
A for-in loop is used to iterate over properties of an object.
Example:
var result = ""; var obj = {prop1: 1, prop2: 2, prop3: 3}; for (var property in obj) { result += obj[property]; } console.log(result); // Output: "123"
Let’s Understand Literals and Loops in JavaScript in more detail.
Q13. What are IIFE’s?
IIFE (Immediately invoke function expression) is a self-executing anonymous function. This function runs as soon as it is defined. Variables which are declared inside an IIFE cannot be retrieved from the outside.
Syntax:
(function() { // code statements; })();
Example:
(function() { var x = "example"; })(); console.log(x) // throws "Uncaught ReferenceError: xis not defined"
In this Example above, x is not accessible outside as it is a part of an IIFE. An IIFE can be assigned to a variable like follows:
var out= (function() { var x= "Example"; return name; })(); console.log(out); // "Example"
Here we have assigned the function to a variable “out”. This variable will store the return value of this function and not the function definition.
Q14. What is ‘NaN’?
NaN is a special value stands for ‘Not a Number’. It is returned as a value from operations that lead to an undefined numerical result.
Some example of operations that result in a NaN is:
Math.sqrt(-5); ParseInt(‘abc’); 0/0;
15. How is ‘var’ different from ‘let’?
‘var’ is used to create a variable irrespective of the block scope, it can create variables anywhere globally or locally, whereas ‘let’ is used to declare variables which are limited to the scope of a block. The variables created using ‘let’ are not accessible globally. Variables created with ‘let’ are usually for a limited purpose.
Q16. What is a callback function and why are they used?
The callback is a type of function which can be passed as a parameter or argument. Callback functions work after other functions or we can say that these callback functions are performed after the other function has ended executing. Callbacks are used in scenarios when you we want to handle something when some other piece of code has been completed.
Example:
alertUserInput(greeting); function alertUserInput(callback) { var userName= prompt('Please enter your name.'); callback(userName); } function greeting(name) { alert('Hello ' + name); }
In the example above, ‘alertUserInput’ method takes ‘greeting’ as an argument which is a function (callback function).
Q17. How is error handling done in JavaScript?
Error handing in JavaScript is done using ‘try’ ‘catch’ and finally blocks.
try { //code to be tested } catch { //code to be executed if error occurs in try block } finally { //code to be executed after try and catch irrespective of the result }
Take some more tips on Handling Errors and Exceptions in JavaScript
Q18. What are the arrow functions?
Arrow functions are the functions which are being used forscripting the function expressions. A single statement function can be written without using ‘function’, ‘return’ statements.
Example:
// normal function declaration var x = function(x, y) { return x + y; } // Converted into arrow function const x = (x, y) => x + y;
‘Const’ is used as a function expression is a constant value.
Q19. What is map used for?
The map is an array function that creates a new array from results of a callback function for every array element.
Example:
var arr = [2, 4, 6, 8]; var new_arr = arr.map ( function(num) { return num / 2; } ); Console.log(new_arr); //OUTPUT: [1,2,3,4]
Q 20. Can you create a class in JavaScript?
Since JavaScript is an ‘object-based language ‘and not a true ‘OOP’s language classes are not an inbuilt part. Earlier to mimic a ‘class’ constructors were created. After ES6 ‘class expressions’ are included as a part of JavaScript.
Want to know about ES6? Read out the New Features of ECMAScript or ES6 for all JavaScript Developers
Summary
So, yes JavaScript is the basis for web development. Whether you aim to land a job as a web developer or a Front-end developer, JavaScript is must to learn. Thus we brought the list of interview questions and answers of JavaScript. These questions will help beginners to get a better understanding of JS interviews.
You can take inspiration from one of our portfolio projects and build something to test your knowledge. Also, here at ADMEC, we offer one of the web designing classes and web development training. These programs not only make you technically sound but also progress your career in a real-time environment.