0% found this document useful (0 votes)
2K views

JS Interview Questions

Uploaded by

Hano Hani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views

JS Interview Questions

Uploaded by

Hano Hani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

• What are the different ways to include JavaScript in an HTML document?

o Inline: Add JavaScript directly in an element's onclick, onmouseover, etc.


o Internal: Write JavaScript in a <script> tag inside the HTML file.
o External: Write JavaScript in a .js file and link it using <script src="file.js"></script>.
• How can you display output in JavaScript? What methods can you use?
o console.log(): Displays output in the browser console.
o alert(): Displays a pop-up alert box.
o innerHTML: Updates the HTML content of an element.
• What does it mean when we say JavaScript is loosely typed and dynamically typed? Can you
provide examples?
o Loosely typed: Variables don't have a fixed type (var x = "Hello"; x = 5;).
o Dynamically typed: Types are determined at runtime.
• What are type conversions or casting in JavaScript? How can you explicitly convert a string to
a number?
o Use Number("42") or parseInt("42"). Implicit conversion happens when JS coerces
types automatically, e.g., 5 + "5" = "55".
• Explain the difference between == and ===.
o == compares values with type coercion.
o === compares values without type coercion (strict equality).
• How are strings compared in JavaScript? Why is ASCII code important?
o Strings are compared character by character based on ASCII codes. For example,
"apple" < "banana" is true.
• How does a switch statement differ from an if-else statement?
o switch is better for multiple discrete values, while if-else is more flexible for
conditions.
• What are the differences between for, while, and do-while loops? Can you give an example of
each?
o For: Executes a block a fixed number of times.
o While: Runs while a condition is true.
o Do-while: Executes at least once, even if the condition is false.
• What is the purpose of functions in JavaScript? How do you declare and invoke a function?
o Functions encapsulate reusable code. Declare using function name() {} and invoke
with name().
• What is hoisting in JavaScript? How does it affect variable and function declarations?
o Hoisting moves variable and function declarations to the top of their scope. Example:
console.log(x); // undefined
var x = 5;
• What are IIFE (Immediately Invoked Function Expressions)? Why and when would you use
them?
o Functions executed immediately after being defined:
o (function() { console.log("IIFE!"); })();
• Explain the difference between stack and heap memory in JavaScript.
o Stack: Stores primitive values and function calls.
o Heap: Stores objects and larger data.
• Name and explain three commonly used array methods.
o push(): Adds an element to the end.
o pop(): Removes the last element.
o map(): Transforms each array element.
• How can you store non-string data types in local storage?
o Convert to JSON:
o localStorage.setItem("data", JSON.stringify({ key: "value" }));
• What are some common string methods in JavaScript? Provide examples of their usage.
o toLowerCase(), toUpperCase(), slice(), split(), replace().
• What are Regular Expressions? How are they used in JavaScript?
o Patterns for matching text:
/abc/.test("abcdef"); // true
• What does CRUD mean, and how would you implement CRUD operations for a list of
products stored in local storage?
o Create: Add to the array and store.
o Read: Retrieve and parse data.
o Update: Modify the array and save back.
o Delete: Remove an item and save.
• How can you retrieve and display data stored in local storage?
o let data = JSON.parse(localStorage.getItem("key"));
• What is the DOM (Document Object Model), and why is it important?
o Represents the structure of an HTML document, allowing JavaScript to interact with
elements.
• How can you select an HTML element using JavaScript?
o document.getElementById(), document.querySelector().
• What is the purpose of the classList property?
o Allows adding, removing, or toggling CSS classes.
• What are AJAX and XMLHttpRequest? Why is AJAX used in web development?
o AJAX enables asynchronous server requests. Example:
▪ let xhr = new XMLHttpRequest();
xhr.open("GET", "url");
xhr.send();
• What are HTTP status codes? Why are they important?
o Indicate the result of an HTTP request (e.g., 200 OK, 404 Not Found).
• What is JSON and its common operations
o JSON is a text-based data format following JavaScript object syntax.
o Parsing: Converting a string to a native object
▪ JSON.parse(text);
o Stringification: Converting a native object to a string so that it can be transmitted across
the network
▪ JSON.stringify(object);
• What is the purpose of the array slice method
o 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 of the array. This method can also accept negative
index which counts back from the end of the array.
o Note: Slice method doesn't mutate the original array but it returns the subset as a new
array.
• What is the purpose of the array splice method
o The splice() method adds/removes items to/from an array, and then returns the
removed item. The first argument specifies the array position/index for insertion or
deletion whereas the optional second argument indicates the number of elements to
be deleted. Each additional argument is added to the array.
o Note: Splice method modifies the original array and returns the deleted array.
• What is the difference between slice and splice
o Slice
▪ Doesn't modify the original array(immutable)
▪ Returns the subset of original array
▪ Used to pick the elements from array
o Splice
▪ Modifies the original array(mutable)
▪ Returns the deleted elements as array
▪ Used to insert/delete elements to/from array
• What is the difference between == and === operators
o JavaScript provides both strict(===, !==) and type-converting(==, !=) equality comparison.
The strict operators take 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,
I. Two strings are strictly equal when they have the same sequence of characters,
same length, and same characters in corresponding positions.
II. Two numbers are strictly equal when they are numerically equal, i.e., having the
same number value. There are two special cases in this,
III. NaN is not equal to anything, including NaN.
IV. Positive and negative zeros are equal to one another.
V. Two Boolean operands are strictly equal if both are true or both are false.
VI. Two objects are strictly equal if they refer to the same Object.
VII. Null and Undefined types are not equal with ===, but equal with == . i.e,
null===undefined --> false, but null==undefined --> true
0 == false // true
0 === false // false
1 == "1" // true
1 === "1" // false
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false
NaN == NaN or NaN === NaN // false
[]==[] or []===[] //false, refer different objects in memory
{}=={} or {}==={} //false, refer different objects in memory

