Check questions and answers by category: for Juniors, Middle and Senior Developers. Choose either theoretical or practical questions. If you have anything to add, please leave a comment.
JavaScript Question № 1 Practical for Senior
How to compare two objects with nested properties in JavaScript?
First sample
| JSON.stringify(obj1) === JSON.stringify(obj2) // but order of keys matters |
Second sample
| // Using Lodash _.isEqual(obj1, obj2); // need to refactor |
JavaScript Question № 2 Theoretical for Middle
List special numeric values.
Infinity is greater than any number
-Infinity is less than any number
NaN represents an error (not a number)
| Infinity - Infinity // NaN |
JavaScript Question № 3 Theoretical for Senior
Explain the Map , Set , WeakMap and WeakSet .
Map is a collection of keyed data items, just like an Object . But the main difference is that Map allows keys of any type.
A Set is a collection of values, where each value may occur only once.
WeakSet is a special kind of Set that does not prevent JavaScript from removing its items from memory. WeakMap is the same thing for Map .
JavaScript Question № 4 Theoretical for Middle
List the methods to search in an array.
The methods arr.indexOf , arr.lastIndexOf and arr.includes have the same syntax and do essentially the same as their string counterparts, but operate on items instead of characters:
- arr.indexOf(item, from) looks for item starting from index from, and returns the index where it was found, otherwise -1.
- arr.lastIndexOf(item, from) – same, but looks for from right to left.
- arr.includes(item, from) – looks for item starting from index from, returns true if found.
The find method looks for a single (first) element that makes the function return true.
The arr.findIndex method is essentially the same, but it returns the index where the element was found instead of the element itself and -1 is returned when nothing is found.
The filter method looks for elements that make the function return true.
JavaScript Question № 5 Theoretical for Middle
What is the purpose of the file package-lock.json ?
package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json . It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.
JavaScript Question № 6 Theoretical for Junior
What’s the difference between using “var”, “let”, and “const”?
The difference is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block. Both are global if outside any block.
Also, variables declared with let are not accessible before they are declared in their enclosing block. As seen in the demo, this will throw a ReferenceError exception.
JavaScript Question № 7 Theoretical for Middle
What is Cross-Origin Requests and CDN?
If we make a fetch from an arbitrary web-site, that will probably fail.
The core concept here is origin – a domain/port/protocol triplet.
Cross-origin requests – those sent to another domain (even a subdomain) or protocol or port – require special headers from the remote side. That policy is called “CORS”: Cross-Origin Resource Sharing.
A CDN (Content Delivery Network) is a group of servers spread out over many locations. These servers store duplicate copies of data so that servers can fulfill data requests based on which servers are closest to the respective end-users. CDNs make for fast service less affected by high traffic.
JavaScript Question № 8 Practical for Middle
Does it make sense to add directive ‘use strict’ in modern scripts?
Yes, it still makes sense, but Babel adds ‘use strict’ during transpilation by default.
JavaScript’s strict mode, introduced in ECMAScript 5, is a way to opt in to a restricted variant of JavaScript, thereby implicitly opting-out of “sloppy mode”. Strict mode isn’t just a subset: it intentionally has different semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don’t rely on strict mode without feature-testing for support for the relevant aspects of strict mode. Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally.
JavaScript Question № 9 Theoretical for Middle
A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.
JavaScript Question № 10 Practical for Middle
Improve the code using ES6
| //sample let person = { name: 'Anna', age: 56, job: { company: 'Tesco', title: 'Manager' } }; function getInfo(person) { var age = person.age, yearOfBirth = 2018 - age, name = person.name, company = person.job.company; console.log(`${ name } works at ${ company } and was born in ${ yearOfBirth }.`); } |
| function getInfo({ age, name, job: { company } }) { var yearOfBirth = 2018 - age; console.log(`${ name } works at ${ company } and was born in ${ yearOfBirth }.`); } |
JavaScript Question № 11 Practical for Middle
Write an example of testing the sum function.
| function sum(a, b) { return a + b; } // using Mocha describe("sum", function() { it("adds two numbers", function() { assert.equal(sum(7, 8), 15); assert.equal(sum(13, 14), 27); }); }) |
JavaScript Question № 12 Theoretical for Junior
How to show the user a notification that javascript is not enabled by his browser?
| <noscript>Your browser does not support JavaScript!</noscript> |
JavaScript Question № 13 Practical for Senior
Give webpack config sample for scss using.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // webpack.config.js module.exports = { ... module: { rules: [{ test: /\.scss$/, use: [{ loader: "style-loader" }, { loader: "css-loader" }, { loader: "sass-loader", options: { includePaths: ["absolute/path/a", "absolute/path/b"] } }] }] } }; |
JavaScript Question № 14 Theoretical for Junior
Why is the order of adding scripts to the page important?
| // Libraries should be added earlier than the scripts that use them. For example, the next fragment will result in an error “Uncaught ReferenceError: jQuery is not defined” <script src="js/jquery.easing.js"></script> <script src="js/jquery.js"></script> |
JavaScript Question № 15 Practical for Senior
Create a script to lazy load the images shown after scrolling.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | let lazyImages = [...document.querySelectorAll('.lazy-image')] let inAdvance = 300 function lazyLoad() { lazyImages.forEach(image => { if (image.offsetTop < window.innerHeight + window.pageYOffset + inAdvance) { image.src = image.dataset.src image.onload = () => image.classList.add('loaded') } }) // if all loaded removeEventListener } lazyLoad() window.addEventListener('scroll', _.throttle(lazyLoad, 16)) window.addEventListener('resize', _.throttle(lazyLoad, 16)) |
JavaScript Question № 16 Theoretical for Junior
How to get the current URL?
| window.location.href document.URL |
JavaScript Question № 17 Practical for Middle
Write a builder class to create developer instances.
| //Sample const developer = new DeveloperBuilder('John') .addSkill('ES6') .addSkill('TypeScript') .setFramework('React'); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class DeveloperBuilder { constructor(name) { this.name = name this.skills = [] } addSkill(skill) { this.skills.push(skill); return this } setFramework(framework) { this.framework = framework return this } } |
JavaScript Question № 18 Practical for Senior
Create a rectangle object with a private width and public height using the Revealing Module Pattern.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | var rectModule = (function() { 'use strict'; var _width = 20; var height = 30; function setHeight(val) { height = val; } function getArea() { return _width * height; } return { height: height, setHeight: setHeight, getArea: getArea }; }()); console.clear(); console.log(rectModule.getArea()); // 600 console.log(rectModule.width); // undefined console.log(rectModule.height); // 30 rectModule.setHeight(10); console.log(rectModule.getArea()); // 200 |
JavaScript Question № 19 Practical for Senior
Create a function that will receive an estimate as the input and output the average of all previously obtained estimates.
| // add the code here setRate(5); // 5 setRate(3); // 4 setRate(4); // 4 setRate(0); // 3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function rateFunc() { var accumObj = { count: 0, sum: 0 } return function(rate) { accumObj.count += 1; accumObj.sum += rate; return Math.round(accumObj.sum / accumObj.count); } } var setRate = rateFunc(); setRate(5); // 5 setRate(3); // 4 setRate(4); // 4 setRate(0); // 3 |
JavaScript Question № 20 Practical for Senior
Write Observer pattern sample.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | function Model(){ var self = this; var heading = "Hello" this.observers = []; this.registerObserver = function(observer){ self.observers.push(observer); } this.notifyAll = function(){ self.observers.forEach(function(observer){ observer.update(self); }) } Object.defineProperty(this,"heading",{ get: function() { return heading; }, set: function(value) { heading = value; //call notifyAll in the assignment function this.notifyAll(); } }); } |
JavaScript Question № 21 Practical for Middle
Improve the code using classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | //Sample function Person(name, lastName) { this.name = name; this.lastName = lastName; } Person.prototype.getFullName = function() { return this.name + " " + this.lastName; }; function Developer(skills, name, lastName) { this._super.call(this, name, lastName); this.skills = skills; } Developer.prototype = Object.create(Person.prototype); Developer.prototype.constructor = Developer; Developer.prototype._super = Person; Developer.prototype.getDeveloperInfo = function() { return this.name + " " + this.lastName + ", skills: " + this.skills; }; var developer = new Developer("JavaScript, React, Redux", "John", "Doe"); console.log(developer.getFullName()); console.log(developer.getDeveloperInfo()); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class Person { constructor(name, lastName) { this.name = name; this.lastName = lastName; } getFullName () { return this.name + " " + this.lastName; } } class Developer extends Person { constructor(skills, name, lastName) { super(name, lastName); this.skills = skills; } getDeveloperInfo() { return this.name + " " + this.lastName + ", skills: " + this.skills; } } var developer = new Developer("JavaScript, React, Redux", "John", "Doe"); console.log(developer.getFullName()); console.log(developer.getDeveloperInfo()); |
JavaScript Question № 22 Practical for Middle
What is output?
| i = 10; var j = 1; for(var i=1; i < 5; i++) { j++; } console.log(i); console.log(j++); |
| i=5 // the variable will be strict equal to 5 and only then the cycle will end j=5 // the last increase of the variable will occur after output to the console |
JavaScript Question № 23 Practical for Senior
How to get the sum of even numbers if the sum of array elements is even and the sum of odd numbers if the sum of array elements is odd? Complete the function without using additional variables.
| // store sum, evenSum and evenFlag // create an example function getOddOrEvenSum(arr) { var a = 0; var b = 0; arr.forEach(function(number) { // place for code }); // place for code } var arr = [1, 2, 3, 4, 5, 10, 11]; console.log(getOddOrEvenSum(arr)) |
| function getOddOrEvenSum(arr) { var a = 0; // sum of all numbers var b = 0; // sum of even numbers arr.forEach(function(number) { a += number; if (number % 2 === 0) { b += number; } }); return (a % 2) ? a - b : b; } var arr = [1, 2, 3, 4, 5, 10, 11]; console.log(getOddOrEvenSum(arr)) |
JavaScript Question № 24 Practical for Middle
Write a function to find the sum number of array elements using reduce.
| const arr = [11, 29, 5] arr.reduce((sum, num) => sum + num, 0); |
JavaScript Question № 25 Practical for Middle
Write a JavaScript function to check that two words are anagrams (formed by rearranging the letters of another)
| function checkAnagrams(a, b) { return a.split('').sort().join('') === b.split('').sort().join(''); } console.log(checkAnagrams('cinema', 'iceman')); |
JavaScript Question № 26 Practical
How to add your method to the Array object so the following code would work?
| var arr = [1, 2, 3, 4, 5]; var sum = arr.sum(); console.log(sum) |
| Array.prototype.sum = function() { return this.reduce(function(prev, cur) { return prev + cur; }); } |
JavaScript Question № 27 Practical for Junior
How to check that variable is not undefined? How to check that a property exists in an object?
| if (typeof someVar !== "undefined") { // do some stuff } // check property with inheritance if ('someProperty' in object) { // do some stuff } // check property without inheritance if (object.hasOwnProperty('someProperty')) { // do some stuff } |
JavaScript Question № 28 Practical for Senior
What is wrong with this code?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // example with parameters in which strict comparison is important function checkTheYear(initYear, targetYear) { switch(targetYear) { case initYear - 30: console.log('I\'m sure in 1985, plutonium is available at every corner drugstore, but in 1955 it\'s a little hard to come by.'); return true; case initYear - 100: console.log('A hundred years ago? But that\'s now!'); return true; case initYear + 30: console.log('Nobody calls me chicken!') return true; default: console.log('Time traveling is just too dangerous. Better that I devote myself to study the other great mystery of the universe: women!'); return false; } } function backToTheFuture(targetYear) { var timeMachine = { model: 'DeLorean DMC-12', initYear: '1985' } if(checkTheYear(timeMachine.initYear, targetYear)) { // execute the secret code for time travel to the targetYear } } |
| backToTheFuture('198530'); // this year will be validated |
JavaScript Question № 29 Practical for Middle
Write 3 code examples to check whether a string “Soshace” contains a substring “sh”.
| let string = "Soshace", substring = "sh" |
| const string = "Soshace", substring = "sh" console.log(string.includes(substring)); console.log(string.indexOf(substring) !== -1); const regex = /sh/ console.log(regex.test(string)) |
JavaScript Question № 30 Theoretical for Senior
How to forbid adding, removing and changing of object properties?
| // using Object.freeze var user = { name: 'John', age: 35 } Object.freeze(user) user.age = 36; console.log(user.age); // 35 |
JavaScript Question № 31 Practical for Middle
How to update the sample to use previous object constructor?
| function Developer(experience) { this.experience = experience; } Developer.prototype = { skills: ['JavaScript'] }; let senior = new Developer(7); let junior = new senior.constructor(1); console.log( junior.experience ); // undefined |
| // the prototype has been replaced by a plain object and the original constructor is not available // need to avoid replacing the prototype function Developer(experience) { this.experience = experience; this.skills = ['JavaScript'] } let senior = new Developer(7); let junior = new senior.constructor(1); console.log( junior.experience ); // 1 |
JavaScript Question № 32 Practical for Senior
Write a recursive function to create a deep copy of the object
| function cloneObject(obj) { var clone = {}; for(var i in obj) { if(obj[i] != null && typeof(obj[i])=="object") clone[i] = cloneObject(obj[i]); else clone[i] = obj[i]; } return clone; } // todo: check |
JavaScript Question № 33 Practical for Middle
Give code samples for immutable operations using Object.assign and Spread operator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // copying an object const user = { name: 'James', age: 31 } const newUser = Object.assign({}, user, { age: 35 }) const user = { name: 'James', age: 31 } const newUser = { ...user, age: 35 } |
JavaScript Question № 34 Practical for Middle
Update the code to correctly release the button object by the garbage collector.
| <button id="click-me" class="btn">Click Me</button> <script type="text/javascript"> var elements = { button: document.getElementById('click-me'), }; elements.button.onclick = function() { alert('clicked!'); document.body.removeChild(elements.button); } </script> |
| elements.button.onclick = function() { // … delete elements.button } |
JavaScript Question № 35 Practical for Junior
Write a simple function to check that a number is an integer?
| function verifyInt(num) { return num % 1 === 0; } |
JavaScript Question № 36 Practical for Senior
Optimize the function using switch statement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | function getFullPrice(type) { var ticket = 10, luggage = 7, service = 5, taxes = 3, price = 0; switch(type) { case 'ticket': price = ticket; break; case 'luggage': price = ticket + luggage; break; case 'service': price = ticket + luggage + service; break; } price += taxes; return price; } console.log(getFullPrice('ticket')); console.log(getFullPrice('luggage')); console.log(getFullPrice('service')); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | function getFullPrice(type) { var ticket = 10, luggage = 7, service = 5, taxes = 3, price = taxes; switch(type) { case 'service': price += service; case 'luggage': price += luggage; case 'ticket': price += ticket; } return price; } console.log(getFullPrice('ticket')); console.log(getFullPrice('luggage')); console.log(getFullPrice('service')); |
JavaScript Question № 37 Practical for Senior
Provide some shorthand coding techniques using operators “&&” , “||” and “?”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // && sample if (condition) { someMethod(); } condition && someMethod(); // || sample var variable; if (optionalValue !== null || optionalValue !== undefined || optionalValue !== '') { variable = optionalValue; } else { variable = defaultValue; } var variable = optionalValue || defaultValue // ? sample var variable; if (condition) { variable = firstNumber; } else { variable = secondNumber; } var variable = condition ? firstNumber : secondNumber; |
JavaScript Question № 38 Theoretical for Junior
How to stop the setInterval function?
To stop further calls, we should save the value returned by setInterval function and then pass it in clearInterval :
| // repeat with the interval of 1 second let intervalId = setInterval(() => console.log('tick'), 1000); // stop after 10 seconds setTimeout(() => { clearInterval(intervalId); console.log('stop'); }, 10000); |
JavaScript Question № 39 Theoretical for Middle
Explain the output of the code? How to improve this code?
| console.log(1.1 - 0.2) // console output 0.9000000000000001 |
| // We can get the correct result using toFixed +(1.1 - 0.2).toFixed(1) |
Numbers are stored in binary form.
1.1 and 0.2 look simple in the decimal numeric system. But the numbers 10 and 2 (bases of the number systems) have different dividers. In this case, it is required to use a long fractional number. Just as it is impossible to store the number 1/3 in decimal form (1/3 is 0.333333) Therefore, the result of working with float numbers in javascript may be implicit.
JavaScript Question № 40 Theoretical for Junior
What is the difference between the following examples of creating a function?
| function myFunc() { // some logic } and var myFunc = function() { // some logic } |
In the first example, the function can be called at the beginning of the script. In the second – only after its initialization.
JavaScript Question № 41 Practical for Senior
Write a JavaScript function that accepts a number as a parameter and check the number is prime or not.
Note: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
| function isPrime(n) { if (n === 1) { return false; } else if (n === 2) { return true; } else { for (var i = 2; i < n; i++) { if (n % i === 0) { return false; } } return true; } } console.log(isPrime(23)); |
JavaScript Question № 42 Practical for Senior
Write a JavaScript program to find the greatest common divisor of two positive numbers.
Sample Input: 32, 24
Sample Output: 8
| function gcd(a, b) { return b ? gcd(b, a % b) : a; } console.log(gcd(32, 24)); |
JavaScript Question № 43 Theoretical for Middle
What is a hasOwnProperty ?
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). Example:
| let person = { age: 30, name: 'John' }; console.log(person.hasOwnProperty("age")); // true console.log(person.hasOwnProperty("lastName")); // false, there is no such property console.log(person.hasOwnProperty("toString")); // false, it is inherited property |
JavaScript Question № 44 Theoretical for Senior
Symbol is a primitive type for unique identifiers (as an alternative for string as object property key)
| // can be created using syntax let secretKey = Symbol(“secretSymbol”); // “secretSymbol” is a description |
We can use Symbols as “Hidden” object properties. A symbolic property does not appear in for..in and won’t be accessed directly by another script.
| let importantObject = { name: ‘public name’, } importantObject[secretKey] = ‘some hidden data’; |
Also, we can use many system JavaScript symbols which are accessible as Symbol.*
JavaScript Question № 45 Theoretical for Senior
What are accessor descriptors?
Descriptors for accessor properties are different – as compared with data properties.
For accessor properties, there is no value and writable, but instead, there are get and set functions.
So an accessor descriptor may have:
get – a function without arguments, that works when a property is read,
set – a function with one argument, that is called when the property is set,
enumerable – same as for data properties,
configurable – same as for data properties.
JavaScript Question № 46 Practical for Middle
Correct the code without changing the object sample.
Sample
| let user = { name: "John", logName() { console.log(`My name is ${this.name}!`); } }; setTimeout(user.logName, 1000); |
| // using wrapper setTimeout(function() { user.logName(); // My name is John! }, 1000); // using bind let logName = user.logName.bind(user); setTimeout(logName, 1000); |
JavaScript Question № 47 Theoretical for Senior
What is the difference between Boolean(“true”) and new Boolean(“true”) ?
Boolean(expression) converts the expression into a boolean primitive value
new Boolean(expression) creates a wrapper object around the converted boolean value
| new Boolean("true") === true; // false, it’s an object Boolean("true") === true; // true, it’s a boolean |
JavaScript Question № 48 Practical for Junior
Write a JavaScript program to create a Clock
Sample Output (will come every second):
“09:57:12”
“09:57:13”
“09:57:14”
| function pad(symb) { return String(symb).length == 1 ? '0' + symb : symb; } function clock() { var time = new Date(), hours = time.getHours(), minutes = time.getMinutes(), seconds = time.getSeconds(); return pad(hours) + ':' + pad(minutes) + ':' + pad(seconds); } setInterval(function() { console.log(clock()); }, 1000); |
JavaScript Question № 49 Theoretical for Senior
Categorize JavaScript test tools by type.
Test tools can be divided into the following functionalities. Some provide us with only one functionality, and some provide us with a combination.
To achieve the most flexible set functionality, it’s common to use a combination of several tools.
- Test launchers launch your tests in the browser or Node.js with user config using the CLI or UI. This can also be achieved by opening the browser manually. (Karma, Jasmine, Jest, TestCafe, Cypress)
- Testing structure providers help you arrange your test files. (Mocha, Jasmine, Jest, Cucumber, TestCafe, Cypress)
- Assertion functions check if the results a test returns are as expected. (Chai, Jasmine, Jest, Unexpected, TestCafe, Cypress)
- Generate and display test progress and results. (Mocha, Jasmine, Jest, Karma, TestCafe, Cypress)
- Mocks, spies, and stubs to isolate certain parts of tests and catch their side effects. (Sinon, Jasmine, enzyme, Jest, testdouble)
- Generate and compare snapshots of component and data structures to make sure changes from previous runs are intended. (Jest, Ava)
- Generate code coverage reports to know how much of the code is covered by your tests. (Istanbul, Jest, Blanket)
- Browser Controllers simulate user actions for Functional Tests. (Nightwatch, Nightmare, Phantom, Puppeteer, TestCafe, Cypress)
- Visual Regression Tools are used to compare your site to its previous versions visually by using image comparison techniques.
- (Applitools, Percy, Wraith, WebdriverCSS)
JavaScript Question № 50 Practical for Middle
How to remove elements from an array by criteria? Complete the function.
// using loop and splice
// create an example
Sample
| function removeElements(arr, criteriaFunc) { var i; for (i = 0; i < arr.length; i++) { if (criteriaFunc(arr[i])) { // place for code } } return arr; } console.log(removeElements([1, 2, 5, 4, 6, 7, 3, 1, 5], function(number) { return number < 5; })); |
| function removeElements(arr, criteriaFunc) { var i; for (i = 0; i < arr.length; i++) { if (criteriaFunc(arr[i])) { arr.splice(i, 1); i--; } } return arr; } console.log(removeElements([1, 2, 5, 4, 6, 7, 3, 1, 5], function(number) { return number < 5; })); |
JavaScript Question № 51 Practical for Middle
Write a JavaScript program to find the most frequent item of an array.
Sample Input: [‘d’, ‘3’, ‘a’, ‘d’, ‘d’, ‘c’, ‘c’, ‘3’, ‘1’, ‘a’, ‘d’]
Sample Output : “d: 4”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | function mostFrequent(arr) { var obj = {}, symb = '', max = 0; for (var i = 0; i < arr.length; i++) { if (typeof obj[arr[i]] === 'undefined') { obj[arr[i]] = 1; } else { obj[arr[i]] += 1; } } Object.keys(obj).forEach(function(key) { if (obj[key] > max) { symb = key; max = obj[key]; } }); return symb + ': ' + max; } console.log(mostFrequent(['d', 3, 'a', 'd', 'd', 'c', 'c', 3, 1, 'a', 'd'])); |
JavaScript Question № 52 Practical for Middle
Write a JavaScript program to remove duplicate items from the char array.
Sample Input: [‘d’, ‘3’, ‘a’, ‘d’, ‘d’, ‘c’, ‘c’, ‘3’, ‘1’, ‘a’, ‘d’]
Sample Output : [“1”, “3”, “d”, “a”, “c”]
| function removeDuplicates(num) { var x, len = num.length, out = [], obj = {}; for (x = 0; x < len; x++) { obj[num[x]] = 0; } for (x in obj) { out.push(x); } return out; } console.log(removeDuplicates(['d', '3', 'a', 'd', 'd', 'c', 'c', '3', '1', 'a', 'd'])); |
JavaScript Question № 53 Practical for Senior
Write a JavaScript program to get the first n Fibonacci numbers.
Note : The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . . . Each subsequent number is the sum of the previous two.
Sample Input: 7
Sample Output: [0, 1, 1, 2, 3, 5, 8]
| var fibonacci = function(n) { if (n === 1) { return [0]; } else if (n === 2) { return [0, 1]; } else { var s = fibonacci(n - 1); s.push(s[s.length - 1] + s[s.length - 2]); return s; } }; console.log(fibonacci(7)); |
JavaScript Question № 54 Theoretical for Middle
Every JavaScript object has an internal property called [[Prototype]] . If you look up a property via obj.propName or obj[‘propName’] and the object does not have such a property – which can be checked via obj.hasOwnProperty(‘propName’) – the runtime looks up the property in the object referenced by [[Prototype]] instead. If the prototype-object also doesn’t have such a property, its prototype is checked in turn, thus walking the original object’s prototype-chain until a match is found or its end is reached.
Some JavaScript implementations allow direct access to the [[Prototype]] property, eg via a non-standard property named __proto__. In general, it’s only possible to set an object’s prototype during object creation: If you create a new object via new Func() , the object’s [[Prototype]] property will be set to the object referenced by Func.prototype.
JavaScript Question № 55 Theoretical for Junior
In JavaScript there are two types of scope:
JavaScript has function scope: Each function creates a new scope.
Scope determines the accessibility (visibility) of these variables.
Variables defined inside a function are not accessible (visible) from outside the function.
JavaScript Question № 56 Theoretical for Middle
Explain static properties and methods.
We can assign a method to the class function, not to its “prototype.” Such methods are called static.
Usually, static methods are used to implement functions that belong to the class, but not to any particular object of it.
JavaScript Question № 57 Practical for Middle
How to find the sum of the elements of an array if the nesting of the array is unknown?
Sample
| arraySum([[1, 2, [3, 4]], [9], [10, 12]]) |
| // using recursion function arraySum(arr) { let sum = 0; arr.map((item) => { if (Array.isArray(item)) { sum += arraySum(item); } else { sum += item; } }); return sum; } console.log(arraySum([[1, 2, [3, 4]], [9], [10, 12]])); |
JavaScript Question № 58 Theoretical for Middle
How to redirect the browser to another page?
For simulation the clicking on a link we can use
For simulation the HTTP redirect:
like so:
| window.location.replace("https://soshace.com/en/"); window.location.href = "https://soshace.com/en/"; |
JavaScript Question № 59 Theoretical for Senior
What are bubbling, capturing, and event delegation in the browser?
The bubbling principle is simple.
When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.
There’s another phase of event processing called “capturing”. It is rarely used in real code, but sometimes can be useful.
The standard DOM Events describes 3 phases of event propagation:
Capturing phase – the event goes down to the element.
Target phase – the event reached the target element.
Bubbling phase – the event bubbles up from the element.
Capturing and bubbling allow us to implement one of the most powerful event handling patterns called event delegation.
The idea is that if we have a lot of elements handled in a similar way, then instead of assigning a handler to each of them – we put a single handler on their common ancestor.
JavaScript Question № 60 Practical for Middle
Write a JavaScript function to create random hex color
Sample Output: “#31c05f”
| function pad(symb) { return String(symb).length == 1 ? '0' + symb : symb; } function randHex() { return pad(Math.floor(Math.random() * 256).toString(16)); } function randHexColor() { return '#' + randHex() + randHex() + randHex(); } console.log(randHexColor()); |
JavaScript Question № 61 Theoretical for Middle
What is the difference between import and require?
ES6 Modules
ECMAScript (ES6) modules have been supported in Node.js since v8.5, with the –experimental-modules flag. All files involved must have the .mjs extension.
| // module.mjs export function hello() { return "Hello"; } // main.mjs import { hello } from 'module'; // or './module' let val = hello(); // val is "Hello"; |
Node.js require
The old style of importing modules, still widely used in Node.js, is the module.exports/requiresystem.
| // mymodule.js module.exports = { hello: function() { return "Hello"; } } // server.js const myModule = require('./mymodule'); let val = myModule.hello(); // val is "Hello" |
JavaScript Question № 62 Practical for Senior
Write a code to drag and drop an absolute positioned element.
The basic Drag and Drop algorithm:
Catch mousedown on a draggable element.
Prepare the element for moving (create a copy)
Changing left/top on mousemove move.
On mouseup – finished Drag and Drop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | //Sample <div id="square"></div> <style> #square { background-color: red; width: 20px; height: 20px; position: absolute; } </style> <script> var el = document.getElementById('square'); el.onmousedown = function(event) { el.style.position = 'absolute'; document.body.append(el); moveAt(event.pageX, event.pageY); function moveAt(pageX, pageY) { el.style.left = pageX - el.offsetWidth / 2 + 'px'; el.style.top = pageY - el.offsetHeight / 2 + 'px'; } function onMouseMove(event) { moveAt(event.pageX, event.pageY); } document.addEventListener('mousemove', onMouseMove); el.onmouseup = function() { document.removeEventListener('mousemove', onMouseMove); el.onmouseup = null; }; }; <script> |
JavaScript Question № 63 Theoretical for Middle
What are the benefits of debugging the script in the browser?
- Watch – shows current values for any expressions.
You can click the plus + and input an expression. The debugger will show its value at any moment, automatically recalculating it in the process of execution. - Call Stack – shows the nested calls chain.
At the current moment the debugger is inside hello() call , called by a script in index.html (no function there, so it’s called “anonymous”).
If you click on a stack item, the debugger jumps to the corresponding code, and all its variables can be examined as well. - Scope – current variables.
Local shows local function variables. You can also see their values highlighted right over the source.
Global has global variables (out of any functions).
There’s also this keyword there that we didn’t study yet, but we’ll do that soon.
JavaScript Question № 64 Practical for Senior
How to set an environment variable in the npm script?
package.json sample fragment for Linux and MacOS
| //... "scripts": { "start": "node app.js", "dev": "NODE_ENV=dev node app.js" }, //… |
For compatibility with windows, the cross-env package can be installed. In this case, the syntax will change:
| “cross-env NODE_ENV=dev node app.js” |
The value will be available inside the process object in the application:
JavaScript Question № 65 Theoretical for Senior
Explain the settings of the following eslintrc.json sample
eslintrc.json
| { "parserOptions": { "ecmaVersion": 6, "sourceType": "module", "ecmaFeatures": { "jsx": true } }, "rules": { "semi": "error" } } |
For ES6 syntax, use { “parserOptions”: { “ecmaVersion”: 6 } } ; for new ES6 global variables, use { “env”: { “es6”: true } } . { “env”: { “es6”: true } } enables ES6 syntax automatically, but { “parserOptions”: { “ecmaVersion”: 6 } } does not enable ES6 globals automatically. Parser options are set in your .eslintrc.* file by using the parserOptions property. The available options are:
ecmaVersion – set to 3, 5 (default), 6, 7, 8, 9, or 10 to specify the version of ECMAScript syntax you want to use. You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), or 2019 (same as 10) to use the year-based naming.
sourceType – set to “script” (default) or “module” if your code is in ECMAScript modules.
ecmaFeatures – an object indicating which additional language features you’d like to use:
globalReturn – allow return statements in the global scope
impliedStrict – enable global strict mode (if ecmaVersion is 5 or greater)
jsx – enable JSX
JavaScript Question № 66 Theoretical for Senior
For what purposes can the global object console be used, besides logging?
There are many more features for debugging and testing:
- assert() Writes an error message to the console if the assertion is false
- clear() Clears the console
- count() Logs the number of times that this particular call to count() has been called
- error() Outputs an error message to the console
- group() Creates a new inline group in the console. This indents following console messages by an additional level, until console.groupEnd() is called
- groupCollapsed() Creates a new inline group in the console. However, the new group is created collapsed. The user will need to use the disclosure button to expand it
- groupEnd() Exits the current inline group in the console
- info() Outputs an informational message to the console
- log() Outputs a message to the console
- table() Displays tabular data as a table
- time() Starts a timer (can track how long an operation takes)
- timeEnd() Stops a timer that was previously started by console.time()
- trace() Outputs a stack trace to the console
- warn() Outputs a warning message to the console
JavaScript Question № 67 Theoretical for Middle
What useful plugins / extensions / features can be added in IDE?
- Syntax highlighting
- Linting
- Debugging
- Local server and hot reload
- Autocompletion
- Shortcuts
- Integration of Git, building tools, etc.
JavaScript Question № 68 Theoretical for Middle
What is a destructuring assignment? Give an example.
Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes they are more convenient. Destructuring also works great with complex functions that have a lot of parameters, default values, and soon we’ll see how these are handled too.
| let arr = ["John", "Doe"] let [firstName, surname] = arr; alert(firstName); // John alert(surname); // Doe |
JavaScript Question № 69 Theoretical for Senior
What is yield, give an example?
The yield keyword is used to pause and resume a generator function (or legacy generator function).
| function * generatorForLoop(num) { for (let i = 0; i < num; i += 1) { yield console.log(i); } } const genForLoop = generatorForLoop(5); genForLoop.next(); // first console.log - 0 genForLoop.next(); // 1 genForLoop.next(); // 2 |
JavaScript Question № 70 Practical for Senior
Rewrite the example using promise
| const printSec = (number, callback) => { setTimeout(() => { console.log(`${number} sec`) callback() }, 1000) } printSec(1, () => { printSec(2, () => { printSec(3, () => {}) }) }) |
Using Promise
| const printSec = (number) => { return new Promise((resolve, reject) => { setTimeout(() => { console.log(`${number} sec`) resolve() }, 1000) }) } printSec(1) .then(() => printSec(2)) .then(() => printSec(3)) |
And using await
| async function printAll(){ await printSec(1) await printSec(2) await printSec(3) } printAll() |
JavaScript Question № 71 Theoretical for Senior
List examples in which ECMAScript languages are used other than the browser and the web backend.
Adobe plugins (Photoshop, After Effects, etc.)
Browser extensions
IDE Plugins
Microcontrollers (Arduino)
JavaScript Question № 72 Theoretical for Middle
What is the difference between REST API and GraphQL?
Representational State Transfer is a software architectural style that defines a set of constraints to be used for creating Web services. Web services that conform to the REST architectural style, called RESTful Web services, provide interoperability between computer systems on the Internet.
GraphQL is an open-source data query and manipulation language for APIs, and a runtime for fulfilling queries with existing data.
JavaScript Question № 73 Theoretical for Middle
Progressive Web Apps are websites that look and feel like an app, and are:
Reliable – Load instantly, even in uncertain network conditions.
Fast – Respond quickly to user interactions with silky smooth animations and no janky scrolling.
Engaging – Feel like a natural app on the device, with immersive user experience.
This new level of quality allows Progressive Web Apps to earn a place on the user’s home screen.
More details: https://developers.google.com/web/progressive-web-apps/
JavaScript Question № 74 Theoretical for Middle
Server-Side Rendering, also called SSR, is the ability of a JavaScript application to render on the server rather than in the browser.
It allows your site to have a faster first page load time, which is the key to good user experience.
It is essential for SEO: search engines cannot (yet?) efficiently and correctly index applications that exclusively render client-side. Despite the latest improvements to indexing in Google, there are other search engines too, and Google is not perfect at it in any case. Also, Google favors sites with fast load times, and having to load client-side is not good for speed.
It’s great when people share a page of your site on social media, as they can easily gather the metadata needed to nicely share the link (images, title, description).
JavaScript Question № 75 Theoretical for Middle
What is Static Site Generators?
Static site generators focus on one main task: generate a complete static HTML-based site. This result does not rely on databases or other external data sources and therewith avoid any server-side processing when accessing the website.
In comparison to dynamic websites, static sites have many advantages and therefore are becoming more and more popular. Static sites can be served quickly, they offer a great extent of simplicity and come with security benefits out of the box. Furthermore, it’s easy to deploy and host static sites as there are no special requirements that need to be covered by your hosting provider.
JavaScript Question № 76 Theoretical for Senior
List types of storage in the browser.
They are all browser-side storage to provide offline/cache mechanisms to web apps/sites:
local storage: simple key-value storage, the data is always stored as strings. The same data is accessible to all the pages of the domain and remains persistent even after closing the browser.
session storage: to one URL and one browser session (deleted on browser close)
SQL database (WebSQL): storage in a local DB, access by SQL requests.
IndexedDB is a kind of local/sessionStorage, use to store JavaScript objects instead of only strings.
JavaScript Question № 77 Theoretical for Middle
What is a common practice for type checking in JavaScript?
We can use TypeScript or Flow:
TypeScript is a typed superset of JavaScript. So, basically a fully new, compile-to-JS language. Because it’s syntax is ES-Next compliant (when not considering types), it can be easily taken as a tool for providing type-safety to your JavaScript code.
Flow in opposition to TypeScript isn’t a superset or language. It’s a static type checker for JavaScript written in OCaml. Thus, it doesn’t provide any other functionalities than type system. And, because it’s not a language, it can be smoothly integrated with JavaScript with a single comment annotation.
JavaScript Question № 78 Theoretical for Middle
A modern JavaScript utility library delivering modularity, performance & extras.
Lodash makes JavaScript easier by taking the hassle out of working with arrays, numbers, objects, strings, etc.
Lodash’s modular methods are great for:
- Iterating arrays, objects, & strings
- Manipulating & testing values
- Creating composite functions
JavaScript Question № 79 Theoretical for Middle
What is a Hybrid Mobile App?
Hybrid apps mean developers only write code once that runs on multiple platforms. Also, it lets the developer reuse the code for developing web apps without any extra efforts.
Frameworks
- PhoneGap
- Ionic
- Onsen UI
- Framework 7
Explain
- React Native
- Native script
JavaScript Question № 80 Theoretical for Middle
What are the disadvantages of using jQuery with SPA?
SPA frameworks have cross-browser support and ready-made functionality for manipulating DOM elements. Therefore, most of the jQuery functionality is not required. In addition, modern frameworks themselves create DOM elements during operation and also interact with a virtual DOM, which complicates the integration of solutions based on jQuery.
JavaScript Question № 81 Theoretical for Middle
List some popular libraries for data visualization.
d3 – A JavaScript visualization library for HTML and SVG.
three.js – JavaScript 3D library.
Chart.js – Simple HTML5 Charts using the tag.
raphael – JavaScript Vector Library.
morris.js – Pretty time-series line graphs.
And many more.
JavaScript Question № 82 Theoretical for Senior
What are the libraries for state management?
JavaScript Question № 83 Theoretical for Junior
List SPA frameworks and libraries.
SPA – Single Page Application
- Angular
- React
- Vue.js
- Ember.js
- Meteor
- Backbone.js
JavaScript Question № 84 Theoretical for Middle
List the libraries to making requests from the browser and Node.js?
Popular ajax libraries (for browser requests):
- Fetch API
- Axios
- jQuery (ajax)
- Request library
For use in scripts that can be executed on the server and in the browser, there is a universal library isomorphic-fetch. This is the implementation of fetch for both node.js and browser, built on top of fetch polyfill.
JavaScript Question № 85 Theoretical for Middle
JSON Web Token (JWT) is a compact URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is digitally signed using JSON Web Signature (JWS).
JavaScript Question № 86 Theoretical for Senior
How to create push notifications?
JavaScript Question № 87 Theoretical for Senior
WebAssembly (WASM) is a binary instruction format which has been built to compile high-level languages such as C, C++, Java, Python and Rust. It allows deployment on the web and server applications.
Users write the code in multiple languages to run it on the web. WebAssembly allows them to run the code on the web at a native speed.
JavaScript Question № 88 Theoretical for Senior
WebSockets provide a persistent connection between a client and server that both parties can use to start sending data at any time.
The client establishes a WebSocket connection through a process known as the WebSocket handshake. This process starts with the client sending a regular HTTP request to the server. An Upgrade header is included in this request that informs the server that the client wishes to establish a WebSocket connection.
JavaScript Question № 89 Practical for Middle
Create a script to toggle the DOM element’s class “active” by clicking.
<button id=”click-me” class=”btn”>Click Me</button>
| <button id="click-me" class="btn">Click Me</button> <script type="text/javascript"> var clickMeBtn = document.getElementById("click-me"); clickMeBtn.addEventListener('click', function() { clickMeBtn.classList.toggle('active'); }) </script> |
JavaScript Question № 90 Theoretical for Junior
List primitive types in JavaScript
- The number type represents both integer and floating point numbers
- The string type must be surrounded by quotes
- The boolean type has only two values: true and false
5 comments
I like how you divide them into theoretical and practical ones. Even if the theory was learned a while ago, one can still feel confident with practical questions.
Thank you for this
Thanks, cool idea with types of questions, very useful!
JavaScript Question № 57
function arrSum(arr) {
return arr.toString().split(‘,’).map(str => +str).reduce((a, b) => a + b);
}
yeah! this is very useful article not for the interview only but for those who have a lot questions in their mind related to css and jq. Thanks for such wonderful post.