Java Script
Java Script
Java Script
34. varx=5,y=1
var obj ={ x:10}
with(obj)
{
alert(y)
}
output:1
35. Among the following given JavaScript snipped codes, which is more efficient:
Code A
for(var number=10;number>=1;number--)
{
document.writeln(number);
}
Code B
var number=10;
while(number>=1)
{
document.writeln(number);
number++;
}
answer: code A
37. Write a JavaScript function that returns a passed string with letters in
alphabetical order
Answer:
Example string : 'webmaster'
Expected Output : 'abeemrstw'
<body onload="alphabet_order()">
<script>
function alphabet_order(str)
{
return str.split('').sort().join('');
}
document.write(alphabet_order("webmaster"));</script>
</body>
</html>
38. Write a JavaScript function that accepts a string as a parameter and counts the
number of vowels within the string.
Answer:
1. function vowel_count(str1)
2. {
3. var vowel_list = 'aeiouAEIOU';
4. var vcount = 0;
5.
6. for(var x = 0; x < str1.length ; x++)
7. {
8. if (vowel_list.indexOf(str1[x]) !== -1)
9. {
10. vcount += 1;
11. }
12.
13. }
14. return vcount;
15.}
16.Document.write(vowel_count("The quick brown fox"));
39) Write a JavaScript function that accepts a string as a parameter and converts
the
first letter of each word of the string in upper case.
Example string : 'the quick brown fox'
Expected Output : 'The Quick Brown Fox '
Answer:
function uppercase(str)
{
var array1 = str.split(' ');
var newarray1 = [];
for(var x = 0; x < array1.length; x++){
newarray1.push(array1[x].charAt(0).toUpperCase()+array1[x].slice(1));
}
return newarray1.join(' ');
}
document.write(uppercase("the quick brown fox"));
JS code:
function multiplyBy()
{
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
document.getElementById("result").innerHTML = num1 * num2;
}
function divideBy() {
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
document.getElementById("result").innerHTML = num1 / num2;
}
43) Write a JavaScript program that accept two integers and display the larger.
Answer:
1. var num1, num2;
2. num1 = window.prompt("Input the First integer", "0");
3. num2 = window.prompt("Input the second integer", "0");
4.
5. if(parseInt(num1, 10) > parseInt(num2, 10))
6. {
7. document.write("The larger of "+ num1+ " and "+ num2+ " is "+ num1+ ".")
;
8. }
9. else
10. if(parseInt(num2, 10) > parseInt(num1, 10))
11. {
12. document.write("The larger of "+ num1+" and "+ num2+ " is "+ num2+ ".");
13. }
14.else
15. {
16. document.write("The values "+ num1+ " and "+num2+ " are equal.");
17. }
44) Write a JavaScript conditional statement to find the sign of product of three
numbers. Display an alert box
with the specified sign.
Answer:
1. var x=3;
2. var y=-7;
3. var z=2;
4. if (x>0 && y>0 && z>0)
5. {
6. alert("The sign is +");
7. }
8. else if (x<0 && y<0 && z>0)
9. {
10. document.write("The sign is +");
11. }
12. else if (x>0 && y<0 && z<0)
13. {
14. document.write("The sign is +");
15. }
16. else if (x<0 && y>0 && z<0)
17. {
18. document.write("The sign is +");
19. }
20. else
21. {
22. document.write("The sign is -");
23. }
47) Write a simple JavaScript program to join all elements of the following array
into
a string.
Answer:
1. myColor = ["Red", "Green", "White", "Black"];
2. document.write(myColor.toString());
3. document.write(myColor.join());
4. document.write(myColor.join('+'));
49) Write a JavaScript for loop that will iterate from 0 to 15. For each iteration,
it will
check if the current number is odd or even, and display a message to the screen.
Answer:
1. for (var x=0; x<=15; x++) {
2. if (x === 0) {
3. Document.write(x + " is even");
4. }
5. else if (x % 2 === 0) {
6. Document.write (x + " is even");
7. }
8. else {
9. Document.write (x + " is odd");
10. }
11.}
50) Write a JavaScript conditional statement to find the largest of five numbers.
Display an alert box to show the result.
Answer:
1. a=-5;
2. b=-2;
3. c=-6;
4. d= 0;
5. f=-1;
6. if (a>b && a>c && a>d && a>f)
7. {
8. document.write(a);
9. }
10.else if (b>a && b>c && b>d && b>f)
11.{
12. document.write(b);
13.}
14.else if (c>a && c>b && c>d && c>f)
15.{
16. document.write(c);
17.}
18.else if (d>a && d>c && d>b && d>f)
19.{
20. document.write(d);
21.}
22.else
23.{
24. document.write(f);
25.}
52) Write a JavaScript function to get difference between two dates in days.
Answer: 1. var date_diff_indays = function(date1, date2) {
2. dt1 = new Date(date1);
3. dt2 = new Date(date2);
4. return Math.floor((Date.UTC(dt2.getFullYear(), dt2.getMonth(), dt2.getDate
()) -
Date.UTC(dt1.getFullYear(), dt1.getMonth(), dt1.getDate()) ) /(1000 * 60
* 60 * 24));
5. }
6. document.write(date_diff_indays('04/02/2014', '11/04/2014'));
7. document.write(date_diff_indays('12/02/2014', '11/04/2014'));
54) Write a JavaScript function to count the number of days passed since beginning
of the year.
Answer:
1. function days_passed(dt) {
2. var current = new Date(dt.getTime());
3. var previous = new Date(dt.getFullYear(), 0, 1);
4.
5. return Math.ceil((current - previous + 1) / 86400000);
6. }
7. document.write(days_passed(new Date(2015, 0, 15)));
8. document.write(days_passed(new Date(2015, 11, 14)));
62) Write a JavaScript function to capitalize the first letter of each word in a
string.
Answer:
1. //capitalize_Words
2. function capitalize_Words(str)
3. {
4. return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCa
se() + txt.substr(1).toLowerCase();});
5. }
6. document.write(capitalize_Words('js string exercises'));
console.log(csv_to_array('a,b\nc,d'));
console.log(csv_to_array('a;b\nc;d', ';'));
console.log(csv_to_array('head1,head2\na,b\nc,d', ',', true));
66) Write a JavaScript program to target a given value in a nested JSON object,
based on the given key.
Answer:
const dig = (obj, target) =>
target in obj
? obj[target]
: Object.values(obj).reduce((acc, val) => {
if (acc !== undefined) return acc;
if (typeof val === 'object') return dig(val, target);
}, undefined);
const data = {
level1: {
level2: {
level3: 'some data'
}
}
};
const dog = {
"status": "success",
"message": "https://images.dog.ceo/breeds/african/n02116738_1105.jpg"
}
console.log(dig(data, 'level3'));
console.log(dig(data, 'level4'));
console.log(dig(dog, 'message'));
67) Write a JavaScript program to converts a specified number to an array of
digits.
Answer:
const digitize = n => [...`${n}`].map(i => parseInt(i));
console.log(digitize(123));
console.log(digitize(1230));
68) Write a JavaScript program to filter out the specified values from a specified
array. Return the original array without the filtered values.
Answer:
const pull = (arr, ...args) => {
let argState = Array.isArray(args[0]) ? args[0] : args;
let pulled = arr.filter((v, i) => !argState.includes(v));
arr.length = 0;
pulled.forEach(v => arr.push(v));
return pulled;
};
let arra1 = ['a', 'b', 'c', 'a', 'b', 'c'];
console.log(pull(arra1, 'a', 'c'));
let arra2 = ['a', 'b', 'c', 'a', 'b', 'c'];
console.log(pull(arra2, 'b'));
69) Write a JavaScript program to combine the numbers of a given array into an
array containing all combinations.
Answer:
const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))),
[[]]);
console.log(powerset([1, 2]));
console.log(powerset([1, 2, 3]));
console.log(powerset([1, 2, 3, 4]));
70) Write a JavaScript program to extract out the values at the specified indexes
from a specified array.
Answer:
const pull_at_Index = (arr, pullArr) => {
let removed = [];
let pulled = arr
.map((v, i) => (pullArr.includes(i) ? removed.push(v) : v))
.filter((v, i) => !pullArr.includes(i));
arr.length = 0;
pulled.forEach(v => arr.push(v));
return removed;
};
let arra1 = ['a', 'b', 'c', 'd', 'e', 'f'];
console.log(pull_at_Index(arra1, [1, 3]));
let arra2 = [1, 2, 3, 4, 5, 6, 7];
console.log(pull_at_Index(arra2, [4]));
console.log(random_hex_color_code())
73) Write a JavaScript program to convert the length of a given string in bytes.
Answer:
const byte_Size = str => new Blob([str]).size;
console.log(byte_Size('123456'));
console.log(byte_Size('Hello World'));
console.log(byte_Size('â'));
74) Write a JavaScript program to replace the names of multiple object keys with
the values provided.
Answer:
const rename_keys = (keysMap, obj) =>
Object.keys(obj).reduce(
(acc, key) => ({
...acc,
...{ [keysMap[key] || key]: obj[key] }
}),
{}
);
const obj = { name: 'Bobo', job: 'Programmer', shoeSize: 100 };
console.log("Original Object");
console.log(obj);
console.log("-------------------------------------");
result = rename_keys({ name: 'firstName', job: 'Actor' }, obj);
console.log("New Object");
console.log(result);
76) Write a JavaScript function that returns true if the provided predicate
function returns true for all elements in a collection, false otherwise.
Answer:
const all = (arr, fn = Boolean) => arr.every(fn);
console.log(all([4, 2, 3], x => x > 1));
console.log(all([4, 2, 3], x => x < 1));
console.log(all([1, 2, 3]));
77) Write a JavaScript program to split values of two given arrays into two groups.
If an element in filter is truthy, the corresponding element in the collection
belongs to the first group; otherwise, it belongs to the second group.
Answer:
const bifurcate = (arr, filter) =>
arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
console.log(bifurcate([1, 2, 3, 4], [true, true, false, true]));
console.log(bifurcate([1, 2, 3, 4], [true, true, true, true]));
console.log(bifurcate([1, 2, 3, 4], [false, false, false, false]));
78) Write a JavaScript program to remove specified elements from the left of a
given array of elements.
Answer:
function remove_from_left(arr, n = 1){
return arr.slice(n);
}
console.log(remove_from_left([1, 2, 3]));
console.log(remove_from_left([1, 2, 3], 1));
console.log(remove_from_left([1, 2, 3], 2));
console.log(remove_from_left([1, 2, 3], 4));
79) Write a JavaScript program to remove specified elements from the right of a
given array of elements.
Answer:
function remove_from_right(arr, n = -1){
return arr.slice(n);
}
console.log(remove_from_right([1, 2, 3]));
console.log(remove_from_right([1, 2, 3], -1));
console.log(remove_from_right([1, 2, 3], -2));
console.log(remove_from_right([1, 2, 3], -4));
80) Write a JavaScript program to extend a 3-digit color code to a 6-digit color
code.
Answer:
const extend_Hex = shortHex =>
'#' +
shortHex
.slice(shortHex.startsWith('#') ? 1 : 0)
.split('')
.map(x => x + x)
.join('');
console.log(extend_Hex('#03f'));
console.log(extend_Hex('05a'));
81) Write a JavaScript program to get every nth element in a given array.
Answer:
const every_nth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
console.log(every_nth([1, 2, 3, 4, 5, 6], 1));
console.log(every_nth([1, 2, 3, 4, 5, 6], 2));
console.log(every_nth([1, 2, 3, 4, 5, 6], 3));
console.log(every_nth([1, 2, 3, 4, 5, 6], 4));
82) Write a JavaScript program to filter out the non-unique values in an array.
Answer:
const filter_Non_Unique = arr => arr.filter(i => arr.indexOf(i) ===
arr.lastIndexOf(i));
console.log(filter_Non_Unique([1, 2, 2, 3, 4, 4, 5]));
console.log(filter_Non_Unique([1, 2, 3, 4]));