Java Script

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 18

JAVASCRIPT

1. What shows in the console?


Var nr=”99.9”;
Console.log(tyoeof nr);
Answer: String
2. What shows in the console?
Var id;
Console.log(id);
Answer: undefined
3. In JS some variables can be used for different types.
Answer: True
4. JS allows to use different data types within an array.
Answer: True
5. What shows in the console?
Console.log(typeof 4.7);
Answer: Nunber
6. What shows in the console?
Console.log(typeof false);
Answer: Boolean
7. What keyword would you use to declare a numeric value in JS?
Answer: var
8. List the data types recognized by JS
Answer: Boolean, null, string, number
9. What are the symbols that could be used to check if a variable is equal to a
specific value?
Answer: ===, and ==
10. When is the && operator true?
Answer: both sides are true
11. What shows in the console?
Var level=6;
Var nextlevel = ++level;
Console.log(nextlevel)
Answer: 7
12. What shows in the console
Var nr=6;
nr *=2;
Console.log(nr)
Answer: 12
13. Which statement checks if a variable is different from a specific value?
Answer: !=
14. What shows in the console?
console.log(!0)
answer: true
15. X += y is the same as what?
Answer: x = x+y
16. What shows in the console?
var level = 9;
var prelevel = --level;
console.log(prelevel)
answer: 8
17. The || operator is true when?
Answer: at least one side is true
18. What operator returns the remainder left over when one operand is divided by
a second?
Answer: %
19. What will the console show?
Array = [];
Array[100] = undefined;
Console.log(array.length);
Answer: 101
20. What shows in the console?
Var arr = [1,3,7,2];
arr.pop();
Console.log(arr);
Answer: [1,3,7]
21. What shows in the console?
Var arr = [2,5,10,6];
Var arr2 = ar.splice(1,1);
Console.log(arr2)
Answer: [5]
22. Convert an array into a string by using spaces as separators.
Answer: (join) (" ")
23. What shows in the console?
var arr = [7,9,3];
arr.shift();
console.log(arr);
answer: [9,3]
24. what shows in the console?
var arr = ["red", "green", "blue"];
var index = arr.imdexOf("orabge");
console.log(index);
answer: -1
25. what shows in the console?
var arr["A", "B", "C":
arr.push("D");
console.log(arr);
answer: ["A", "B", "C", "D"]
26. what shows in the console?
array = [];
array[100] = undefined;
console.log(array.length);
answer: 101
27. How to get size of an array?
var arr = [1,5,10,16]
answer: arr.length
28. What shows in the console?
var arr = [5,10,15];
console.log(arr[3]);
answer: undefined
29. what shows in the console?
var arr = [1,2,3];
arr.unshift(6);
console.log(arr);
answer: [6,1,2,3]
30. What symbol is used to seperate statements in JS?
answer: ;
31. what tag allows to write internal JS code?
answer: <script></script>
32. what shows in the console?
console.log(typeof "Hello World");
answer: string
33. How to convert string to number?
answer: Number(str)
parseInt(str)
parseFloat(str)

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

36. Write a JavaScript function that reverse a number


Answer: Example x = 32243;
Expected Output : 34223
Sample Solution : -
<body onload="reverse()">
<script>
function reverse()
{
var r=prompt("ente the number");
var t=r.split('').reverse().join('');
document.write(t);
}</script>
</body>
</html>

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"));

40) Write a JavaScript program to get the current date.


Expected Output :
mm-dd-yyyy, mm/dd/yyyy or dd-mm-yyyy, dd/mm/yyyy
Answer:
1. var today = new Date();
2. var dd = today.getDate();
3.
4. var mm = today.getMonth()+1;
5. var yyyy = today.getFullYear();
6. if(dd<10)
7. {
8. dd='0'+dd;
9. }
10.
11.if(mm<10)
12.{
13. mm='0'+mm;
14.}
15.today = mm+'-'+dd+'-'+yyyy;
16.document.write(today);
17.today = mm+'/'+dd+'/'+yyyy;
18.document.write(today);
19.today = dd+'-'+mm+'-'+yyyy;
20.document.write(today);
21.today = dd+'/'+mm+'/'+yyyy;
22.document.write(today);
41) Write a JavaScript program to calculate number of days left until next
Christmas.
Answer:
1. today=new Date();
2. var cmas=new Date(today.getFullYear(), 11, 25);
3. if (today.getMonth()==11 && today.getDate()>25)
4. {
5. cmas.setFullYear(cmas.getFullYear()+1);
6. }
7. var one_day=1000*60*60*24;
8. document.write(Math.ceil((cmas.getTime()-today.getTime())/(one_day))+
9. " days left until Christmas!");

42) Write a JavaScript program to calculate multiplication and division of two