• What is an IIFE (Immediately Invoked Function Expression)


o IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon
as it is defined. The signature of it would be as below,
(function () {
// logic here
})();

The primary reason to use an IIFE is to obtain data privacy because any variables declared
within the IIFE cannot be accessed by the outside world. i.e, If you try to access variables
from the IIFE then it throws an error as below,
(function () {
var message = "IIFE";
.log(message);
})();
console.log(message); //Error: message is not defined
• What is Hoisting
o Hoisting is a JavaScript mechanism where variables, function declarations and classes 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,
o console.log(message); //output : undefined
var message = "The variable Has been hoisted";
o The above code looks like as below to the interpreter,
var message;
console.log(message);
message = "The variable Has been hoisted";
o In the same fashion, function declarations are hoisted too
message("Good morning"); //Good morning

function message(name) {
console.log(name);
}
o This hoisting makes functions to be safely used in code before they are declared.
• What is scope in javascript
o Scope is the accessibility of variables, functions, and objects in some particular part of
your code during runtime. In other words, scope determines the visibility of variables and
other resources in areas of your code.
• What is web storage
o Web storage is an API that provides a mechanism by which browsers can store key/value
pairs locally within the user's browser, in a much more intuitive fashion than using cookies.
The web storage provides two mechanisms for storing data on the client.
▪ Local storage: It stores data for current origin with no expiration date.
▪ Session storage: It stores data for one session and the data is lost when the
browser tab is closed.
• What is the main difference between localStorage and sessionStorage
o LocalStorage is the same as SessionStorage but it persists the data even when the browser
is closed and reopened(i.e it has no expiration time) whereas in sessionStorage data gets
cleared when the page session ends.
• What is typeof operator
o You can use the JavaScript typeof operator to find the type of a JavaScript variable. It
returns the type of a variable or an expression.
• What is undefined property
o The undefined property indicates that a variable has not been assigned a value, or declared
but not initialized at all. The type of undefined value is undefined too.
• What is null value
o 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.
• What is the difference between null and undefined
o Null
▪ It is an assignment value which indicates that variable points to no object.
▪ Type of null is object
▪ The null value is a primitive value that represents the null, empty, or non-existent
reference.
▪ Indicates the absence of a value for a variable
▪ Converted to zero (0) while performing primitive operations
o Undefined
▪ It is not an assignment value where a variable has been declared but has not yet
been assigned a value.
▪ Type of undefined is undefined
▪ The undefined value is a primitive value used when a variable has not been assigned
a value.
▪ Indicates absence of variable itself
▪ Converted to NaN while performing primitive operations
• What is eval
o The eval() function evaluates JavaScript code represented as a string. The string can be a
JavaScript expression, variable, statement, or sequence of statements.
o console.log(eval("1 + 2")); // 3
• What are the differences between undeclared and undefined variables
o Below are the major differences between undeclared(not defined) and undefined variables,
▪ Undeclared
• These variables do not exist in a program and are not declared
• If you try to read the value of an undeclared variable, then a runtime error is
encountered
▪ Undefined
• These variables declared in the program but have not assigned any value
• If you try to read the value of an undefined variable, an undefined value is
returned.
• What are global variables
o 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
o msg = "Hello"; // var is missing, it becomes global variable
• What is NaN property
o 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
o Math.sqrt(-1);
parseInt("Hello");
• What is an event flow
o Event flow is the order in which event is received on the web page. When you click an
element that is nested in various other elements, before your click actually reaches its
destination, or target element, it must trigger the click event for each of its parent elements
first, starting at the top with the global window object.
o There are two ways of event flow
▪ Top to Bottom(Event Capturing)
▪ Bottom to Top (Event Bubbling)
• What is event bubbling
o 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(i.e, global
window object).
• What is event capturing
o Event capturing is a type of event propagation where the event is first captured by the
outermost element, and then successively triggers on the descendants (children) of the
target element in the same nesting hierarchy till it reaches the innermost target DOM
element.
• Is JavaScript a case-sensitive language
o Yes, JavaScript is a case sensitive language. The language keywords, variables, function &
object names, and any other identifiers must always be typed with a consistent
capitalization of letters.
• What is the use of stopPropagation method
o The stopPropagation method is used to stop the event from bubbling up the event chain.
• What is JSON
o JSON (JavaScript Object Notation) is a lightweight format that is used for data
interchanging. It is based on a subset of JavaScript language in the way objects are built in
JavaScript.
• What is the purpose JSON stringify
o When sending data to a web server, the data has to be in a string format. You can achieve
this by converting JSON object into a string using stringify() method.
var userJSON = { name: "John", age: 31 };
var userString = JSON.stringify(userJSON);
console.log(userString); //"{"name":"John","age":31}"
• How do you parse JSON string
o When receiving the data from a web server, the data is always in a string format. But you
can convert this string value to a javascript object using parse() method.
var userString = '{"name":"John","age":31}';
var userJSON = JSON.parse(userString);
console.log(userJSON); // {name: "John", age: 31}
• How do you check if a string starts with another string
o You can use ECMAScript 6's String.prototype.startsWith() method to check if a string
starts with another string or not. But it is not yet supported in all browsers. Let's see an
example to see this usage,
"Good morning".startsWith("Good"); // true
"Good morning".startsWith("morning"); // false
• How do you trim a string in javascript
o JavaScript provided a trim method on string types to trim any whitespaces present at the
beginning or ending of the string.

You might also like