JavaScript Questions
1. What is the difference between == and === ?
The ===
comparison operator is a strict comparison operator that will only return true if both the type and value of the two operands are equal. However, the ==
comparison operator will do an implicit type conversion if the value is the same but the type is different.
For example, if you have 2 === "2"
, the result will be false
. However, if you have 2 == "2"
, the result is true
, because the value of the two operands are equal, resulting in a type conversion to make the type the same.
2. What will the following code output to the console and why?
(function(){
var a = b = 3;
})();
console.log("a defined? " + (typeof a !== 'undefined'));
console.log("b defined? " + (typeof b !== 'undefined'));
Here is a great explanation from Toptal:
"Since both a
and b
are defined within the enclosing scope of the function, and since the line they are on begins with the var
keyword, most JavaScript developers would expect typeof a
and typeof b
to both be undefined in the above example.
However, that is not the case. The issue here is that most developers incorrectly understand the statement var a = b = 3;
to be shorthand for:
var b = 3;
var a = b;
But in fact, var a = b = 3;
is actually shorthand for:
b = 3;
var a = b;
As a result (if you are not using strict mode), the output of the code snippet would be:
a defined? false
b defined? true
But how can b
be defined outside of the scope of the enclosing function? Well, since the statement var a = b = 3;
is shorthand for the statements b = 3;
and var a = b;
, b
ends up being a global variable (since it is not preceded by the var
keyword) and is therefore still in scope even outside of the enclosing function.
Note that, in strict mode (i.e., with use strict
), the statement var a = b = 3;
will generate a runtime error of ReferenceError: b is not defined
, thereby avoiding any headfakes/bugs that might otherwise result. (Yet another prime example of why you should use use strict
as a matter of course in your code!)"
3. What will the following code output to the console and why?
var myObject = {
foo: "bar",
func: function() {
var self = this;
console.log("outer func: this.foo = " + this.foo);
console.log("outer func: self.foo = " + self.foo);
(function() {
console.log("inner func: this.foo = " + this.foo);
console.log("inner func: self.foo = " + self.foo);
}());
}
};
myObject.func();
Here is a great explanation from Toptal:
"The above code will output the following to the console:
outer func: this.foo = bar
outer func: self.foo = bar
inner func: this.foo = undefined
inner func: self.foo = bar
In the outer function, both this
and self
refer to myObject
and therefore both can properly reference and access foo
.
In the inner function, though, this
no longer refers to myObject
. As a result, this.foo
is undefined in the inner function, whereas the reference to the local variable self
remains in scope and is accessible there."
4. Explain how this
works in JavaScript.
A full understanding of using this
in JavaScript can be found in the MDN docs, but here is a good, succinct explanation from [Nick at Unschoolder.org](http://unschooled.org/2012/03/understanding-javascript-this/):
this
refers to the global object.- When a function is called as a property on a parent object,
this
refers to the parent object inside that function. - When a function is called with the
new
operator,this
refers to the newly created object inside that function. - When a function is called using
call
orapply
,this
refers to the first argument passed tocall
orapply
. If the first argument isnull
or not an object,this
refers to the global object.
5. What are data attributes good for?
Data attributes are used to put different forms of data within HTML elements and then retrieve them when needed using JavaScript. HTML elements with data attributes can also be targeted by CSS for styling.
For example, if a programmer wants to store the associated id of an element from a table into an HTML file, the data can be stored dynamically into the HTML element and then retrieved using dataset.
var elementToStoreId = document.getElementById('someElement');
elementToStoreId.dataset.idFromDb = 3; // This would set the data into the element.
elementToStoreId.dataset.idFromDb; // This would retrieve data from the element.
6. Explain the difference between stateless and stateful protocols. Which type of protocol is HTTP? Explain your answer.
Toptal has a terrific answer to this:
"A stateless communications protocol treats each request as an independent transaction. It therefore does not require the server to retain any session, identity, or status information spanning multiple requests from the same source. Similarly, the requestor cannot rely on any such information being retained by the responder.
In contrast, a stateful communications protocol is one in which the responder maintains “state” information (session data, identity, status, etc.) across multiple requests from the same source.
HTTP is a stateless protocol. HTTP does not require a server to retain information or status about each user for the duration of multiple requests.
Some web servers implement states using different methods (using cookies, custom headers, hidden form fields, etc.). However, in the very core of every web application, everything relies on HTTP, which is still a stateless protocol that is based on simple request/response paradigm."
7. Explain Ajax in as much detail as possible.
Segue Tech does a fairly good job at explaining the answer in detail:
"Ajax is not a programming language or a tool, but a concept. Ajax is a client-side script that communicates to and from a server/database without the need for a postback or a complete page refresh. The best definition I’ve read for Ajax is “the method of exchanging data with a server, and updating parts of a web page—without reloading the entire page.” Ajax itself is mostly a generic term for various JavaScript techniques used to connect to a web server dynamically without necessarily loading multiple pages. In a more narrowly defined sense, it refers to the use of XmlHttpRequest objects to interact with a web server dynamically via JavaScript.
Benefits of Ajax
There are 4 main benefits of using Ajax in web applications:
- Callbacks: Ajax is used to perform a callback, making a quick round trip to and from the server to retrieve and/or save data without posting the entire page back to the server. By not performing a full postback and sending all form data to the server, network utilization is minimized and quicker operations occur. In sites and locations with restricted bandwidth, this can greatly improve network performance. Most of the time, the data being sent to and from the server is minimal. By using callbacks, the server is not required to process all form elements. By sending only the necessary data, there is limited processing on the server. There is no need to process all form elements, process the ViewState, send images back to the client, or send a full page back to the client.
- Making Asynchronous Calls: Ajax allows you to make asynchronous calls to a web server. This allows the client browser to avoid waiting for all data to arrive before allowing the user to act once more.
- User-Friendly: Because a page postback is being eliminated, Ajax-enabled applications will always be more responsive, faster and more user-friendly.
- Increased Speed: The main purpose of Ajax is to improve the speed, performance, and usability of a web application. A great example of Ajax is the movie rating feature on Netflix. The user rates a movie and their personal rating for that movie will be saved to their database without waiting for the page to refresh or reload. These movie ratings are being saved to their database without posting the entire page back to the server."
Note: This is a very exhaustive explanation. You should just take the concepts from this and explain them in your own words, rather than trying to memorize any of the above. Furthermore, you may be asked to write out an example of an AJAX call. You should try and avoid using jQuery when making the call and instead initiate an XMLHttpRequest object for the call.
8. What are the advantages and disadvantages of using Ajax?
The following answer from [DZone](https://dzone.com/articles/pros-and-cons-of-ajax) provides a very comprehensive answer. Please note that you should just take the concepts from this and explain them in your own words, rather than trying to memorize any of it.
"AJAX (Asynchronous JavaScript and XML) is an interactive and dynamic web application development technology that offers a rich user experience. Complete AJAX applications provide the feel of desktop applications. Like any other technology, AJAX also comes with its own set of pros and cons. Below [are] some important scenarios which one definitely must be aware of while using AJAX in web based application development.
Pros of Using AJAX
-
Improved User Experience: The enriched user experience provided by AJAX is the foremost benefit. AJAX allows webpages to update serially by exchanging a small amount of data with the server. This way it is possible to update parts of a webpage, without reloading the whole page. Classic webpages must reload the entire page and are cumbersome. AJAX increases the browser’s performance and facilitates faster browsing speed thereby providing a responsive user experience.
-
Enhanced User Productivity: The AJAX library provides object-oriented helper functions that dramatically increase the productivity while decreasing frustration. In addition, a well-configured ASP.NET application has its own data access layer and business layer. Finally, the “robust” ASP.NET application includes a UI layer where server side operations are performed. If you already have included these features, AJAX only needs an extra layer of AJAX-specific services and some enrichment on client features. This way the deployment cost is reduced and the productivity of the user can be enhanced. Popular websites like Amazon, Google, Yahoo, etc. also incorporate AJAX in their development.
-
Reduced Bandwidth Usage and Increased speed: AJAX uses client-side scripting to communicate with the web server and exchange data using JavaScript. Using AJAX, you can cut down on network load and bandwidth usage and retrieve only the data that is required to give you faster interfaces and better responsive times. Response time is faster, hence performance and speed are increased.
-
Increased Compatibility: AJAX can be compatible with ASP.NET, J2EE, PHP, or any languages. It almost supports all popular browsers such as Internet Explorer 5 and above, Mozilla Firefox 1.0 and above, Apple Safari 1.2 and above, Opera 7.6 and above, and RockMelt.
-
Supports Asynchronous Processing: Asynchronous data retrieval can be done by using XMLHttpRequest, the backbone of AJAX applications. Hence, requests are handled effectively and dynamic content loading is brought to higher heights by improving the performance considerably.
-
Reduced server hits and network load: Atlas, an older form of Microsoft AJAX library, is a framework that integrates the Client-side JavaScript library and is easily available and can be used with ASP.NET to develop Ajax applications. It has cross-browser support and exposes object-oriented APIs, which can be used to develop web applications that minimize server hit/network load and perform asynchronous processing.
-
Easier Navigation: AJAX applications can be built to allow easy transition between webpages to the users instead of using conventional back and forward buttons on a browser.
Cons of Using AJAX
-
Browser Incompatibility: AJAX highly depends on JavaScript which is implemented differently for various browsers. This turns out to be a hurdle especially when AJAX has to work across many browsers. Browsers which do not support JavaScript or have the JavaScript option disabled will not be able to use its functionality. Due to the AJAX’s dependency on JavaScript, it is not suitable for designing mobile applications. The Back button of your web browser does not work as expected.
-
Insecurity:The webpage can be difficult to debug, increases the code size of your webpage, and makes your webpage prone to severe security threats.
-
Increased load on web server: The load can be increased depending on the user if you are adding an auto-update type that hits the server every few seconds."
9. Describe event bubbling.
Lucy Bain does a great job of explaining event bubbling. Note that the examples are provided so that you as an interviewee can understand them; you do not need to write out the examples in an interview. Simply going through the concepts listed, in your own words, will be more than sufficient.
"Event bubbling occurs when a user interacts with a nested element and the event propagates up (“bubbles”) through all of the ancestor elements.
HTML
<div class="ancestor">
<div class="parent">
<button> Click me! </button>
</div>
</div>
When a user clicks the button the event first fires on the button itself, then bubbles up to the parent div, and then up to the ancestor div. The event would continue to bubble up through all the ancestors, until it finally reaches thedocument
.
JavaScript
$( "button" ).click(function(event) {
console.log( "button was clicked!" );
});
$( ".parent" ).click(function(event) {
console.log( "child element was clicked!" );
});
$( ".ancestor" ).click(function(event) {
console.log( "descendant element was clicked!" );
});
When the user clicks the button the events starts at the button element, so button was clicked!
is logged to the console. Then child element was clicked!
and finally descendant element was clicked!
are logged as well.
Stopping Event Bubbling
What if you don’t want the event to bubble up?
A fair question. Often you only want the event to trigger on the element itself, without bothering all its ancestors. Consider the following JS (with the same HTML as above):
$( "button" ).click(function(event) {
console.log( "button was clicked!" );
});
$( ".parent, .ancestor" ).click(function(event) {
console.log( "don't click me!" );
});
As it stands, the don't click me!
will get logged when the user clicks on the button, even though they haven’t actually clicked on the parent or ancestor element.
You have to explicitly stop event propagation (bubbling) if you don’t want it.
$( "button" ).click(function(event) {
event.stopPropagation(); // <-- this line here!
console.log( "button was clicked!" );
});
$( ".parent, .ancestor" ).click(function(event) {
console.log( "don't click me!" );
});
Now the event propagation stops on the first element of the bubbling sequence. You can also stop the bubbling later on if you'd like; it doesn’t have to be on the first element."
10. How does hoisting work in JavaScript?
Function hoisting is a feature in JavaScript that allows functions to be used even if they're declared later in the application (but in the same execution context).
Here's an example from MDN:
catName("Chloe");
function catName(name) {
console.log("My cat's name is " + name);
}
/*
The result of the code above is: "My cat's name is Chloe"
*/
According to MDN, the way hoisting works is that "variable and function declarations are put into memory during the compile phase, but stays exactly where you typed it in your coding."
11. Explain the difference between synchronous and asynchronous functions.
Bisque does a good job of explaining the difference between asynchronous and synchronous execution (same concept as sync and aync functions):
"The difference between synchronous and asynchronous execution may seem a bit confusing at first. Program execution in most high-level languages is usually very straightforward. Your program starts at the first line of source code and each line of code executed sequentially thereafter. Easy enough.
Synchronous program execution is somewhat similar to the above. Your program is executed line by line, one line at a time. Each time a function is called, program execution waits until that function returns before continuing to the next line of code.
This method of execution can have undesirable ramifications. Suppose a function is called to start a time consuming process. What if you want to stop the lengthy process? With synchronous execution, your program is “stuck,” waiting for the process to end, with no way out.
Asynchronous execution avoids this bottleneck. You are essentially saying, “I know this function call is going to take a great deal of time, but my program doesn’t want to wait around while it executes.”
12. Describe the difference between a cookie, sessionStorage, and localStorage.
According to MDN, "An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user's web browser. The browser may store it and send it back with the next request to the same server. Typically, it's used to tell if two requests came from the same browser—keeping a user logged-in, for example. It remembers stateful information for the stateless HTTP protocol.
Cookies are mainly used for three purposes:
Session Management
Logins, shopping carts, game scores, or anything else the server should remember
Personalization
User preferences, themes, and other settings
Tracking
Recording and analyzing user behavior
Cookies were once used for general client-side storage. While this was legitimate when they were the only way to store data on the client, it is recommended nowadays to prefer modern storage APIs. Cookies are sent with every request, so they can worsen performance (especially for mobile data connections). Modern APIs for client storage are the Web storage API (localStorage
andsessionStorage
) and IndexedDB."
There are many sites that still use cookies for client storage, but now let's give a description about the newer Web storage APIs, also from MDN:
sessionStorage
maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).localStorage
does the same thing, but persists even when the browser is closed and reopened.
13. What is a JavaScript callback function?
According to MDN, "A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action."
JavaScript callback functions are often (but not necessarily) seen after an asynchronous function has finished, calling the callback function to execute.
14. What is NaN? What is its type? How can you reliably test if a value is equal to NaN?
A good answer has been given by Toptal:
"TheNaN
property represents a value that is “not a number." This special value results from an operation that could not be performed either because one of the operands was non-numeric (e.g.,"abc" / 4
), or because the result of the operation is non-numeric (e.g., an attempt to divide by zero).
While this seems straightforward enough, there are a couple of somewhat surprising characteristics of NaN
that can result in hair-pulling bugs if one is not aware of them.
For one thing, although NaN
means “not a number,” its type is, believe it or not, Number
:
console.log(typeof NaN === "number"); // logs "true"
Additionally, NaN
compared to anything—even itself!—is false:
console.log(NaN === NaN); // logs "false"
A semi-reliable way to test whether a number is equal to NaN is with the built-in function isNaN()
, but even using isNaN()
is an imperfect solution.
A better solution would either be to use value !== value
, which would only produce true if the value is equal to NaN. Also, ES6 offers a new Number.isNaN()
function, which is a different and more reliable than the old global isNaN()
function."
15. What is a potential pitfall when using typeof bar === "object"
to determine if bar is an object? How can this pitfall be avoided?
Here is another comprehensive answer from Toptal:
Although typeof bar === "object"
is a reliable way of checking if bar
is an object, the surprising gotcha in JavaScript is tha null
is also considered an object!
Therefore, the following code will, to the surprise of most developers, log true
(not false
) to the console:
var bar = null;
console.log(typeof bar === "object"); // logs true!
As long as one is aware of this, the problem can easily be avoided by also checking if bar
is null
:
console.log((bar !== null) && (typeof bar === "object")); // logs false
To be entirely thorough in our answer, there are two other things worth noting:
First, the above solution will return false
if bar
is a function. In most cases, this is the desired behavior, but in situations where you want to also return true
for functions, you could amend the above solution to be:
console.log((bar !== null) && ((typeof bar === "object") || (typeof bar === "function")));
Second, the above solution will return true
if bar
is an array (e.g., if var bar = [];
). In most cases, this is the desired behavior, since arrays are indeed objects, but in situations where you want to also return false
for arrays, you could amend the above solution to be:
console.log((bar !== null) && (typeof bar === "object") && (toString.call(bar) !== "[object Array]"));
However, there’s one other alternative that returns false
for nulls, arrays, and functions, but true
for objects:
console.log((bar !== null) && (bar.constructor === Object));
16. What is an event loop in JavaScript?
Hackernoon has a good explanation for the event loop:
"This is a constantly running process that checks if the call stack is empty. Imagine it like a clock and every time it ticks, it looks at the Call Stack, and if it is empty, it looks into the Event Queue. If there is something in the event queue that is waiting, it is moved to the call stack. If not, then nothing happens."
A good video of the event loop can be found here.
17. In what order will the numbers 1–4 be logged to the console when the code below is executed? Why?
(function() {
console.log(1);
setTimeout(function(){console.log(2)}, 1000);
setTimeout(function(){console.log(3)}, 0);
console.log(4);
})();
The question and answer comes from Toptal:
"The values will be logged in the following order:
1
4
3
2
Let’s first explain the parts of this that are presumably more obvious:
-
1
and4
are displayed first since they are logged by simple calls toconsole.log()
without any delay. -
2
is displayed after3
because2
is being logged after a delay of 1000 msecs (i.e., 1 second), whereas3
is being logged after a delay of 0 msecs.
OK, fine. But if 3
is being logged after a delay of 0 msecs, doesn’t that mean that it is being logged right away? And, if so, shouldn’t it be logged before 4
, since 4
is being logged by a later line of code?
The answer has to do with properly understanding JavaScript events and timing.
The browser has an event loop which checks the event queue and processes pending events. For example, if an event happens in the background (e.g., a script onload
event) while the browser is busy (e.g., processing an onclick
), the event gets appended to the queue. When the onclick handler is complete, the queue is checked and the event is then handled (e.g., the onload
script is executed).
Similarly, setTimeout()
also puts execution of its referenced function into the event queue if the browser is busy.
When a value of zero is passed as the second argument to setTimeout()
, it attempts to execute the specified function “as soon as possible." Specifically, execution of the function is placed on the event queue to occur on the next timer tick. Note, though, that this is not immediate; the function is not executed until the next tick. That’s why in the above example, the call to console.log(4)
occurs before the call to console.log(3)
(since the call to console.log(3)
is invoked via setTimeout, so it is slightly delayed)."
18. What is a “closure” in JavaScript? Provide an example.
Toptal provides this question and answer. However, be sure not to just memorize the answers given here; try to explain them in your own words instead.
"A closure is an inner function that has access to the variables in the outer (enclosing) function’s scope chain. The closure has access to variables in three scopes; specifically: (1) variable in its own scope, (2) variables in the enclosing function’s scope, and (3) global variables.
Here is an example:
var globalVar = "xyz";
(function outerFunc(outerArg) {
var outerVar = 'a';
(function innerFunc(innerArg) {
var innerVar = 'b';
console.log(
"outerArg = " + outerArg + "\n" +
"innerArg = " + innerArg + "\n" +
"outerVar = " + outerVar + "\n" +
"innerVar = " + innerVar + "\n" +
"globalVar = " + globalVar);
})(456);
})(123);
In the above example, variables from innerFunc
,outerFunc
, and the global namespace are all in scope in the innerFunc
. The above code will therefore produce the following output:
outerArg = 123
innerArg = 456
outerVar = a
innerVar = b
globalVar = xyz
19. Explain the purpose of each of the HTTP request types when used with a RESTful web service.
Java Revisited has a fully detailed explanation:
"The purpose of each of the HTTP request types, when used with a RESTful web service, is as follows:
GET
Retrieves data from the server (should only retrieve data and should have no other effect). This is also called an idempotent method. Here is an example of a GET request to retrieve the book with id 123 from Server.
GET /books/123
POST
This HTTP request type is usually used for creating an entity, i.e., a resource without an id. Once the request is successfully created, an id of the newly created entity is returned as part of the response to this HTTP request. It is often used when uploading a file or submitting a completed web form.
For example, the following URL will create a new book in the server:
POST
POST /books/
PUT
Similar to POST, but used to update an existing entity. You pass the id of existing resource along with the PUT request type. For example, the following URL will replace the book with id 123 in the server:
PUT /books/123
DELETE
Removes the resource from the server. Similar to PUT, you need to pass the id of the resource to be deleted. For example, the following URL will remove the book with id 123 in the server:
DELETE /books/123
Note: In the answer above, we have left out references to other, lesser used HTTP methods, but the full article does provide an example for each of those.
20. What does CORS stand for, and what issue does it address?
Blake Allen gives a good explanation to this question on Quora:
"Cross Origin Resource Sharing.
This is all because of JavaScript. On the web, it’s a huge risk to have JavaScript running that you can’t confirm came from the right source. Taken from Wikipedia: “In computing, the same-origin policy is an important concept in the web application security model. Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin. An origin is defined as a combination of URI scheme, hostname, and port number.
This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's Document Object Model. “
This can be pretty limiting. So, for instance, say you want to send and receive data to and from multiple servers and make a single page application. This is where CORS comes in.
CORS allows resource sharing from across a different origin, or cross-domain requests."
21. What are the differences between variables created using let
, var
, and const
?
Eric Elliot provides a good explanation:
const
is a signal that the identifier won’t be reassigned.
let
is a signal that the variable may be reassigned, such as a counter in a loop, or a value swap in an algorithm. It also signals that the variable will be used only in the block it’s defined in, which is not always the entire containing function.
var
is now the weakest signal available when you define a variable in JavaScript.The variable may or may not be reassigned, and the variable may or may not be used for an entire function, or just for the purpose of a block or loop.
22. Explain the use cases for and differences between bind
, apply
, and call
.
A concise answer for this can be found on GitHub here:
bind
is used when we want to apply a context to function to be called later.
apply
takes the context passed to it and performs the function call.
call
is essentially the same as apply
, except that it requires the parameters be listed, whereas apply
can take the arguments
object as an argument.
A more detailed response can be found here.
23. What is the difference between GET and POST?
This question and answer comes from Toptal:
"Both are methods used in HTTP requests. Generally it is said that GET is to download data and PUT is to upload data. But we can do both downloading as well as uploading either by GET/POST.
GET
- If we are sending parameters in a GET request to the server, then those parameters will be visible in the URL, because in GET, parameters are append to the URL. So there’s a lack of security while uploading to the server.
- We can only send a limited amount of data in a GET request, because the URL has its max limit and we cannot append a long data string to the URL.
POST
- If we are using POST, then we are sending parameters in the body section of a request. If we send data after using encryption in the body of an HTTP request, it’s quite a bit more secure.
- We can send a lot more data using POST.
Note: GET is faster in the case of just getting data using a static API call in cases where we don’t have to pass any parameters."
24. What is the significance, and what are the benefits, of including use strict
at the beginning of a JavaScript source file?
This question and answer comes from Toptal. Note that the first paragraph is generally a good enough answer. However, you can ask the interviewer if they would like you to go into more detail. If so, proceed with the key benefits (again, don't memorize, just put into your own words).
"The short and most important answer here is that use strict
is a way to voluntarily enforce stricter parsing and error handling on your JavaScript code at runtime. Code errors that would otherwise have been ignored or would have failed silently will now generate errors or throw exceptions. In general, it is a good practice.
Some of the key benefits of strict mode include:
- Makes debugging easier. Code errors that would otherwise have been ignored or would have failed silently will now generate errors or throw exceptions, alerting you sooner to problems in your code and directing you more quickly to their source.
- Prevents accidental globals. Without strict mode, assigning a value to an undeclared variable automatically creates a global variable with that name. This is one of the most common errors in JavaScript. In strict mode, attempting to do so throws an error.
- Eliminates
this
coercion. Without strict mode, a reference to athis
value of null or undefined is automatically coerced to the global. This can cause many headfakes and pull-out-your-hair kind of bugs. In strict mode, referencing a athis
value of null or undefined throws an error. - Disallows duplicate parameter values.
Strict mode throws an error when it detects a duplicate named argument for a function (e.g.,
function foo(val1, val2, val1){}
), thereby catching what is almost certainly a bug in your code that you might otherwise have wasted lots of time tracking down. - Note: It used to be (in ECMAScript 5) that strict mode would disallow duplicate property names (e.g.,
var object = {foo: "bar", foo: "baz"};
) but as of ECMAScript 2015 this is no longer the case. - Makes eval() safer.
There are some differences in the way
eval()
behaves in strict mode and in non-strict mode. Most significantly, in strict mode, variables and functions declared inside of aneval()
statement are not created in the containing scope (they are created in the containing scope in non-strict mode, which can also be a common source of problems). - Throws error on invalid usage of
delete
. Thedelete
operator (used to remove properties from objects) cannot be used on non-configurable properties of the object. Non-strict code will fail silently when an attempt is made to delete a non-configurable property, whereas strict mode will throw an error in such a case."
25. How do you clone an object?
This question and answer comes from Toptal.
var obj = {a: 1 ,b: 2}
var objclone = Object.assign({},obj);
Now the value of objclone is {a: 1 ,b: 2}
but points to a different object than obj
.
Note the potential pitfall, though: Object.clone()
will just do a shallow copy, not a deep copy. This means that nested objects aren’t copied. They still refer to the same nested objects as the original:
let obj = {
a: 1,
b: 2,
c: {
age: 30
}
};
var objclone = Object.assign({},obj);
console.log('objclone: ', objclone);
obj.c.age = 45;
console.log('After Change - obj: ', obj); // 45 - This also changes
console.log('After Change - objclone: ', objclone); // 45
26. How do you add an element at the beginning of an array? How do you add one at the end?
This question and answer comes from Toptal.
var myArray = ['a', 'b', 'c', 'd'];
myArray.push('end');
myArray.unshift('start');
console.log(myArray); // ["start", "a", "b", "c", "d", "end"]
With ES6, one can use the spread operator:
myArray = ['start', ...myArray];
myArray = [...myArray, 'end'];
Or, in short:
myArray = ['start', ...myArray, 'end'];
27. What is the value of typeof undefined == typeof NULL
?
This question and answer comes from Toptal.
"The expression will be evaluated to true, since NULL
will be treated as any other undefined variable.
Note: JavaScript is case-sensitive and here we are using NULL
instead of null
.