JS Interview Questions

Size
7,121 Kb
Views
4,048

How do I make an js interview questions?

What is a js interview questions? How do you make a js interview questions? This script and codes were developed by Martin Baillie on 25 January 2023, Wednesday.

JS Interview Questions Previews

JS Interview Questions - Script Codes HTML Codes

<!DOCTYPE html>
<html >
<head> <meta charset="UTF-8"> <title>JS Interview Questions</title>
</head>
<body> <script src="js/index.js"></script>
</body>
</html>

JS Interview Questions - Script Codes JS Codes

/* * https://www.toptal.com/javascript/interview-questions
*/
// testing for objects and arrays
var bar = {};
console.log('is this an object', bar !== null && typeof bar === 'object');
bar = [];
console.log('is this an object and not array', bar !== null && typeof bar === 'object' && toString.call(bar) !== '[object Array]');
// b = 3; var a = b; No strict mode so no runtime error on b so assigned to global object.
(function(){ var a = b = 3;
})();
console.log('a defined? ' + (typeof a !== 'undefined'));
console.log('b defined? ' + (typeof b !== 'undefined'));
// See how the context changes the scope.
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() { var baz = 'boo' console.log("inner func: this.foo = " + this.foo); console.log("inner func: self.foo = " + self.foo); }()); }
};
myObject.func();
var myObjFunc = myObject.func;
myObjFunc();
myObjFunc.call(myObject);
/*
What is the significance of, and reason for, wrapping the entire content of a JavaScript source file in a function block?
This is an increasingly common practice, employed by many popular JavaScript libraries (jQuery, Node.js, etc.). This technique creates a closure around the entire contents of the file which, perhaps most importantly, creates a private namespace and thereby helps avoid potential name clashes between different JavaScript modules and libraries.
*/
/*
What is the significance, and what are the benefits, of including 'use strict' at the beginning of a JavaScript source file?
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 a this 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 this value of null or undefined throws an error.
* Disallows duplicate property names or parameter values. Strict mode throws an error when it detects a duplicate named property in an object (e.g., var object = {foo: "bar", foo: "baz"};) or 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.
* 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 an eval() 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. The delete 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.
*/
// What is NaN? What is its type? How can you reliably test if a value is equal to NaN?
// NaN means 'not a number'
var value = NaN;
console.log(value + ' means "not a number"');
console.log('it\'s type is "number" ' + (typeof value === "number"));
console.log('to test for NaN test that it doesn\'t equal itself!', value !== value);
// What will the code below output? Explain your answer.
// It will output 0.30000000000000004 and false.
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 == 0.3);
// Discuss possible ways to write a function isInteger(x) that determines if x is an integer.
var isInteger = function(x) { return typeof x === 'number' && x % 1 === 0;
};
var isIntegerCleanest = function(x) { return (x^0) === x;
};
console.log('is 1 an integer', isInteger(1));
console.log('is 1.1 an integer', isInteger(1.1));
console.log('is [] an integer', isInteger([]));
console.log('is {} an integer', isIntegerCleanest({}));
console.log('is "HELLO" an integer', isIntegerCleanest('HELLO'));
// 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 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 and 4 are displayed first since they are logged by simple calls to console.log() without any delay
2 is displayed after 3 because 2 is being logged after a delay of 1000 msecs (i.e., 1 second) whereas 3 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 ( http://javascript.info/tutorial/events-and-timing-depth ).
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).
*/
var isPalindrome = function (str) { str = str.replace(/\W/g, '').toLowerCase(); return str == str.split('').reverse().join('');
};
console.log('is palindrome', isPalindrome("xyx"));
// Write a sum method which will work properly when invoked using either syntax below.
// console.log(sum(2,3)); // Outputs 5
// console.log(sum(2)(3)); // Outputs 5
function sum(x, y) { return x + y;
};
function sum2(x) { return function (y) { return x + y; };
};
function sum3(x, y) { if (y !== undefined) { return x + y; } else { return function (y) { return x + y; }; }
};
console.log('sum: 2 + 3 is', sum(2,3)); // Outputs 5
console.log('sum2: 2 + 3 is', sum2(2)(3)); // Outputs 5
console.log('sum3: 2 + 3 is', sum3(2,3)); // Outputs 5
console.log('sum3: 2 + 3 is', sum3(2)(3)); // Outputs 5
// (a) What gets logged to the console when the user clicks on “Button 4” and why?
// It returns '5'. So do all the other buttons. Because the event listener returns the value of i as it is now, when the
// event is triggered, not as it was when the event was set.
// No matter what button the user clicks the number 5 will always be logged to the console. This is because, at the point
// that the onclick method is invoked (for any of the buttons), the for loop has already completed and the variable i
// already has a value of 5. (Bonus points for the interviewee if they know enough to talk about how execution contexts,
// variable objects, activation objects, and the internal “scope” property contribute to the closure behavior.)
for (var i = 0; i < 5; i++) { var btn = document.createElement('button'); btn.appendChild(document.createTextNode('Button ' + i)); btn.addEventListener('click', function(){ console.log(i); }); document.body.appendChild(btn);
}
// (b) Provide one or more alternate implementations that will work as expected.
// The key to making this work is to capture the value of i at each pass through the for loop by passing it into a
// newly created function object. Here are three possible ways to accomplish this:
for (var i = 0; i < 5; i++) { var btn = document.createElement('button'); btn.appendChild(document.createTextNode('Button ' + i)); btn.addEventListener('click', (function(i){ return function() { console.log(i); }; })(i)); document.body.appendChild(btn);
}
//Alternatively, you could wrap the entire call to btn.addEventListener in the new anonymous function:
for (var i = 0; i < 5; i++) { var btn = document.createElement('button'); btn.appendChild(document.createTextNode('Button ' + i)); (function (i) { btn.addEventListener('click', function() { console.log(i); }); })(i); document.body.appendChild(btn);
}
// Or, we could replace the for loop with a call to the array object’s native forEach method:
['a', 'b', 'c', 'd', 'e'].forEach(function (value, i) { var btn = document.createElement('button'); btn.appendChild(document.createTextNode('Button ' + i)); btn.addEventListener('click', function() { console.log(i); }); document.body.appendChild(btn);
});
// What will the code below output to the console and why?
// "array 1: length=5 last=j,o,n,e,s" and "array 2: length=5 last=j,o,n,e,s"
// because arr2 is a reference to arr1. And arr3 was pushed onto arr2, making it the last value.
var arr1 = 'john'.split('');
var arr2 = arr1.reverse();
var arr3 = 'jones'.split('');
arr2.push(arr3);
console.log("array 1: length=" + arr1.length + " last=" + arr1.slice(-1));
console.log("array 2: length=" + arr2.length + " last=" + arr2.slice(-1));
// What will the code below output to the console and why ?
console.log(1 + "2" + "2"); // "122"
console.log(1 + +"2" + "2"); // "32"
console.log(1 + -"1" + "2"); // "02"
console.log(+"1" + "1" + "2"); // "112"
console.log( "A" - "B" + "2"); // "NaN2"
console.log( "A" - "B" + 2); // NaN
//The following recursive code will cause a stack overflow if the array list is too large.
// How can you fix this and still retain the recursive pattern?
function readHugeList() { return [1,2,3,4];
}
var list = readHugeList();
var nextListItem = function() { var item = list.pop(); if (item) { // process the list item... nextListItem(); }
};
// The potential stack overflow can be avoided by modifying the nextListItem function as follows:
var list = readHugeList();
var nextListItem = function() { var item = list.pop(); if (item) { // process the list item... setTimeout( nextListItem, 0); }
};
/*
The stack overflow is eliminated because the event loop handles the recursion, not the call stack. When nextListItem runs, if item is not null, the timeout function (nextListItem) is pushed to the event queue and the function exits, thereby leaving the call stack clear. When the event queue runs its timed-out event, the next item is processed and a timer is set to again invoke nextListItem. Accordingly, the method is processed from start to finish without a direct recursive call, so the call stack remains clear, regardless of the number of iterations.
*/
// Their 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);
/*
Explanation: 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.
*/
/*
Kyle Simpson's explanation: "Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope."
*/
/*
The below is not quite closure. bar() has a 'closure' over the scope of foo() (and all the other scopes it has access to such as global). Can also be expressed as bar() closes over the scope of foo() because bar() appears nested inside of foo(). But closure is not observable here. PP48 Scope & Closures
*/
function foo() { var a = 2; function bar() { console.log('foo() > bar()', a) // 2 } bar();
}
foo();
// to observe closure...
function foo3() { var a = 2 function bar3() { console.log('closure observed', a ); } return bar3;
}
var baz3 = foo3()
baz3(); // 2 closure observed!
// Callbacks are closures.
function foo2() { var a = 2; function baz2() { console.log('callback closure', a); // 2 } bar2( baz2 );
}
function bar2(fn){ fn(); // execute callback. It's a closure!
}
foo2();
// The timer function closure error
for (var i = 1; i <= 5; i++) { setTimeout( function timer1() { // console.log('timer loop', i); }, i*100);
}
// timer function loop that works
for (var i = 1; i <= 5; i++) { (function(j){ setTimeout( function timer2() { // console.log('timer loop that works', j); }, j*100); })(i);
}
for (var i = 1; i <= 5; i++) { (function iifeLoop() { // console.log('IIFE loop', i) })();
}
for (var i = 1; i <= 5; i++) { function functionDeclarationLoop() { // console.log('function declaration loop', i) }; functionDeclarationLoop();
}
for (var i = 1; i <= 5; i++) { function functionInvocationOutsideLoop() { // console.log('function invocation outside loop', i) };
}
functionInvocationOutsideLoop();
// ES6 solution
for ( let i = 1; i <= 5; i++ ){ setTimeout( function timer(){ // console.log('ES6 loop and let', i ); }, i * 100 );
}
// IIFEs are not observed closure. the function is not executed outside of its lexical scope.
// It does however create scope. it creates scope that can be closed over.
var ed = 2;
(function IIFE2(){ console.log('IIFE2', ed);
})();
/* * Modules */
// no observable closure. It's there - doSomethign has closure over foo4, but you can't see it.
function foo4() { var something = 'cool'; var another = [1, 2, 3]; function doSomething() { console.log( something ); } function doAnother() { console.log( another.join( " ! " ) ); }
}
// revealing module pattern - called revealing because the public methods are hidden behind the
// returned object inside the module.
function CoolModule() { var something = 'cool'; var another = [1, 2, 3]; var testing = "test123"; function doSomething() { console.log('cm1', something ); } function doAnother() { console.log('cm1', another.join( " ! " ) ); } return { doSomething: doSomething, doAnother: doAnother, test: function () { console.log(testing); } };
}
var coolModule = CoolModule();
coolModule.doSomething(); // cool
coolModule.doAnother(); // 1 ! 2 ! 3
coolModule.test(); // "test123"
// A variation on the module pattern is the singleton, using an IIFE and a function expression.
var coolModule2 = (function CoolModule2() { var something = 'cool'; var another = [1, 2, 3]; function doSomething() { console.log('cm2', something ); } function doAnother() { console.log('cm2', another.join( " ! " ) ); } return { doSomething: doSomething, doAnother: doAnother };
})();
coolModule2.doSomething(); // cool
coolModule2.doAnother(); // 1 ! 2 ! 3
// using a named public api.
// this enables you to change the implementation of the wihtout affecting the interface (API)
function CoolModule3(id) { function change() { // modifying the public API publicAPI.identify = identify2; } function identify1() { console.log( id ); } function identify2() { console.log( id.toUpperCase() ); } var publicAPI = { change: change, identify: identify1 }; return publicAPI;
}
coolModule3 = CoolModule3( "foo module" );
coolModule3.identify(); // foo module
coolModule3.change();
coolModule3.identify(); // FOO MODULE
JS Interview Questions - Script Codes
JS Interview Questions - Script Codes
Home Page Home
Developer Martin Baillie
Username martin42
Uploaded January 25, 2023
Rating 3
Size 7,121 Kb
Views 4,048
Do you need developer help for JS Interview Questions?

Find the perfect freelance services for your business! Fiverr's mission is to change how the world works together. Fiverr connects businesses with freelancers offering digital services in 500+ categories. Find Developer!

Martin Baillie (martin42) Script Codes
Create amazing web content with AI!

Jasper is the AI Content Generator that helps you and your team break through creative blocks to create amazing, original content 10X faster. Discover all the ways the Jasper AI Content Platform can help streamline your creative workflows. Start For Free!