cssqbso

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

1.

Explain bitwise operators available in JavaScript

Bitwise Operator: perform bitwise operations on operands

Operator Description Example

& Bitwise AND (10==20 &


20==33) = false

| Bitwise OR (10==20 |
20==33) = false

^ Bitwise XOR (10==20 ^


20==33) = false

~ Bitwise NOT (~10) = -10


<< Bitwise Left Shift (10<<2) = 40
>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with (10>>>2) = 2


Zero

2. Explain getter and setter in JavaScript

Property getter and setter


Also known as Javascript assessors.
Getters and setters allow you to control how important variables are accessed and
updated in your code.
JavaScript can secure better data quality when using getters and setters.

Following example access fullName as a function: person.fullName().


<script>
// Create an object:
var person = {
firstName: "Chirag",
lastName: "Shetty",
fullName: function () {
return this.firstName + " " + this.lastName;
}
};
document.write(person.fullName());
</script>
Following example fullName as a property: person.fullName.
<script>
// Create an object:
var person = {
firstName: "Yash ", lastName: "Desai",
get fullName() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object using a getter
document.write(person.fullName);
</script>

3. State the ways to display the output in JavaScript

• Writing into an HTML element, using innerHTML.


• Writing into the HTML output using document.write().
• Writing into an alert box, using window.alert().
• Writing into the browser console, using console.log().
4. List the logical operators in JavaScript with description

Logical Operator:

Operator Description Example

&& Logical AND (10==20 && 20==33) = false


|| Logical OR (10==20 || 20==33) = false
! Logical Not !(10==20) = true

5. Write JavaScript to create object “student”with properties roll number


,name,branch,year,Delete branch property and display remaining properties of student object.

6. Explain Object creation in JavaScript using ‘new’ keyword with adding properties and methods
with example

<html>
<body>
<script>
var object1 = new Object;
object1.name = "Rucha";
object1.nationality = "Indian";
document.write(" Name: " + object1["name"]);
document.write("<br>");
document.write("Nationality: " + object1["nationality"]);
document.write("<br><br>");
document.write("Hello, my name is " + object1.name + " and I am " +
object1.nationality);

</script>
</body>
</html>

7. Write a JavaScript for loop that will iterate from 1 to 15. For each iteration it will check if the
current number is obb or even and display a message to the screen Sample Output: “1 is odd” “2 is
even” ….............

<html>
<body>
<script>
for (let i = 1; i <= 15; i++) {
if (i % 2 === 0) {
document.write(i + " is even<br>");
} else {
document.write(i + " is odd<br>");
}
}
</script>
</body>
</html>

8. State the use of method in JavaScript with the help of suitable example.

Methods

➢JavaScript methods are actions that can be performed on objects.

➢A JavaScript function is a block of code designed to perform a particular task.

➢A JavaScript function is defined with the function keyword, followed by a name, followed
by parentheses ().

➢The parentheses may include parameter names separated by commas:

(parameter1, parameter2, ...)

➢The code to be executed, by the function, is placed inside curly brackets: {}

➢Syntax:

function name(parameter1, parameter2, parameter3) {


// code to be executed
}
9. List & explain datatypes in JavaScript

Data Types: Primitive


Primitive data types can hold only one value at a time.
1) The String Data Type
The string data type is used to represent textual data (i.e. sequences of
characters).characters, as shown below:
var a = ‘Welcome'; // using single quotes
var b = “Welcome”;// using double quotes
2) The Number Data Type
✓ The number data type is used to represent positive or negative
numbers with or without decimal place.
✓ The Number data type also includes some special values which
are: Infinity,-Infinity, NaN(Not a Number)
✓ Example,
var a = 25; // integer
var b = 80.5; // floating-point number
var c = 4.25e+6; // exponential notation, same as 4.25e6 or 4250000
var d = 4.25e-6; // exponential notation, same as 0.00000425
3) The Boolean Data Type
✓ The Boolean data type can hold only two values: True/False
✓ Example,
var a = 2, b = 5, c = 10;
alert(b > a) // Output: true
alert(b > c) // Output: false

4) The Undefined Data Type


