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

JAVA Script Assignment

1.What will the code below output to the console and why?
( function() {
var a = b = 3 ;
})();

console .log( "a defined? " + ( typeof a !== 'undefined' ));


console .log( "b defined? " + ( typeof b !== 'undefined' ));

Java Script:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
(function(){
var a = b = 3;
})();
console.log("a defined? " + (typeof a !== 'undefined'));
console.log("b defined? " + (typeof b !== 'undefined'));
</script>
</head>
<body>

</body>
</html>
b = 3;
var a = b;
Output Console:
2.Write a simple function (less than 160 characters) that returns a boolean
indicating whether or not a string is a palindrome.
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
textarea
{
border-radius: 4px;
width: 250px;
height: 90px;
background-color: #f2f2f2;
}
</style>
<body>
<textarea type="text" id="string" required placeholder= "Enter the
string"></textarea><br>
<button type="button" onclick="palindrome()">enter</button><br>
<p id="demo"></p>
</body>
<script type="text/javascript">
function getInputFromTextBox()
{
var string1 = document.getElementById("string").value;
console.log(string1);
var string2 = string1.split("").reverse().join("");
if((string1==string2)&&(string1.length<160))
{
return true;

}
else
{
return false;
}
}
function palindrome()
{
if(getInputFromTextBox()==true)
{
document.getElementById("demo").innerHTML =
"The Entered string is a Palindrome";
}
else
{
document.getElementById("demo").innerHTML =
"The Entered string is not a Palindrome";}}
</script>
</head>
</html>
Output:

4. Let and Const

1. Declare a constant variable, PI, and assign it the value Math.PI. You
will not pass this challenge unless the variable is declared as a constant
and named PI (uppercase).
2. Read a number, r, denoting the radius of a circle from stdin.
3. Use PI and r to calculate the area and perimeter of a circle having
radius r.
4. Print area as the first line of output and print perimeter as the second
line of output.
Code:
<html>
<head>
<title> </title>
</head>
<body>
<script>
const PI=3.14;
var r=Number(prompt("Enter the value"));
let area=PI*r*r;
alert(area);
let perimeter=2*PI*r;
alert(perimeter);
</script>
</body>
</html>
Output:
Area:

Perimeter:

5. Complete the getGrade(score) function in the editor. It has one parameter: an


integer, score, denoting the number of points Julia earned on an exam. It must
return the letter corresponding to her grade according to the following rules:

· If 25 < score ≤ 30 , then grade = A.

· If 20 < score ≤ 25 , then grade = B.


· If 15 < score ≤ 20 , then grade = C.

· If 10 < score ≤ 15 , then grade = D.

· If 5 < score ≤ 10 , then grade = E.

· If 0 < score ≤ 5 , then grade = F.


Code:
<!DOCTYPE html>
<html>
<head>
<title> </title>
</head>
<body>

<script type="text/javascript">
var score=Number(prompt("Enter the value"));
function score(score)
{

if(score>25 && score<=30)


{
document.write("Grade A");
}
else if(score>20 && score<=25)
{
document.write("Grade B");
}
else if(score>15 && score<=20)
{
document.write("Grade C");
}
else if(score>10 && score<=15)
{
document.write("Grade D ");
}
else if(score>5 && score<=10)
{
document.write("Grade E");
}
else if(score>0 && score<=5)
{
document.write("Grade F");
}

}
</script>
</body>
</html>
Output:
7. Complete the vowelsAndConsonants function in the editor below. It has one
parameter, a string, s, consisting of lowercase English alphabetic letters (i.e., a
through z). The function must do the following:

1. First, print each vowel in s on a new line. The English vowels are a, e,
i, o, and u, and each vowel must be printed in the same order as it
appeared in s.

2. Second, print each consonant (i.e., non-vowel) in s on a new line in


the same order as it appeared in s.

Code:
<html>
<head> <title> </title>
</head>
<body>
<script>
const vowels=['A','E','I','O','U','a','e','i','o','u'];

function countVowels(sentence)
{
let counts = 0;
for(let i = 0; i < vowels.length; i++)
{
if(vowels.includes(sentence[i]))
{
counts++;
}
}
return document.write(counts);
}
countVowels(Nareshpriya);
</script>
</body>
</html>

Output:
9. Complete the reverseString function; it has one parameter, s. You must
perform the following actions:

1. Try to reverse string s using the split, reverse, and join methods.

2. If an exception is thrown, catch it and print the contents of the


exception’s messages on a new line.

3. Print s on a new line. If no exception was thrown, then this should be


the reversed string; if an exception was thrown, this should be the
original string.

Code:

<html>

<head> <title> </title>


</head>

<body>

<script>

