JavaScript is still one of the most in-demand programminglanguage, as it was ranked no 1 most popular language in the latest Stack Overflow survey. While professional developers like it for its variety of use cases, new coders also started learning this technology first, beating Python or C++. So, most technical interviews are now mostly based on JavaScript.
Here we have curated a list of Javascript Questions (along with answers) whose answer you must know before applying for any software developer job. And don’t worry, we have give you answers with them as well.
1) What is JavaScript?
JavaScript is a programming language that is mainly used to creating dynamic, interactive web pages as well as online apps. It is also a high-level, interpreted programming language. Developers also sometimes call it “universal language,” as it is mostly used by front-end and back-end developers.
2) What are the different data types in JavaScript?
JavaScript has six primary data types:
- Number
- String
- Boolean
- Null
- Undefined
- Symbol
3) What are its advantages?
Following are some of the main advantages we will prefer JavaScript over others:
- Less server interaction: You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.
- Immediate feedback to the visitors: They don’t have to wait for a page reload to see if they have forgotten to enter something.
- Increased interactivity: You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.
- Richer interfaces: You can make really beautiful and appealing user interfaces with JavaScript.
4) How can you create an Array in JavaScript?
An array is a data structure that stores data of the same type for example array of numbers or strings. You can define arrays using the array literal as follows:
var x=[]; var y=[1,2,3,4,5];
5) What are the scopes of a variable?
The scope of a variable is the region of your program in which it is defined. JavaScript variables will have only two scopes.
- Global Variables: A global variable has a global scope which means it is visible everywhere in your JavaScript code. In simple words, we can say that we can access global variables anywhere in the code.
- Local Variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
6) How many ways can a JS code be involved in an HTML file?
There are 3 different ways in which a JavaScript code can be involved in an HTML file:
- Inline
- Internal
- External
An inline function is a JavaScript function, which is assigned to a variable created at runtime. You can differentiate between Inline Functions and Anonymous since an inline function is assigned to a variable and can be easily reused.
When you need JavaScript for a function, you can either have the script integrated into the page you are working on, or you can have it placed in a separate file that you call, when needed. This is the difference between an internal script and an external script.
7) What is hoisting in JavaScript?
The act of pushing declarations to the top of their scope is known as “hoisting” in JavaScript. As long as they are defined before being used in a function, variables and functions can be utilized before they are declared.
For instance, even though the wishes variable isn’t declared until after the console.log() instruction, the code below will produce “Hello, world!”:
var wishes= "Hello, world!"; function sayHello() { console.log(wishes); A } sayHello();
8) What is the difference between null and undefined?
null is an assignment value that represents no value or an empty value, while undefined is a variable that has been declared but not assigned a value.
Learn more about the differences between null and undefined here.
9) What is the purpose of the “this” keyword in JavaScript?
The object that is carrying out the current function or method is referred to by this keyword. It permits access to methods and attributes of an object while it is in that object’s context.
10) What is the difference between == and === operators in JavaScript?
The equality == operator is a comparison operator that compares two values and returns true if they are equal. The strict equality === operator is also a comparison operator, but it compares two values and returns true only if they are equal and of the same type.
11) What is the difference between “var” and “let” keywords?
In JavaScript, variables are declared using the var and let keywords. The two terms have some minor but yet important differences.
A global variable is one that is declared using the var keyword and can be accessed from anywhere in the code. A local variable is declared with the let keyword, meaning that it can only be accessible within the block of code in which it is declared.
We have a separate tutorial blog on the differences between ‘var’ and ‘let’ keywords.
12) What are closures in JavaScript?
Closures (closureFn) are functions that have access to variables from an outer function even after the outer function has finished executing. They “remember” the environment in which they were created.
function outer() { var outerVar = "Hello"; function inner() { console.log(outerVar); } return inner; } var closureFn = outer(); closureFn(); // Output: Hello
13) What is the difference between “let”, “const”, and “var”?
let
and const
were introduced in ES6 and have block scope. let is reassignable, and const is non-assignable. var is function-scoped and can be redeclared and reassigned throughout the function
14) What is implicit type coercion in JavaScript?
The automatic conversion of a value from one type to another is known as implicit type coercion in JavaScript. T
his conversion happens in JavaScript in a priority order that usually starts with strings, moves up to integers, and ends with booleans. Because strings have the highest priority in type coercion, JavaScript will implicitly coerce a number to a string before executing the addition operation if you try to add a string to a number.
For instance, the string “510” is produced when you use the addition operator to join the integer 5 with the text “10.” This happens as a result of JavaScript’s implicit conversion of 5 to a string based on coercion priority, which is subsequently concatenated with the string “10.”
var x = 5; var y = "10"; console.log(x + y); // "510"
15) What is the output of the following code?
console.log(3+2+"7")
The output will be “57”. The addition operation is performed from left to right, and when a string is encountered, it performs concatenation.
16) What are higher-order functions in JavaScript?
Higher-order functions are functions that can accept other functions as arguments or return functions as their results. They enable powerful functional programming patterns in JavaScript.
17) What is the difference between function declarations and function expressions?
Function declarations are defined using the function keyword, while function expressions are defined by assigning a function to a variable. Function declarations are hoisted, while function expressions are not.
// Function declaration function multiply(a, b) { return a b; } // Function expression const add function(a, b) { return a + b; }; console.log(multiply(2, 3)); // Output: 6 console.log(add(2, 3)); // Output: 5
18) What are the different types of errors in JavaScript?
JavaScript can throw a variety of errors, including:
- Syntax errors: These errors occur when the code is not syntactically correct.
- Runtime errors: These errors occur when the code is executed and there is a problem.
- Logical errors: These errors occur when the code does not do what it is supposed to do.
19) What is Memoization?
Memoization is a technique that can be used to improve the performance of JavaScript code. Memoization works by storing the results of expensive calculations in a cache. This allows the JavaScript code to avoid re-performing the expensive calculations if the same input is provided again.
For example, the following code calculates the factorial of a number. The factorial of a number is the product of all the positive integers from one to the number.
function factorial(n) { if (factorialCache [n] !== undefined) { return factorialCache[n]; } else { factorialCache[n] = n factorial(n 1); return factorialCache[n]; }
20) What is Recursion?
Recursion is a programming technique that allows a function to call itself. Recursion in JavaScript can be used to solve a variety of problems, such as finding the factorial of a number or calculating the Fibonacci sequence.
21) What is the use of a constructor function?
A constructor function is a special type of function that is used to create objects. Constructor functions are used to define the properties and methods of an object.
22) What is a callback function in JavaScript?
A callback function is a function passed as an argument to another function, which is then invoked inside the outer function. It allows asynchronous or event-driven programming.
function fetchData(callback) { // Simulating an asynchronous operation setTimeout(function() { const data "Some data"; callback(data); }, 2000); } function processData(data) { console.log("Data received: " + data); } fetchData(processData); // Output after 2 seconds: Data received: Some data
23) What is the difference between synchronous and asynchronous programming?
In synchronous programming, the program execution occurs sequentially, and each statement blocks the execution until it is completed. In asynchronous programming, multiple tasks can be executed concurrently, and the program doesn’t wait for a task to finish before moving to the next one.
24) How do you handle errors in JavaScript?
Errors in JavaScript can be handled using try-catch blocks. The try block contains the code that may throw an error, and the catch block handles the error and provides an alternative execution path.
try { / / Code that may throw an error throw new Error("Something went wrong"); } catch (erroог) { // Error handling console.log("Error occurred: " + }
25) What are arrow functions in JavaScript?
Arrow functions are a concise syntax for writing JavaScript functions. They have a more compact syntax compared to traditional function expressions and inherit this value from their surrounding scope.
26) What is the purpose of the setTimeout() function in JavaScript?
The setTimeout()
function is used to delay the execution of a function or the evaluation of an expression after a specified amount of time in milliseconds.
27) What is the difference between localStorage and sessionStorage in JavaScript?
Both localStorage and sessionStorage are web storage objects in JavaScript, but they have different scopes and lifetimes.
- localStorage persists data even after the browser window is closed and is accessible across different browser tabs/windows of the same origin.
- sessionStorage stores data for a single browser session and is accessible only within the same tab or window.
28) How can you convert a string to lowercase in JavaScript?
You can use the toLowerCase()
method to convert a string to lowercase in JavaScript.
const str= "Hello, World!"; console.log(str.toLowerCase()); // Output: hello, world!
29) What is the purpose of the map() function in JavaScript?
The map() function is used to iterate over an array and apply a transformation or computation on each element. It returns a new array with the results of the transformation.
const numbers [1, 2, 3, 4, 5]; const squaredNumbers = numbers.map(function(num) { return num* num; }); console.log(squaredNumbers); // Output: [1, 4, 9, 16, 251
30) What is the difference between splice() and slice()?
The splice()
function is used to modify an array by adding, removing, or replacing elements at a specific position. The slice()
function is used to create a new array that contains a portion of an existing array, specified by the starting and ending indices.
31) How can you check if an array includes a certain value in JavaScript?
You can use the includes() method to check if an array includes a specific value. It returns true if the value is found, and false otherwise.
const fruits = ["apple", "banana", "orange"]; console.log(fruits.includes ("banana")); // Output: true console.log(fruits.includes("grape")); // Output: false
32) What is the difference between an array and an object in JavaScript?
An array is a data structure that can store a collection of values. An object is a data structure that can store a collection of properties.
Arrays are indexed by numbers, while Objects are indexed by strings. Arrays can only store primitive data types and objects. Objects can store primitive data types, objects, and arrays.
33) What is the purpose of the fetch() function in JavaScript?
The fetch() function is used to make asynchronous HTTP requests in JavaScript. It returns a Promise that resolves to the response from the server.
fetch("https://apt.example.com/data") .then(function(response) { return response.json(); }) .then(function(data) { console.log(data); }) .catch(function(error) { console.log("Error occurred: " + error); });
34) What are the different events in JavaScript?
There are many different events in JavaScript, but some of the most common events include:
- Click: The click event occurs when a user clicks on an HTML element.
- Mouseover: The mouseover event occurs when a user’s mouse pointer moves over an HTML element.
- Keydown: The keydown event occurs when a user presses a key on the keyboard.
- Keyup: The keyup event occurs when a user releases a key on the keyboard.
- Change: The change event occurs when a user changes the value of an HTML input element.
35) What is the purpose of the window object in JavaScript?
The window object represents the browser window. The window object can be used to access the browser’s features, such as the location bar, the status bar, and the bookmarks bar.
36) What is the purpose of the async and await keywords in JavaScript?
The async and await keywords are used for handling asynchronous operations in a more synchronous-like manner. The async keyword is used to define an asynchronous function, and the await keyword is used to pause the execution of an async function until a promise is fulfilled or rejected.
async function fetchData() { try { const response = await fetch("https://api.example.com/data"); const data await response.json(); console.log(data); } catch (error) { console.log("Error occurred: " + error); } } fetchData();
37) What is the difference between innerHTML & innerText?
- innerHTML: It will process an HTML tag if found in a string
- innerText: It will not process an HTML tag if found in a string
38) What is NaN in JavaScript?
NaN is a short form of Not a Number since it always compares unequal to any number, 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 in JavaScript.
39) How are JavaScript primitive/object types passed in functions?
One of the differences between the two is that Primitive Data Types are passed By Value and Objects are passed By Reference.
- Value means creating a COPY of the original. Picture it like twins: they are born exactly the same, but the first twin doesn’t lose a leg when the second twin loses him in the war.
- Reference means creating an ALIAS to the original. When your Mom calls you “Pumpkin Pie” although your name is Margaret, this doesn’t suddenly give birth to a clone of yourself: you are still one, but these two very different names can call you.
The parseInt() function is used to convert numbers between different bases. It takes the string to be converted as its first parameter, and the second parameter is the base of the given string. For example:
parseInt("4F",16);
40) What is currying in JavaScript?
Currying is an advanced technique to transform a function of arguments n, to n functions of one or fewer arguments. Example of a curried function:
function add (a) { return function(b){ return a + b; } } add(3)(4)
For Example, if we have a function f(a,b), then the function after currying, will be transformed to f(a)(b).
By using the currying technique, we do not change the functionality of a function, we just change the way it is invoked.
Let’s see currying in action:
function multiply(a,b){ return a*b; } function currying(fn){ return function(a){ return function(b){ return fn(a,b); } } } var curriedMultiply = currying(multiply); multiply(4, 3); // Returns 12 curriedMultiply(4)(3); // Also returns 12
As one can see in the code above, we have transformed the function multiply(a,b) to a function curriedMultiply, which takes in one parameter at a time.
41) What are some advantages of using External JavaScript?
External JavaScript is the JavaScript Code (script) written in a separate file with the extension.js, and then we link that file inside the or element of the HTML file where the code is to be placed.
Some advantages of external javascript are:
- It allows web designers and developers to collaborate on HTML and JavaScript files.
- We can reuse the code.
- Code readability is simple in external JavaScript.
42) What is the distinction between client-side and server-side JavaScript?
Client-side JavaScript is made up of two parts, a fundamental language and predefined objects for performing JavaScript in a browser. JavaScript for the client is automatically included in the HTML pages. At runtime, the browser understands this script.
Server-side JavaScript, involves the execution of JavaScript code on a server in response to client requests. It handles these requests and delivers the relevant response to the client, which may include client-side JavaScript for subsequent execution within the browser.
Conclusion
If you know the answers to all these basic JavaScript questions for beginners, you are ready for the interview! But if you have any doubts, we have experts ready to help you with anything JavaScript. We wish you good luck!