✓ The undefined data type can only have one value-the special value “undefined”.
✓ If a variable has been declared, but has not been assigned a value, has the
value ”undefined”.
✓ Example,
var a;
var b = “Welcome”;
alert(a) // Output: undefined
alert(b) // Output: Welcome

5) The Null Data Type


✓ A Null value means that there is no value.
✓ It is not equivalent to an empty string (“ “) or zero or it is simply nothing.
✓ Example,
var a = null;
alert(a); // Output: null
var b = "Hello World!“
alert(b); // Output: Hello World!
b = null;
alert(b) // Output: null

Data Types: Non-primitive

1) The Object Data Type


✓ a complex data type that allows you to store collections of data.
✓ An object contains properties, defined as a key-value pair.
✓ A property key (name) is always a string, but the value can be any data type, like
strings, numbers, Boolean, or complex data types like arrays, function and other
objects.
✓ Example,
var car =
{ model: “SUZUKI", color: “WHITE", model_year: 2019 }

2) The Array Data Type


✓ An array is a type of object used for storing multiple values in single variable.
✓ Each value (also called an element) in an array has a numeric position, known as its
index, and it may contain data of any data type-numbers, strings, Booleans,
functions, objects, and even other arrays.
✓ The array index starts from 0, so that the first array element is arr [0].
✓ The simplest way to create an array is by specifying the array elements as a comma-
separated list enclosed by square brackets, as shown in the example below:
✓ var cities = ["London", "Paris", "New York"];
✓ alert(cities[2]); // Output: New York
✓ var a = ["London", 500, ”aa56”, 5.6];

3) The Function Data Type


✓ The function is callable object that executes a block of code.
✓ Since functions are objects, so it is possible to assign them to variables, as shown in
the example below:
var ab = function()
{
return “Welcome”;
}
alert(typeof ab); //output: function
alert(ab()); //output:Welcome
10. Write a simple calculator program using switch case in JavaScript. 1

<html>
<body>
<script>
var result;
var operator = prompt('Enter operator ( either +, -, * or / ): ');
var number1 = parseFloat(prompt('Enter first number: '));
var number2 = parseFloat(prompt('Enter second number: '));
switch(operator)
{
case '+':
result = number1 + number2;
document.write(number1 + ' + ' + number2 + ' = ' + result);
break;
case '-':
result = number1 - number2;
document.write(number1 + ' - ' + number2 + ' = ' + result);
break;
case '*':
result = number1 * number2;
document.write(number1 + ' * ' + number2 + ' = ' + result);
break;
case '/':
result = number1 / number2;
document.write(number1 + ' / ' + number2 + ' = ' + result);
break;
default:
document.write('Invalid operator');
break;
}
</script>
</body>
</html>

11. State the features of JavaScript.


12. Write a JavaScript program to check whether entered number is prime or not.

<html>
<body>
<script>
function isPrime(num) {
if (num <= 1) {
return false; // Numbers less than or equal to 1 are not prime
}
for (let i = 2; i < num; i++) {
if (num % i === 0) {
return false; // If divisible by any number other than 1 and
itself
}
}
return true;
}
var number = parseInt(prompt("Enter a number:"));
if (isPrime(number)) {
document.write(number + " is a prime number.");
} else {
document.write(number + " is not a prime number.");
}
</script>
</body>
</html>

13. Write a JavaScript program to validate user accounts for multiple set of user ID and password
(using switch case statement).
<html>
<body>
<script>
var userID = prompt("Enter your user ID:");
var password = prompt("Enter your password:");
switch (userID) {
case "user1":
if (password === "password1") {
document.write("Welcome, User 1!");
} else {
document.write("Invalid password for User 1.");
}
break;
case "user2":
if (password === "password2") {
document.write("Welcome, User 2!");
} else {
document.write("Invalid password for User 2.");
}
break;
case "admin":
if (password === "adminpass") {
document.write("Welcome, Admin!");
} else {
document.write("Invalid password for Admin.");
}
break;
default:
document.write("User ID not recognized.");
}
</script>
</body>
</html>

14. Differentiate between For-loop and For-in loop.


15. Write a JavaScript to checks whether a passed string is palindrome or not.