numbers (input from user).
Answer:
HTML code:
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset=utf-8 />
5. <title>JavaScript program to calculate multiplication and division of two
numbers </title>
6. <style type="text/css">
7. body {margin: 30px;}
8. </style>
9. </head>
10.<body>
11.<form>
12.1st Number : <input type="text" id="firstNumber" /><br>
13.2nd Number: <input type="text" id="secondNumber" /><br>
14.<input type="button" onClick="multiplyBy()" Value="Multiply" />
15.<input type="button" onClick="divideBy()" Value="Divide" />
16.</form>
17.<p>The Result is : <br>
18.<span id = "result"></span>
19.</p>
20.</body>
21.</html>

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

45) Write a JavaScript function to check whether an `input` is an array or not.


Answer:
1. is_array = function(input) {
2. if (toString.call(input) === "[object Array]")
3. return true;
4. return false;
5. };
6. document.write(is_array('Early Code'));
7. document.write(is_array([1, 2, 4, 0]))

46) Write a JavaScript function to clone an array.


Answer:
1. array_Clone = function(arra1) {
2. return arra1.slice(0);
3. };
4. document.write(array_Clone([1, 2, 4, 0]));
5. document.write(array_Clone([1, 2, [4, 0]]));

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('+'));

48) Write a JavaScript program to sort the items of an array.


Answer:
1. var arr1=[-3,8,7,6,5,-4,3,2,1];
2. var arr2=[];
3. var min=arr1[0];
4. var pos;
5. max=arr1[0];
6. for (i=0; i<arr1.length; i++)
7. {
8. if (max<arr1[i]) max=arr1[i];
9. }
10.
11.for (var i=0;i<arr1.length;i++)
12.{
13. for (var j=0;j<arr1.length;j++)
14. {
15. if (arr1[j]!="x")
16. {
17. if (min>arr1[j])
18. {
19. min=arr1[j];
20. pos=j;
21. }
22. }
23. }
24. arr2[i]=min;
25. arr1[pos]="x";
26. min=max;
27.}
28.document.write(arr2);

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

51) Write a JavaScript conditional statement to sort three numbers. Display an


alert
box to show the result.
Answer:
1. var x= 0;
2. var y=-1;
3. var z= 4;
4. if (x>y && x>z)
{
6. if (y>z)
7. {
8. document.write(x + ", " + y + ", " +z);
9. }
10. else
11. {
12. document.write(x + ", " + z + ", " +y);
13. }
14.}
15.else if (y>x && y >z)
16.{
17. if (x>z)
18. {
19. document.write(y + ", " + x + ", " +z);
20. }
21. else
22. {
23. document.write(y + ", " + z + ", " +x);
24. }
25.}
26.else if (z>x && z>y)
27.{
28. if (x>y)
29. {
30. document.write(z + ", " + x + ", " +y);
31. }
32. else
33. {
34. document.write(z + ", " + y + ", " +x);
35. }
36.}

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'));

53) Write a JavaScript function to get the last day of a month


Answer:
1. var lastday = function(y,m){
2. return new Date(y, m +1, 0).getDate();
3. }
4. document.write(lastday(2014,0));
5. document.write(lastday(2014,1));
6. document.write(lastday(2014,11));

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)));

55) Write a JavaScript program to calculate age.


Answer:
1. function calculate_age(dob) {
2. var diff_ms = Date.now() - dob.getTime();
3. var age_dt = new Date(diff_ms);
4.
5. return Math.abs(age_dt.getUTCFullYear() - 1970);
6. }
7.
8. document.write(calculate_age(new Date(1982, 11, 4)));
9.
10.document.write(calculate_age(new Date(1962, 1, 1)));
56) Write a JavaScript function to get time differences in days between two dates.
Test Data :
dt1 = new Date("October 13, 2014 08:11:00");
dt2 = new Date("October 19, 2014 11:13:00");
document.write(diff_days(dt1, dt2));
Answer:
1. function diff_days(dt2, dt1)
2. {
3.
4. var diff =(dt2.getTime() - dt1.getTime()) / 1000;
5. diff /= (60 * 60 * 24);
6. return Math.abs(Math.round(diff));
7.
8. }
9.
10.dt1 = new Date(2014,10,2);
11.dt2 = new Date(2014,10,6);
12.document.write(diff_days(dt1, dt2));
13.
14.dt1 = new Date("October 13, 2014 08:11:00");
15.dt2 = new Date("October 19, 2014 11:13:00");
16.document.write(diff_days(dt1, dt2));

57) Write a JavaScript function to get the week start date.


Answer:
1. function startOfWeek(date)
2. {
3. var diff = date.getDate() - date.getDay() + (date.getDay() === 0 ? -
6 : 1);
4.
5. return new Date(date.setDate(diff));
6.
7. }
8.
9. dt = new Date();
10.
11.document.write(startOfWeek(dt).toString());