function ReverseString(str) {

if(!str || str.length < 2 || typeof str!== 'string')

return 'Not valid';

const revArray = [];

const length = str.length - 1;

for(let i = length; i >= 0; i--) {

revArray.push(str[i]);

return revArray.join('');

}
Document.write(ReverseString("Nareshbaby"));

</script>

</body>

</html>

Output

10. Complete the isPositive function below. It has one integer parameter, a. If
the value of a is positive, it must return the string YES. Otherwise, it must throw
an Error according to the following rules:

· If a is 0, throw an Error with message = Zero Error.

· If a is negative, throw an Error with message = Negative Error.

Code:

<!DOCTYPE html>
<html>

<head>

<title></title>

</head>

<body>

<script type="text/javascript">

ispositive(-4);

function ispositive(num)

if(num>0)

document.write("Yes");

else if(num<0)

document.write("message=Negative Error");

else
{

document.write("message=Zero Error");

</script>

</body>

</html>

Output:

11. Complete the function in the editor. It has one parameter: an array, a, of
objects. Each object in the array has two integer properties denoted by x and y. The
function must return a count of all such objects o in array a that satisfy o.x == o.y.

Code:
<html>
<head> <title> </title>
</head>
<body>
<script>

function getCount(objects)
{
return objects.reduce((target, item) =>
{
(item.x === item.y) && (target += 1);

return target;
}, 0);
}
</script>
</body>
</html>

12. Create a function that will convert from Celsius to Fahrenheit

Code:

<html>
<head> <title> JavaScript Celsius to Farenhit </title>
</head>
<body>
<script>
function cToF(celsius)
{
var cTemp = celsius;
var cToFahr = cTemp * 9 / 5 + 32;
var message = cTemp+'\xB0C is ' + cToFahr + ' \xB0F.';
console.log(message);
}

function fToC(fahrenheit)
{
var fTemp = fahrenheit;
var fToCel = (fTemp - 32) * 5 / 9;
var message = fTemp+'\xB0F is ' + fToCel + '\xB0C.';
console.log(message);
}
document.write(cToF(30));
document.write(fToC(30));

</script>
</body>
</html>
Output:
13. Calculate the sum of numbers in an array of numbers

Code:

<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body>

<script type="text/javascript">

var array = [1, 2, 3, 4, 5];

var sum=0;

for(var i=0;i<=array.length;i++)

sum=sum+i;

alert("Array addition is:"+sum);

</script>
</body>

</html>

Output:

14. Create a function that receives an array of numbers and returns an array
containing only the positive numbers

Code:

<html>

<head>

<title></title>

</head>

<body>

<script>

var value = Math.abs(-1);

document.write("First Test Value : " + value );


var value = Math.abs(null);

document.write("<br />Second Test Value : " + value );

var value = Math.abs(20);

document.write("<br />Third Test Value : " + value );

var value = Math.abs("string");

document.write("<br />Fourth Test Value : " + value );

</script>

</body>

</html>

Output:
15. Create a function that will find the nth Fibonacci number using recursion

Code:

<html>

<head> <title> </title>

</head>

<body>

<script>

var num1 = 0, num2 = 1, sum, i;

var num = parseInt (prompt (" Enter the limit for Fibonacci Series "));

document.write( "Fibonacci Series: ");

for ( i = 1; i <= num; i++)

document.write (" <br> " + num1);

sum = num1 + num2;

num1 = num2;

num2 = sum;

}
</script>

</body>

</html>Output:

16. Create a function that will receive two arrays of numbers as arguments and
return an array composed of all the numbers that are either in the first array or
second array but not in both

Code:
<html>

<head> <title></title>

</head>

<body>

<script>

function findMissing(a,b,n,m)

for (let i = 0; i < n; i++)

let j;

for (j = 0; j < m; j++)

if (a[i] == b[j])

break;

if (j == m)

document.write(a[i] + " ");

}
let a=[ 1, 2, 6, 3, 4, 5 ];

let b=[2, 4, 3, 1, 5];

let n = a.length;

let m = b.length;

findMissing(a, b, n, m);

</script>

</html>

Output:

Missing number in the array

17. Create a function that will add two positive numbers of indefinite size. The
numbers are received as strings and the result should be also provided as string.

Code:

<html>

<head> <title></title>
</head>

<body>

<script>

function findSum(str1, str2)

if (str1.length > str2.length)

let t = str1;

str1 = str2;

str2 = t;

let str = "";

let n1 = str1.length, n2 = str2.length;

str1 = str1.split("").reverse().join("");

str2 = str2.split("").reverse().join("");

let carry = 0;

for(let i = 0; i < n1; i++)

{
let sum = ((str1[i].charCodeAt(0) -'0'.charCodeAt(0)) +
(str2[i].charCodeAt(0) -'0'.charCodeAt(0)) + carry);

str += String.fromCharCode(sum % 10 +'0'.charCodeAt(0));

carry = Math.floor(sum / 10);

for(let i = n1; i < n2; i++)

let sum = ((str2[i].charCodeAt(0) -

'0'.charCodeAt(0)) + carry);

str += String.fromCharCode(sum % 10 +

'0'.charCodeAt(0));

carry = Math.floor(sum / 10);

if (carry > 0)

str += String.fromCharCode(carry +'0'.charCodeAt(0));

str = str.split("").reverse().join("");

return str;

}
let str1 = "12";

let str2 = "148153";

document.write(findSum(str1, str2))

</script>

</body>

</html>

Output:

18. Create a function that will capitalize the first letter of each word in a text

Code:
<html>

<head> <title></title>

</head>

<body>

<script>

function capitalize(input)

return input.toLowerCase().split(' ').map(s => s.charAt(0).toUpperCase() +


s.substring(1)).join(' ');

const string = prompt('Enter a string : ');

const value = capitalize(string);

document.write(value);

</script>

</body>

</html>

Output:
19. Create a function that will convert a string in an array containing the ASCII
codes of each character

Code:

Output:

20. Create a function to calculate the distance between two points defined by
their x, y coordinates

Code:

<html>

<head> <title></title>

</head>
<body>

<script>

function getDistance(x1,y1,x2,y2)

let y = x2 - x1;

let x = y2 - y1;

return document.write(Math.sqrt(x * x + y * y));

getDistance(20,50,100,50);

</script>

</body>

</html>

Output:

You might also like