function checkPalindrome(string) {
const arrayValues = string.split('');
const reverseArrayValues = arrayValues.reverse();

const reverseString = reverseArrayValues.join('');


if(string == reverseString) {
document.write('It is a palindrome');
}
else {
document.write('It is not a palindrome');
}
}
const string = prompt('Enter a string: ');

checkPalindrome(string);
16. Define a function with example.
The Function Data Type
✓ The function is callable object that executes a block of code.
✓ Since functions are objects, so it is possible to assign them to variables, as shown in
the example below:
var ab = function()
{
return “Welcome”;
}
alert(typeof ab); //output: function
alert(ab()); //output:Welcome
Code:

<html>
<body>
<h1>JavaScript Array</h1>
<script>
var stringArray = ["one", "two", "three"];
var mixedArray = [1, "two", "three", 4];
document.write(stringArray+"<br>");
JavaScript Array
document.write( mixedArray); one,two,three
</script> 1,two,three,4
</body>
</html>

17. List datatypes in JavaScript.

JavaScript Data Types

Primitive (Primary) Non-Primitive


(Composite)
String Number Boolean Undefined Null

Object Array Function

18. List form events.


19. Define array in JavaScript with example.

The Array Data Type


✓ An array is a type of object used for storing multiple values in single variable.
✓ Each value (also called an element) in an array has a numeric position, known as its
index, and it may contain data of any data type-numbers, strings, Booleans,
functions, objects, and even other arrays.
✓ The array index starts from 0, so that the first array element is arr [0].
✓ The simplest way to create an array is by specifying the array elements as a comma-
separated list enclosed by square brackets, as shown in the example below:
✓ var cities = ["London", "Paris", "New York"];
✓ alert(cities[2]); // Output: New York
✓ var a = ["London", 500, ”aa56”, 5.6];
20. Write the use of following String methods: a) charCodeAt() b) fromCharCode()

charCodeAt() It returns the ASCII code of the character at the specified position.
fromCharCode() It converts Unicode value into characters

21. Explain calling a function with arguments in JavaScript with example.

Calling function with arguments

You can pass arguments to a function.

These are variables, either numbers or strings, with which the function is supposed to do something.

Of course the output of the function depends on the arguments you give it.

Syntax:

