Unveiling the Top 10 Most Commonly Asked JavaScript Questions
Pic
Theory:
JavaScript is a versatile and powerful programming language that plays a crucial role in web development. As developers dive into the world of JavaScript, they often encounter common questions that shape their understanding and proficiency in the language. In this blog post, we’ll explore the 10 most frequently asked JavaScript questions and unravel the mysteries behind them.
What is JavaScript, and how does it differ from Java?
- JavaScript and Java share a similar name, but they are distinct languages. JavaScript is a lightweight, interpreted programming language primarily used for web development. Java, on the other hand, is a general-purpose, object-oriented language. They differ in syntax, use cases, and where they are executed.
What is the DOM (Document Object Model)?
- The DOM is a programming interface for web documents. It represents the structure of a document as a tree of objects, where each object corresponds to a part of the document. JavaScript can manipulate the DOM, allowing developers to dynamically update and change the content, structure, and style of a web page.
What is the difference between let
, const
, and var
?
- These are JavaScript variable declarations.
let
andconst
were introduced in ECMAScript 6 (ES6) to address some issues withvar
.let
allows for variable reassignment, whileconst
is used for constant values that cannot be reassigned.var
is function-scoped, whilelet
andconst
are block-scoped.
Explain the concept of closures.
- Closures occur when a function is defined within another function and has access to the outer function’s variables. This allows the inner function to “remember” the environment in which it was created, even after the outer function has finished executing. Closures are a powerful feature in JavaScript and are commonly used in various design patterns.
What is the event loop in JavaScript?
- The event loop is a crucial concept for understanding how asynchronous operations work in JavaScript. It manages the execution of multiple tasks by placing them in a queue and processing them in a loop. This ensures that time-consuming operations, like I/O or AJAX requests, do not block the execution of the rest of the program.
Explain the differences between ==
and ===
.
==
is the equality operator, which performs type coercion, meaning it converts the operands to the same type before making the comparison.===
is the strict equality operator, which checks both value and type without coercion. It is generally recommended to use===
to avoid unexpected type conversions.
What is the significance of the this
keyword in JavaScript?
- The
this
keyword refers to the current execution context in JavaScript. Its value depends on how a function is invoked. In a method,this
refers to the object the method was called on. In a regular function,this
may refer to the global object or be undefined in strict mode.
What is asynchronous programming, and how does it work in JavaScript?
- Asynchronous programming allows for the execution of multiple tasks without waiting for each to complete before moving on. JavaScript uses callbacks, promises, and async/await to handle asynchronous operations. Callbacks are functions passed as arguments to other functions and executed later. Promises and async/await provide more structured and readable ways to work with asynchronous code.
Explain the concept of hoisting.
- Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase. This means that you can use a variable or function before it is declared. However, only the declarations are hoisted, not the initializations.
What is the purpose of the bind
, call
, and apply
methods?
- These methods are used to manipulate the value of
this
in JavaScript functions.bind
creates a new function with a specifiedthis
value, without invoking the function.call
andapply
invoke the function with a specifiedthis
value, with the main difference being how arguments are passed –call
takes them individually, whileapply
takes them as an array.
Numericals:
In this kata you will create a function that takes a list of non-negative integers and strings and returns a new list with the strings filtered out.
Example
filter_list([1,2,'a','b']) == [1,2]
filter_list([1,'a','b',0,15]) == [1,0,15]
filter_list([1,2,'aasf','1','123',123]) == [1,2,123]
Solution:
function filter_list(l) {
// Return a new array with the strings filtered out
// Use the filter method to create a new array with non-negative integers only
const filteredList = l.filter(item => typeof item === 'number' && item >= 0);
return filteredList;
}
ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits.
If the function is passed a valid PIN string, return true
, else return false
.
Examples (Input → Output)
"1234" --> true
"12345" --> false
"a234" --> false
Solution:
function validatePIN (pin) {
//return true or false
return /^\d+$/.test(pin) && (pin.length === 4 || pin.length === 6);
}
Capitalize the first letter of each word in a string
To achieve this, we split the words from the string and store them in an array, and then use the above concept on each element of the array and join all the array elements together to get the string back. Let us take a look at this using an example
const str = 'i have learned something new today';
//split the above string into an array of strings
//whenever a blank space is encountered
const arr = str.split(" ");
//loop through each element of the array and capitalize the first letter.
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
}
//Join all the elements of the array back into a string
//using a blankspace as a separator
const str2 = arr.join(" ");
console.log(str2);
//Outptut: I Have Learned Something New Today
Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown below. Index 0
will be considered even.
For example, capitalize("abcdef") = ['AbCdEf', 'aBcDeF']
. See test cases for more examples.
The input will be a lowercase string with no spaces.
Solution:
function capitalize(s){
let arr=s.split("");//"roshan"=["r","o","s","h","a","n"]
let str1="";
let str2="";
// i want RoShAn
for(let i=0;i<arr.length;i++){
if(i%2===0){
str1+=arr[i].toUpperCase();
}
else{str1+=arr[i];}
}
for(let i=0;i<arr.length;i++){
if(i%2!==0){
str2+=arr[i].toUpperCase();
}
else{ str2+=arr[i];}
}
return [str1,str2];
}
Given: an array containing hashes of names
Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.
Example:
list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ])
// returns 'Bart, Lisa & Maggie'
list([ {name: 'Bart'}, {name: 'Lisa'} ])
// returns 'Bart & Lisa'
list([ {name: 'Bart'} ])
// returns 'Bart'
list([])
// returns ''
Solution:
function list(names){
//your code here
if (names.length === 0) {
return '';
} else if (names.length === 1) {
return names[0].name;
} else {
const lastPerson = names.pop();//removing and stroing the last item
const namesArray = names.map(person => person.name);//creating an array which contains all items
return namesArray.join(', ') + ' & ' + lastPerson.name;
}
}
Write a function, persistence
, that takes in a positive parameter num
and returns its multiplicative persistence, which is the number of times you must multiply the digits in num
until you reach a single digit.
For example (Input → Output):
39 --> 3 (because 3*9 = 27, 2*7 = 14, 1*4 = 4 and 4 has only one digit)
999 --> 4 (because 9*9*9 = 729, 7*2*9 = 126, 1*2*6 = 12, and finally 1*2 = 2)
4 --> 0 (because 4 is already a one-digit number)
function persistence(num) {
// Initialize a count variable to keep track of the number of iterations
let count = 0;
// Continue the loop until the number is a single-digit
while (num >= 10) {
// Convert the number to a string, split it into an array of digits, and convert each digit back to a number
let digits = num.toString().split('').map(Number);
// Calculate the product of all digits using the reduce function
num = digits.reduce((product, digit) => product * digit, 1);
// Increment the count variable to track the number of iterations
count++;
}
// Return the final count, which represents the persistence of the original number
return count;
}
You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones — everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. [’n’, ‘s’, ‘w’, ‘e’]). You always walk only a single block for each letter (direction) and you know it takes you one minute to traverse one city block, so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don’t want to be early or late!) and will, of course, return you to your starting point. Return false otherwise.
Note: you will always receive a valid array containing a random assortment of direction letters (’n’, ‘s’, ‘e’, or ‘w’ only). It will never give you an empty array (that’s not a walk, that’s standing still!).
function isValidWalk(walk) {
//insert brilliant code here
if(walk.length!==10){
return false;
}
let countn=0;
let countw=0;
let counte=0;
let counts=0;
for(let i=0;i<walk.length;i++){
if(walk[i]==='s'){
counts++;
}else if(walk[i]==='n'){
countn++
}
else if(walk[i]==='e'){
counte++;
}else {
countw++;
}
}
return ((countn===counts) && (counte===countw));
}
Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.
It should remove all values from list a
, which are present in list b
keeping their order.
arrayDiff([1,2],[1]) == [2]
If a value is present in b
, all of its occurrences must be removed from the other:
arrayDiff([1,2,2,2,3],[2]) == [1,3]
function arrayDiff(a, b) {
// Use filter to keep only the elements in 'a' that are not present in 'b'
return a.filter(element => !b.includes(element));
}
Given a number , Return The Maximum number could be formed from the digits of the number given .
Notes
Only Natural numbers passed to the function , numbers Contain digits [0:9] inclusive
Digit Duplications could occur , So also consider it when forming the Largest
Input >> Output Examples:
maxNumber (213) ==> return (321)
Explanation:
As 321
is The Maximum number could be formed from the digits of the number 213 .
maxNumber (7389) ==> return (9873)
Explanation:
As 9873
is The Maximum number could be formed from the digits of the number 7389 .
maxNumber (63729) ==> return (97632)
Explanation:
As 97632
is The Maximum number could be formed from the digits of the number 63729 .
maxNumber (566797) ==> return (977665)
Explanation:
As 977665
is The Maximum number could be formed from the digits of the number 566797 .
Note : Digit duplications are considered when forming the largest .
maxNumber (17693284) ==> return (98764321)
Explanation:
As 98764321
is The Maximum number could be formed from the digits of the number 17693284 .
function maxNumber(n){
//your code here
const digit=Array.from(String(n),Number);
const sortedArray=digit.sort((a,b)=>b-a);
return parseInt(sortedArray.join(''),10);
}
Same in Java:(Sorry for bringing Java but could not resist it.)
import java.util.HashMap;
import java.util.Map;
public class MaxNumber {
public static int maxNumber(int n) {
// Count the frequency of each digit using a map
Map<Character, Integer> digitCount = new HashMap<>();
char[] digits = String.valueOf(n).toCharArray();
for (char digit : digits) {
digitCount.put(digit, digitCount.getOrDefault(digit, 0) + 1);
}
// Construct the result by iterating over digits in descending order
StringBuilder resultBuilder = new StringBuilder();
for (char digit = '9'; digit >= '0'; digit--) {
if (digitCount.containsKey(digit)) {
int count = digitCount.get(digit);
resultBuilder.append(String.valueOf(digit).repeat(count));
}
}
return Integer.parseInt(resultBuilder.toString());
}
public static void main(String[] args) {
System.out.println(maxNumber(213)); // Output: 321
System.out.println(maxNumber(7389)); // Output: 9873
System.out.println(maxNumber(63729)); // Output: 97632
System.out.println(maxNumber(566797)); // Output: 977665
System.out.println(maxNumber(17693284)); // Output: 98764321
}
}
Your task is simply to count the total number of lowercase letters in a string.
Examples
"abc" ===> 3
"abcABC123" ===> 3"abcABC123!@€£#$%^&*()_-+=}{[]|\':;?/>.<,~" ===> 3"" ===> 0;"ABC123!@€£#$%^&*()_-+=}{[]|\':;?/>.<,~" ===> 0"abcdefghijklmnopqrstuvwxyz" ===> 26
function lowercaseCount(str){
//How many?
let count=0;
for(let i=0;i<str.length;i++){
if(/[a-z]/.test(str[i])){
count++;
}
}
return count++;
}
Write a simple function that takes a Date
as a parameter and returns a Boolean
representing whether the date is today or not.
Make sure that your function does not return a false positive by only checking the day.
function isToday(date) {
//create date object
let today = new Date();//current date and time stored in d variable
let inputDate = new Date(date); //date input
//extract date parts YYYY-MM-
// create new date object based on input value from date parameter
let todayDate = new Date (today.getFullYear(),today.getMonth(), today.getDate());
let inputDateOnly = new Date (inputDate.getFullYear(),inputDate.getMonth(), inputDate.getDate());
//
if(todayDate.getTime() === inputDateOnly.getTime()){
return true;
}else{
return false;
}
}