0% found this document useful (0 votes)
9 views

JavaScript Related Questions

Uploaded by

muralidharan.r
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

JavaScript Related Questions

Uploaded by

muralidharan.r
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Explain what a callback function is and provide a simple example

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

var string = "Welcome to this Javascript Guide!";


// Output becomes !ediuG tpircsavaJ siht ot emocleW

var reverseEntireSentence = reverseBySeparator(string, "");


// Output becomes emocleW ot siht tpircsavaJ !ediuG

var reverseEachWord = reverseBySeparator(reverseEntireSentence, " ");

function reverseBySeparator(string, separator) {


return string.split(separator).reverse().join(separator);
}
How to empty an array in JavaScript?
Problem
var arrayList = ['a', 'b', 'c', 'd', 'e', 'f’];
How could we empty the array above?

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

Enqueue means to add an element, dequeue to remove an element.

var inputStack = []; // First stack


var outputStack = []; // Second stack
// For enqueue, just push the item into the first stack
function enqueue(stackInput, item) {
return stackInput.push(item);
}

function dequeue(stackInput, stackOutput) {


// Reverse the stack such that the first element of the output stack is the
// last element of the input stack. After that, pop the top of the output to
// get the first element that was ever pushed into the input stack
if (stackOutput.length <= 0) {
while(stackInput.length > 0) {
var elementToOutput = stackInput.pop();
stackOutput.push(elementToOutput); }
}
return stackOutput.pop();
}
Make this work
Problem
duplicate([1, 2, 3, 4, 5]); // [1,2,3,4,5,1,2,3,4,5]

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

function mul (x) {


return function (y) { // anonymous function
return function (z) { // anonymous function
return x * y * z;
};
};
}
Write a function that would allow you to do this?
Problem
var addSix = createBase(6);
addSix(10); // returns 16
addSix(21); // returns 27

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:

for (let i = 1; i <= 100; i++) {


let f = i % 3 == 0,
b = i % 5 == 0;
console.log(f ? (b ? 'FizzBuzz' : 'Fizz') : b ? 'Buzz' : i);
}
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;
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.

// Collection of data in key-value pairs


var obj1 = { x: 43,
y: "Hello world!",
z: function(){
return this.x;
} }
// Collection of data as an ordered list
var array1 = [5, "Hello", true, 4.1];
Why do we use the word “debugger” in javascript?

 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.

Some differences are


 From the very beginning, the 'var' keyword was used in JavaScript programming whereas the keyword 'let' was just
added in 2015.
 The keyword 'Var' has a function scope. Anywhere in the function, the variable specified using var is accessible but in
‘let’ the scope of a variable declared with the 'let' keyword is limited to the block in which it is declared. Let's start with a
Block Scope.
 In ECMAScript 2015, let and const are hoisted but not initialized. Referencing the variable in the block before the
variable declaration results in a ReferenceError because the variable is in a "temporal dead zone" from the start of the
block until the declaration is processed.
What is NaN property 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.

isNaN("Hello") // Returns true


isNaN(345) // Returns false
isNaN('1') // Returns false, since '1' is converted to Number type which results in 0 ( a number)
isNaN(true) // Returns false, since true converted to Number type results in 1 ( a number)
isNaN(false) // Returns false isNaN(undefined) // Returns true
Explain “this” keyword.

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?

Following are the features of JavaScript:


 It is a lightweight, interpreted programming language.
 It is designed for creating network-centric applications.
 It is complementary to and integrated with Java.
 It is an open and cross-platform scripting language.
How can you create an object in 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?

You can define arrays using the array literal as follows-


var x = [];
var y = [1, 2, 3, 4, 5];
What is a name function in JavaScript & how to define it?

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?

 A callback is a plain JavaScript function passed to some method as an argument or option.


 It is a function that is to be executed after another function has finished executing, hence the name ‘call back‘.
 In JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by
other functions.
What is the difference between Attributes and Property?

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.

You might also like