function function_name(arg1, arg2) {

lines of code to be executed

Example

<html>
<body>
<script>
function ShowMessage(firstName, lastName) {
var message = "Hello, " + firstName + " " + lastName + "!";
document.write(message);
}
ShowMessage("John", "Doe");
</script>
</body>
</html>

22. Differentiate between push() and join() method of array object with respect to
use,syntax,return value and example.

23. Write a Javascript code to perform following operation on string (Use split() method) Input
string : Sudha Narayana Murthy” Display output as First Name:Sudha Middle Name: Narayana Last
Name: Murthy

<html>
<body>
<script>
var fullName = "Sudha Narayana Murthy";
var parts = fullName.split(' ');
var firstName = parts[0];
var middleName = parts.slice(1, -1).join(' '); // Join middle names if
there are multiple
var lastName = parts[parts.length - 1];
document.write("First Name: " + firstName + "<br>");
document.write("Middle Name: " + middleName + "<br>");
document.write("Last Name: " + lastName);
</script>
</body>
</html>

24. Explain splice() method of array object with syntax and example.

Thesplice() method can be used to add new items to an array, and removes elements from an array.

Syntax: arr.splice(start_index,removed_elements, list_of_elemnts_to_be_added)

<!DOCTYPE html>
<html>
<body>
<script>
var fruits = ["Banana", "Watermelon", "Chikoo", "Mango", "Orange",
"Apple"];
document.write(fruits+"<br>");
fruits.splice(2,2, "Lemon", "Kiwi");
document.write(fruits+"<br>");
fruits.splice(0,2);
document.write(fruits+"<br>");
</script>
</body>
</html>

25. Write a program using sort method of array object.

<html>
<body>
<script>
var fruits = ["Banana", "Watermelon", "Chikoo", "Mango", "Orange",
"Apple"];
fruits.sort();
document.write(fruits+"<br>");
</script>
</body>
</html>
26. Write a JavaScript program that will display current date in DD/MM/YYYY format.

<html>
<body>
<script>
var now = new Date();
var day = now.getDate();
var month = now.getMonth() + 1;
var year = now.getFullYear();
document.write("Current Date: " + day + '/' + month + '/' + year);
</script>
</body>
</html>

27. Write a JavaScript program that will remove the duplicate element from an Array.

28. Write a JavaScript program that will display list of student in ascending order according to the
marks & calculate the average performance of the class.

<html>
<body>
<script>
var students = [
{ name: "Alice", marks: 85 },
{ name: "Bob", marks: 78 },
{ name: "Charlie", marks: 92 },
{ name: "David", marks: 70 },
{ name: "Eva", marks: 88 }
];
for (var i = 0; i < students.length - 1; i++) {
for (var j = i + 1; j < students.length; j++) {
if (students[i].marks > students[j].marks) {
var temp = students[i];
students[i] = students[j];
students[j] = temp;
}
}
}
var totalMarks = 0;
for (var i = 0; i < students.length; i++) {
totalMarks += students[i].marks;
}
var averageMarks = totalMarks / students.length;
document.write("<br>Students Sorted by Marks (Ascending Order):");
for (var l = 0; l < students.length; l++) {
document.write("<br>" +students[l].name + ": " + students[l].marks
);
}
document.write("<br>Average Marks: " + averageMarks.toFixed(2));
</script>
</body>
</html>

29. Write and explain a string functions for converting string to number and number to string.
Converting string to Number

parseInt(): converts a string into an integer.

parseFloat(): converts a string into a decimal points. (floating point)

Number( ): converts a string into number.

Converting Numbers into string

toString(): convert integer value and decimal value into a string.

30. Differentiate between concat( ) & join( ) methods of array object.

31. Write a JavaScript function to check the first character of a string is uppercase or not.

<html></html>
<head>
<title>Sort Array Elements</title>
<script>
function isFirstCharUpperCase(str) {
return str.length > 0 && str[0] === str[0].toUpperCase();
}
document.write(isFirstCharUpperCase("Hello")+ "<br>"); // true
document.write(isFirstCharUpperCase("hello")); // false
</script>
</head>
</html>

32. Write a JavaScript function to merge two array & removes all duplicate values.

<html>
<head>
<title>Sort Array Elements</title>
<script>
function removeDuplicates(arr) {
return arr.filter((item, index) => arr.indexOf(item) === index);
}
var array1 = [1, 2, 3, 4];
var array2 = [3, 4, 5, 6];
var mergedArray = array1.concat(array2);
document.write("Merged array: " +mergedArray);
var uniqueArray = removeDuplicates(mergedArray);
document.write("<br>Merged array with duplicates removed: " +
uniqueArray.join(", "));
</script>
</head>
</html>

33. Write a javascript function that accepts a string as a parameter and find the length of the
string.

<html>
<head>
<title>Sort Array Elements</title>
<script>
function getStringLength(str) {
return str.length;
}
var myString = "Hello, World!";
document.write("String: " +myString);
document.write("<br>Length of the string:"+getStringLength(myString));
</script>
</head>
</html>

34. Develop javascript to convert the given character to unicode and vice-versa.

<html>
<head>
<title>Sort Array Elements</title>
<script>
var char = prompt("Enter a character:");
if (char) {
alert("Unicode code point: " + char.charCodeAt(0));
}
var unicode = prompt("Enter a Unicode code point:");
unicode = parseInt(unicode, 10);
if (!isNaN(unicode)) {
alert("Character: " + String.fromCharCode(unicode));
}
</script>
</head>
</html>

35. Write a javascript function to generate Fibonacci series till user defined limit.

<html>
<head>
<title>Sort Array Elements</title>
<script>
var limit = Number(prompt("Enter the upper limit for the Fibonacci
series:"), 10);
var a = 0, b = 1;
document.write(a + ", " + b);
while (b <= limit) {
var next = a + b;
document.write(", " + next);
a = b;
b = next;
}
document.write("Fibonacci series up to " + limit + ": " + result);
</script>
</head>
</html>

36. Write a Java Script code to display 5 elements of array in sorted order.

<html>
<head>
<title>Sort Array Elements</title>
<script>
var numbers = [12, 5, 8, 130, 44];
document.write("Original Array:" +numbers+ "<br>");
numbers.sort(function (a, b) {
return a - b;
});
document.write("Sorted Array:" +numbers);
</script>
</head>
</html>

37. Define objects and write different ways to create an Object with example.

A. Define and create a single object, using an object literal.

• Using an object literal, you both define and create an object in one statement.

• An object literal is a list of names: value pairs (like age:10) inside curly braces {}.

• The following example creates a new JavaScript object with 3 properties:

var person = { firstName: “Hhh", lastName: “Bbb", age: 10 };


B. Define and create a single object, with the keyword “new” OR by creating instance of Object
new keyword is used to create object.

Syntax: var objectname=new Object();

Example: var person = new Object();

person.firstName = “Hhh";

person.age = 10;

C. Define an object constructor, and then create objects of the constructed type.

Here, you need to create function with arguments. Each argument value can be assigned in the
current object by using this keyword.

The this keyword refers to the current object.

Example:

function person(firstName, lastName, age) {

this. firstName = firstName;

this. lastName = lastName;

this. age = age;

p=new person(“aaa”,”vvv”,10);

document.write(p.firstName+" "+p.lastName+" "+p.age);

38. Write a JavaScript to demonstrate the use of Checkbox with example.

<html>
<head>
<title>Checkbox Example</title>
<script>
function showSelectedFruits() {
var checkboxes = document.getElementsByName('fruits');
var selectedFruits = [];
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
selectedFruits.push(checkboxes[i].value);
}
}
document.getElementById('result').innerHTML = "Selected Fruits: "
+ selectedFruits.join(', ');
}
</script>
</head>
<body>
<h2>Select Your Favorite Fruits</h2>
<input type="checkbox" name="fruits" value="Apple"> Apple<br>
<input type="checkbox" name="fruits" value="Banana"> Banana<br>
<input type="checkbox" name="fruits" value="Cherry"> Cherry<br>
<input type="checkbox" name="fruits" value="Date"> Date<br>
<input type="checkbox" name="fruits" value="Mango"> Mango<br><br>
<button onclick="showSelectedFruits()">Show Selected Fruits</button>
<div id="result"></div>
</body>
</html>

39. Write JavaScript that initializes an array called Colors with the names of 3 Colors and display
array elements.

<html>
<head>
<title>Display Colors</title>
<script>
var Colors = ["Red", "Green", "Blue"];
function displayColors() {
for (var i = 0; i < Colors.length; i++) {
document.write(Colors[i] + "<br>");
}
}
</script>
</head>
<body>
<h2>Color List</h2>
<button onclick="displayColors()">Show Colors</button>
</body>
</html>

40. Write HTML code to design a form that display two textboxes for accepting two numbers,one
textbox for accepting result and two buttons as ADDITION and SUBTRACTION.Write proper
JavaScript such that when the user clicks on any one of the button,respective operation will be
performed on two numbers and result will be displayed in result textbox.

<html>
<head>
<title>Simple Calculator</title>
<script>
function performAdd () {
var num1 = parseFloat(document.getElementById('num1').value);
var num2 = parseFloat(document.getElementById('num2').value);
var result = num1 + num2;
document.getElementById('result').value = result;
}

function performSub () {
var num1 = parseFloat(document.getElementById('num1').value);
var num2 = parseFloat(document.getElementById('num2').value);
var result = num1 - num2;
document.getElementById('result').value = result;
}
</script>
</head>
<body>
<h2>Simple Calculator</h2>
<form>
<label for="num1">Number 1:</label>
<input type="text" id="num1" name="num1"><br><br>

<label for="num2">Number 2:</label>


<input type="text" id="num2" name="num2"><br><br>

<label for="result">Result:</label>
<input type="text" id="result" name="result" readonly><br><br>

<button type="button" onclick="performAdd ()">ADD</button>


<button type="button" onclick="performSub ()"> SUBTRACT</button>
</form>
</body>
</html>

You might also like