58) Write a JavaScript function to get the week end date.


Answer:
1. function endOfWeek(date)
2. {
3.
4. var lastday = date.getDate() - (date.getDay() - 1) + 6;
5. return new Date(date.setDate(lastday));
6.
7. }
8.
9. dt = new Date();
10.
11.document.write(endOfWeek(dt).toString());

59) Write a JavaScript function to get the month start date.


Answer:
1. function startOfMonth(date)
2. {
3.
4. return new Date(date.getFullYear(), date.getMonth(), 1);
5.
6. }
7.
8. dt = new Date();
9.
10.document.write(startOfMonth(dt).toString())

60) Write a JavaScript function to check whether a string is blank or not.


Answer: 1. is_Blank = function(input) {
2. if (input.length === 0)
3. return true;
4. else
5. return false;
6. }
7. document.write(is_Blank(''));
8. document.write(is_Blank('abc'));

61) Write a JavaScript function to remove specified number of characters from a


string.
Answer: 1. truncate_string = function (str1, length) {
2.
3. if ((str1.constructor === String) && (length>0)) {
4. return str1.slice(0, length);
5. }
6. };
7. document.write(truncate_string("Robin Singh",4));

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'));

63) Write a JavaScript program to copy a string to the clipboard.


Answer:
const copy_to_Clipboard = str => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected =
document.getSelection().rangeCount > 0 ?
document.getSelection().getRangeAt(0) : false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
};

64) Write a JavaScript program to converts a comma-separated values (CSV) string to


a 2D array.
Answer:
const csv_to_array = (data, delimiter = ',', omitFirstRow = false) =>
data
.slice(omitFirstRow ? data.indexOf('\n') + 1 : 0)
.split('\n')
.map(v => v.split(delimiter));

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));

65) Write a JavaScript program to convert an array of objects to a comma-separated


values (CSV) string that contains only the columns specified.
Answer:
const JSON_to_CSV = (arr, columns, delimiter = ',') =>
[
columns.join(delimiter),
...arr.map(obj =>
columns.reduce(
(acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' :
obj[key]}"`,
''
)
)
].join('\n');

console.log(JSON_to_CSV([{ x: 100, y: 200 }, { x: 300, y: 400, z: 500 }, { x: 6 },


{ y: 7 }], ['x', 'y']));
console.log(JSON_to_CSV([{ x: 100, y: 200 }, { x: 300, y: 400, z: 500 }, { x: 6 },
{ y: 7 }], ['x', 'y'], ';'));

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]));

71) Write a JavaScript program to generate a random hexadecimal color code.


Answer:
const random_hex_color_code = () => {
let n = (Math.random() * 0xfffff * 1000000).toString(16);
return '#' + n.slice(0, 6);
};

console.log(random_hex_color_code())

72) Write a JavaScript program to removes non-printable ASCII characters from a


given string.
Answer:
const remove_non_ASCII = str => str.replace(/[^\x20-\x7E]/g, '');
console.log(remove_non_ASCII('äÄçÇéÉêw3resouröceÖÐþúÚ'));

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);

75) Write a JavaScript program to return the minimum-maximum value of an array,


after applying the provided function to set comparing rule.
Answer:
const reduce_Which = (arr, comparator = (a, b) => a - b) =>
arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a));
console.log(reduce_Which([1, 3, 2]));
console.log(reduce_Which([10, 30, 20], (a, b) => b - a));
console.log(reduce_Which(
[{ name: 'Kevin', age: 16 }, { name: 'John', age: 20 }, { name: 'Ani', age:
19 }],
(a, b) => a.age - b.age));

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]));

83) Write a JavaScript program to decapitalize the first letter of a string.


Answer:
const decapitalize = ([first, ...rest], upperRest = false) =>
first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join(''));
console.log(decapitalize('Early Code'))
console.log(decapitalize('Red', true));
84) Write a JavaScript program to create a new array out of the two supplied by
creating each possible pair from the arrays.
Answer:
const xProd = (a, b) => a.reduce((acc, x) => acc.concat(b.map(y => [x, y])), []);
console.log(xProd([1, 2], ['a', 'b']));
console.log(xProd([1, 2], [1, 2]));
console.log(xProd(['a', 'b'], ['a', 'b']));

85) What are the differences between JavaScript and Java?


JavaScript doesn't strongly type one and requires additional integration in HTML to
be executed, while Java supports multi-threading, and requires JDK installation to
make it usable.

86) What data types are there in JavaScript?


There are two groups of data types in JavaScript: Primitive and Non-Primitive. The
first group includes String, Boolean, Number, BigInt, Null, undefined and Symbol.
The non-primitive data type is the Object.

87) What is the global variable?


It is the variable with global scope, so it is available from any part of the
script.

