JavaScript Related Questions
JavaScript Related Questions
A callback function is a function that is passed to another function as an argument and is executed after some operation has been
completed.
Below is an example of a simple callback function that logs to the console after some operations have been completed.
function modifyArray(arr, callback) {
// do something to arr here
arr.push(100);
// then execute the callback function that was passed
callback();
}
var arr = [1, 2, 3, 4, 5];
modifyArray(arr, function() {
console.log("array has been modified", arr);
}
);
Given a string, reverse each word in the sentence
For example, Welcome to this Javascript Guide! should be become emocleW ot siht tpircsavaJ !ediuG
arrayList = [];
Above code will set the variable arrayList to a new empty array.
This is recommended if you don't have references to the original array arrayList anywhere else because It will create a new empty
array.
You should be careful with this way of empty the array, because if you have referenced this array from another variable, then the
original reference array will remain unchanged, Only use this way if you have only referenced the array by its original
variable arrayList.
var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var anotherArrayList = arrayList; // Referenced arrayList by another variable
arrayList = []; // Empty the array
console.log(anotherArrayList); // Output ['a', 'b', 'c', 'd', 'e', 'f']
How would you check if a number is an integer?
A very simply way to check if a number is a decimal or integer is to see if there is a remainder left when you divide by 1.
function isInt(num) {
return num % 1 === 0;
}
console.log(isInt(4)); // true
console.log(isInt(12.2)); // false
console.log(isInt(0.3)); // false
Implement enqueue and dequeue using only two stacks
Answer
function duplicate(arr) {
return arr.concat(arr);
}
duplicate([1, 2, 3, 4, 5]); // [1,2,3,4,5,1,2,3,4,5]
Write a "mul" function which will properly when invoked as below syntax
Problem
console.log(mul(2)(3)(4)); // output : 24
console.log(mul(4)(3)(4)); // output : 48
Answer
Answer
function createBase(baseNumber) {
return function(N) {
// we are referencing baseNumber here even though it was declared
// outside of this function. Closures allow us to do this in JavaScript
return baseNumber + N;
}
}
var addSix = createBase(6);
addSix(10);
addSix(21);
FizzBuzz Challenge
Problem
Create a for loop that iterates up to 100 while outputting "fizz" at multiples of 3, "buzz" at multiples of 5 and "fizzbuzz" at
multiples of 3 and 5.
Answer
Check out this version of FizzBuzz:
Answer
var firstWord = "Mary";
var secondWord = "Army";
isAnagram(firstWord, secondWord); // true
function isAnagram(first, second) {
// For case insensitivity, change both words to lowercase.
var a = first.toLowerCase();
var b = second.toLowerCase(); // Sort the strings, and join the resulting array to a string.
Compare the results
a = a.split("").sort().join("");
b = b.split("").sort().join("");
return a === b;
Given two strings, return true if they are anagrams of one another
Problem
For example: Mary is an anagram of Army
Answer
var firstWord = "Mary";
var secondWord = "Army";
isAnagram(firstWord, secondWord); // true
function isAnagram(first, second) {
// For case insensitivity, change both words to lowercase.
var a = first.toLowerCase();
var b = second.toLowerCase(); // Sort the strings, and join the resulting array to a string.
Compare the results
a = a.split("").sort().join("");
b = b.split("").sort().join("");
return a === b;
Provide some examples of non-bulean value coercion to a boolean one
Answer
The question is when a non-boolean value is coerced to a boolean, does it become true or false, respectively?
The specific list of "falsy" values in JavaScript is as follows:
• "" (empty string)
• 0, -0, NaN (invalid number)
• null, undefined
• false
Any value that's not on this "falsy" list is "truthy." Here are some examples of those:
• "hello"
• 42
• true
• [ ], [ 1, "2", 3 ] (arrays)
• { }, { a: 42 } (objects)
• function foo() { .. } (functions)
What will be the output of the following code?
Problem
var y = 1;
if (function f() {}) {
y += typeof f;
}
console.log(y);
Answer
Above code would give output 1undefined.
If condition statement evaluate using eval so eval(function f() {}) which return function f() {} which is true so inside if statement code
execute.
typeof f return undefined because if statement code execute at run time, so statement inside if condition evaluated at run time.
var k = 1;
if (1) {
function foo() {};
k += typeof foo;
}
console.log(k); // output 1function
What will the following code output?
Problem
(function() {
var a = b = 5;
})();
console.log(b);
Answer
The code above will output 5 even though it seems as if the variable was declared within a function and can't be accessed outside of it.
This is because
var a = b = 5;
is interpreted the following way:
var a = b;
b = 5;
But b is not declared anywhere in the function with var so it is set equal to 5 in the global scope.
What are the different data types present in javascript?
To know the type of a JavaScript variable, we can use the typeof operator.
1. Primitive types
String - It represents a series of characters and is written with quotes. A string can be represented using a single or a double quote.
Number - It represents a number and can be written with or without decimals.
BigInt - This data type is used to store numbers which are above the limitation of the Number data type. It can store large integers
and is represented by adding “n” to an integer literal.
Boolean - It represents a logical entity and can have only two values : true or false. Booleans are generally used for conditional
testing.
Undefined - When a variable is declared but not assigned, it has the value of undefined and it’s type is also undefined.
Null - It represents a non-existent or a invalid value.
Symbol - It is a new data type introduced in the ES6 version of javascript. It is used to store an anonymous and unique value.
typeof "John Doe" // Returns "string"
typeof 3.14 // Returns "number"
typeof true // Returns "boolean"
typeof 234567890123456789012345678901234567890n // Returns bigint
typeof undefined // Returns "undefined"
typeof null // Returns "object" (kind of a bug in JavaScript)
typeof Symbol('symbol') // Returns Symbol
2. Non-primitive types
Primitive data types can store only a single value. To store multiple and complex values, non-primitive data types are
used.
Object - Used to store collection of data.
The debugger for the browser must be activated in order to debug the code.
Built-in debuggers may be switched on and off, requiring the user to report faults.
The remaining section of the code should stop execution before moving on to the next line while debugging.
Difference between “ == “ and “ === “ operators.
Both are comparison operators. The difference between both the operators is that “==” is used to compare values whereas, “
=== “ is used to compare both values and types.
Example
var x = 2;
var y = "2";
(x == y) // Returns true since the value of both x and y is the same
(x === y) // Returns false since the typeof x is "number" and typeof y is "string"
Difference between var and let keyword in javascript.
NaN property represents the “Not-a-Number” value. It indicates a value that ias not a legal number.
typeof of NaN will return a Number.
To check if a value is NaN, we use the isNaN() function,
Note- isNaN() function converts the given value to a Number type, and then equates to NaN.
The “this” keyword refers to the object that the function is a property of.
The value of the “this” keyword will always depend on the object that is invoking the function.
Confused? Let’s understand the above statements by examples:
function doSomething() {
console.log(this);
}
doSomething();
What do you think the output of the above code will be?
Note - Observe the line where we are invoking the function.
Check the definition again:
The “this” keyword refers to the object that the function is a property of.
In the above code, the function is a property of which object?
Since the function is invoked in the global context, the function is a property of the global object.
Therefore, the output of the above code will be the global object. Since we ran the above code inside the browser, the global object is the
window object.
Explain call(), apply() and, bind() methods.
1. call():
It’s a predefined method in javascript.
This method invokes a method (function) by specifying the owner object.
Example:
function sayHello(){
return "Hello " + this.name;
}
var obj = {name: "Sandy"};
sayHello.call(obj); // Returns "Hello Sandy"
call() method allows an object to use the method (function) of another object.
apply()
The apply method is similar to the call() method. The only difference is that,
call() method takes arguments separately whereas, apply() method takes arguments as an array.
function saySomething(message){
return this.name + " is " + message;
}
var person4 = {name: "John"};
saySomething.apply(person4, ["awesome"]);
2. bind():
This method returns a new function, where the value of “this” keyword will be bound to the owner object, which is provided as a parameter.
Example with arguments:
var bikeDetails = {
displayDetails: function(registrationNumber,brandName){
return this.name+ " , "+ "bike details: "+ registrationNumber + " , " + brandName;
}
}
var person1 = {name: "Vivek"};
var detailsOfPerson1 = bikeDetails.displayDetails.bind(person1, "TS0122", "Bullet");
// Binds the displayDetails function to the person1 object detailsOfPerson1();
// Returns Vivek, bike details: TS0452, Thunderbird
What are the features of JavaScript?
JavaScript supports Object concept very well. You can create an object using the object literal as follows −
var emp = {
name: "Daniel",
age: 23
};
How can you create an Array in JavaScript?
A named function declares a name as soon as it is defined. It can be defined using function keyword as :
function named(){
// write code here
}
What are the scopes of a variable in JavaScript?
The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.
Global Variables − A global variable has global scope which means it is visible everywhere in your JavaScript code.
Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are
always local to that function.
What is Callback?
Attributes-
provide more details on an element like id, type, value etc.
Property-
Property is the value assigned to the property like type=”text”, value=’Name’ etc.
List out the different ways an HTML element can be accessed in a JavaScript code.
Here are the list of ways an HTML element can be accessed in a Javascript code:
getElementById(‘idname’): Gets an element by its ID name
getElementsByClass(‘classname’): Gets all the elements that have the given classname.
getElementsByTagName(‘tagname’): Gets all the elements that have the given tag name.
querySelector(): This function takes css style selector and returns the first selected element.