88) What problems are associated with global variables?


Global variables stay in memory all time, have lower protection as inside the
functions and may have conflicts with local variables with the same name.

89) What is the "null" in JavaScript?


The JS script returns "null" if the requested value is "empty". It may happen when
you try to request a deleted element of the script or when a variable value was
assigned with null to check it for changes during the script execution.

90) What is the "undefined" in JavaScript?


The "undefined" may be returned when you request a declared variable without any
assigned value.

91) What is the "NaN" in JavaScript?


It's a bool property which shows that object is "Not-a-Number" or vice versa.

92) What is the Array in JavaScript?


It is the kind of Object type which contains values placed in specified by user
order and has special functions and properties to work with contained data.

93) What are the objects in JavaScript?


It is the basic entity of JavaScript with its own properties and their values. How
to declare object:

94) What is the scope in JavaScript?


The scope is the area of the accessibility, and visibility of variables. The main
principle of this concept is that if a variable is not in the scope, it cannot be
referenced by functions and variables outside this scope.

95) What is the callback?


It's a function which passed as an argument in another function, so they must be
executed one-by-one.

96) What is an arrow function?


It is a short variant of declaring functions, using the "=>" symbol.
97) What is the difference between "=" "==" and "===" operators?
Their difference is in the used comparison algorithm. The "===" compares values
and data types, so it is more strict, while the "==" does the type conversion of
operands before comparison. The "=" is the assignment operator used to assign value
to variables.

98) What are the properties in JavaScript?


It is the basic characteristic of an object, generated by default and based on the
structure of property name plus property value. For example all strings in
JavaScript always have the property "length", which describes how many characters
in it.

99) What are the attributes in JavaScript?


Attributes is the part of DOM, which describes additional attributes of the element
as key-value pairs.

100) How to write functions in JavaScript?


Depending on function difficulty it can be declared in three ways: as callback
function, arrow function and inline callback function.

101) What is the difference between BOM and DOM?


Document Oriented Model is a versatile standard of interacting with web documents
(like HTML) but inside in the browsers. Browser Oriented model is non-standardized
and stands for interaction with browsers, for example its windows.

102) What is the "debugger" keyword in JS?


The debugger is the statement which makes possible using the debug functions, like
a breakpoint.

103) What JS frameworks are in use?


The most known are: React (used for UI), Angular (web dev), Vue (UI), JQuery
(client-side web dev), Ember (scalable web apps) and Node (server-side web dev).

104) What is enumerable in JavaScript?


It's the property of an object which with "true" state means that it is available
for use in loops as it is enumerable.

105) What are the main JS advantages?


Versatility (cross-platform), easy for novices, weakly typed, client-side
execution, prevails in web development.

106) Are there any JS disadvantages?


One-thread execution, strong potential of security vulnerabilities, single
inheritance, may have different interpretations according to the selected browser.

107) What is an anonymous function in JS?


It is the function declared without name.

108) How to use JavaScript in HTML?


You can write JS code inside the <script> tag, or initialize JS script from
source, via script attribute.

109) What is the window.object?


It is part of the Browser Oriented Model which refers to a current window in the
browser.

110) How to use comments in JS?


There are two types of comments in JavaScript: one-line ("//" before it) and multi-
line ("/*" before and "*/" after text).
111) What 2 groups of data types exist in JS?
Non-primitive which include only Object, and Primitive for 7 other data types.
Primitive and Non-Primitive. The first one includes String, Boolean, Number,
BigInt, Null, undefined and Symbol. The non-primitive data type is the Object.

112) How to create objects in JavaScript?


To create an object in JS you need: write directive (let, const or var), then write
variable name and close the string (";").To assign a value you need to write equal
("=") and the required value after the variable name.

113) How to create an Array in JavaScript?


Declare array name and assign its elements after the equal sign in square brackets.
If the array doesn't have elements - write only brackets.

114) What is the Infinity in JavaScript?


Infinity is the Number object which represents the mathematical infinity, so it
will always be bigger than any finite number.

115) Can Infinity be negative in JavaScript?


In JavaScript mathematical negative infinity is denoted as "-Infinity" . It is not
equal to "Infinity" and always will be less than any finite number.

116) How to catch exceptions in script execution?


Put code inside try...catch construction.

117) What is the "this" keyword in JavaScript?


Depending on how it was invoked, the keyword "this" refers to an object, global
object or element.

118) . What is the strict mode in JavaScript?


This mode enables special rules of writing JS scripts, like mandatory variables
declaring, extended reserved words list, prohibit numbers in octal system, using
"eval" statement for creating new variables and other.

119) What is the Boolean object in JavaScript?


Object which can have only two values: "false" or "true".

120) What is the Number object in JavaScript?


Object to store integer or floating point numeric values.

You might also like