0% found this document useful (0 votes)
13 views12 pages

CSS Chapter 1Notes

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 12

Unit I : Basics of JavaScript Programming

Unit Outcomes(UOs)
1a. Create object to solve the given problem.
1b. Develop JavaScript to implement the switch-case statement for the given problem
1c. Develop JavaScript to implement loop for solving the given iterative problem.
1d. Display properties of the given object using letters and setters.
1e. Develop program using basic features of JavaScript to solve the given problem.

Contents
1.1 Features of JavaScript.
1.2 Object Name, Property, method, Dot syntax, main event.
1.3 Values and Variables.
1.4 Operators and Expressions – Primary expressions, Object and Array initializers, function
definition expression, property access expressions, invocation expressions.
1.5 If Statement, if…else, if….elseif, nested if statement.
1.6 Switch…case statement.
1.7 Loop statement – for loop, for…in loop, while loop, continue statement.
1.8 Querying and setting properties and deleting properties, property getters and setters.

2 Marks Questions
1. Enlist any four features of JavaScript.
• JavaScript is a object-based scripting language.
• Giving the user more control over the browser.
• It Handling dates and time.
• It Detecting the user's browser and OS
• It is light weighted.
• Client – Side Technology
• JavaScript is a scripting language and it is not java.
• JavaScript is interpreter based scripting language.
• JavaScript is case sensitive.
• JavaScript is object based language as it provides predefined objects.
• Every statement in JavaScript must be terminated with semicolon (;).
• Most of the JavaScript control statements syntax is same as syntax of control statements in C
language.
• An important part of JavaScript is the ability to create new functions within scripts. Declare a
function in JavaScript using function keyword

2. List the comparison operators in JavaScript.


Example:
<script>
// = is used to assign a value to a variable
var num = 10;
document.write(num); // num 10
/* += first add the value to the existing value of the variable then
assign it the new added value */
num +=10;
document.write(num); // num 20
</script>

3. List and explain data types in JavaScript.


It uses six types of values:
• Number: It is numeric value can be integer or float.
For Example : var a=20;

• String: It is a collection of characters. Enclosed within single or double quote.


For Example : car city=”Nashik”

• Boolean: It contains true and false values.


For Example : var b=true;

• Null: This value can be assigned by reserved word ‘null’. It means no value.
For Example : var i=null;
• Object: It is the entity that represents some value. Ex: Form is an object on which some
components can be placed and used.
For Example : var person = { firstname:"John", lastname:"Doe"};

4. Explain the terms


i) Method ii) Property iii) Event iv) Object Name
OR
State the use of Object, Method and Property in JavaScript

Object Name:
• Object is entity. In JavaScript document, window, forms, fields, buttons are some properly used
objects.
• Each object is identified by ID or name.
• Array of objects or Array of collections can also be created.

Property:
• It is the value associated with each object.
• Each object has its own set of properties.
• For example, a form object has a title, a width, and a height—to mention a few properties

Method:
• A method is a process performed by an object when it receives a message.
• For example, a Submit button on a form is an object. Its Submit label and the dimensions of the
button are properties of the button object.
• If you click the Submit button, the form is submitted to the server-side application. In other
words, clicking the Submit button causes the button to process a method.
Main Event:
• Event causes JavaScript to execute the code.
• In JavaScript when user submits form, clicks button, writes something to text box the
corresponding event gets triggered and execution of appropriate code is done through Event
Handling.

5. How to write a JavaScript?


• JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page.
• You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it
is normally recommended that you should keep it within the <head> tags.
• The <script> tag alerts the browser program to start interpreting all the text between these tags as
a script.

• A simple syntax of your JavaScript will appear as follows.


<script ...>
JavaScript code
</script>

• The script tag takes two important attributes −


• Language − This aLribute specifies what scripNng language you are using.
• Type − This aLribute is what is now recommended to indicate the scripNng language in use
and its value should be set to "text/javascript".
• So your JavaScript segment will look like −
<script language = "javascript" type = "text/javascript">
JavaScript code
</script>

Example :
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>

6. Write a JavaScript program that will print even numbers from 1 to 20


<html>
<body>
<script type="text/javascript">
vari;
for(i=1; i<=20;i++)
{
if(i%2==0)
{
document.write(i+"<br>");
}
}
</script>
</body>
</html>
7. Write a JavaScript to create person object with properties firstname, lastname, age, eye color,
delete eye color property and display remaining properties of person object.
<html>
<body>
<script>
var person = {
firstname:"John",
lastname:"Doe",
age:50,
eyecolor:"blue"
};
delete person.eyecolor; //delete person eyecolor
document.write("After delete "+ person.firstname +" "+
person.lastname+" "
+person.age +" "+ person.eyecolor);
</script>
</body>
</html>

8. Describe property Getters & Setter.


In JavaScript, accessor properties are methods that get or set the value of an object. For that, we use
these two keywords:
get - to define a getter method to get the property value
set - to define a setter method to set the property value
The following example shows a getter defined on an object called person. The getter is called name,
and it returns the value of the name property on the object:
let person = {
name: 'John',
get name() {
return this.name;
}
};
For example, let's say we have an object called "user" with a property called "name". We can define
a setter method for the "name" property like this:
const user = {
name: '',
set name(value) {
this.name = value;
},
};

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


<head>
<title>Check a number is prime pr not using javascript</title>
<script type="text/javascript">
function prime()
{
var n,i,flag=true;
n=document.myform.n.value;
for(i=2;i<=n/2;i++)
{
if(n%i==0)
{
flag=false;
break;
}
}
if(flag==true)
{
alert(n+"is prime");
}
else
{
alert(n+"is not prime");
}
}
</script>
</head>
<body>
<form name="myform">
Enter the Number:<input type="text" name=n value=" ">
<br><br>
<input type="button" value="Check" onClick="prime()">
<br>
</form>
</body>
</html>

10. Write and explain syntax of prompt( ) method in JavaScript.


•prompt() method is used to display a dialogue box to the user to prompt them to an input.
•It has two buttons “OK” and “CANCEL”, if the user click on the “OK” button then it will return the
inputed value , if the user clicks on the "CANCEL” button then it will return a null value
• Syntax: prompt(text)
Example:
<script>
var name = prompt ("Enter a name");
document. Write(name);
</script>

11. Give syntax of and explain the use of small “with” clause.
“with” clause is used to directly access the properties and method of an object.
Syntax:
with (object)
{
//object
}
Example:
<script>
var person ={ name:"Abc", age:18}
with(person){ docment.write(name);
docment.write(age);
}
</script>
12. Write a JavaScript that accepts a number and displays addition of digits of that number in a
message box.
<html>
<body>
<script>
var num = prompt(“Enter a 2 digit number:”); //accept number from user
var digits = num.split();
var firstdigit = Integer(digits[0]);
var seconddigit = Integer(digits[1]);
var addition = firstdigit+seconddigit;
alert(“The addition is “+addition); //display result in message box
</script>
</body>
</html>

13. Give syntax of and explain for-in loop in javascript with the help of suitable example.
For-in Loop:
Syntax:-
For(x in object){
//code to be executed
}
• For-in loop is used to loop through the properties of an object.
• In syntax, variable represents the property name, and object is the object being iterated.
• It's handy for tasks like accessing or manipulating object properties.

Example:-
<html>
<body>
<script>
Var car = { Brand: ‘Toyota’, Model: ‘Camry’, Year: 2022
};
For( key in car){ Document.write(‘${key}: ${car[key]}’);
}
</script>
</body>
</html>

14. Write a JavaScript function that accepts string as a paramenter and find the length of the string.
<html>
<body>
<script type="text/javascript">
var str="HelloWorld";
document.write("The given string is:"+str);
document.write("<br>TheLength of given string is:"+str.length);
</script>
</body>
</html>
4 Marks Questions
15. Write a simple calculator program using switch case in JavaScript
<html>
<body>
<script>
let result;
const operator = prompt('Enter operator ( either +, -, * or / ): ');

const number1 = parseFloat(prompt('Enter first number: '));


const number2 = parseFloat(prompt('Enter second number: '));

switch(operator) {
case '+':
result = number1 + number2;
console.log(`${number1} + ${number2} = ${result}`);
break;

case '-':
result = number1 - number2;
console.log(`${number1} - ${number2} = ${result}`);
break;

case '*':
result = number1 * number2;
console.log(`${number1} * ${number2} = ${result}`);
break;

case '/':
result = number1 / number2;
console.log(`${number1} / ${number2} = ${result}`);
break;

default:
console.log('Invalid operator');
break;
}
</script>
</body>
</html>

16. Write a JavaScript program which computes average marks of the student and according to
average marks determine the grade
<html>
<head>
<title>Compute the average marks and grade</title>
</head>
<body>
<script>
var students = [['Summit', 80], ['Kalpesh', 77], ['Amit', 88],
['Tejas', 93],['Abhishek', 65]];
var Avgmarks = 0;
for (var i=0; i < students.length; i++)
{
Avgmarks += students[i][1];
}
var avg = (Avgmarks/students.length);
document.write("Average grade: " + (Avgmarks)/students.length);
document.write("<br>");
if (avg < 60)
{
document.write("Grade : E");
}
else if (avg < 70)
{
document.write("Grade : D");
}
else if (avg < 80)
{
document.write("Grade : C");
}
else if (avg < 90)
{
document.write("Grade : B");
}
else if (avg < 100)
{
document.write("Grade : A");
}
</script>
</body>
</html>

17. Differentiate BETWEEN For-loop and For-in loop.


• for loop is a method available for arrays in JavaScript. It allows you to iterate over each
element in an array and perform a specific action for each element.

for(var i=1; i<=5; i++)


{
document.write("<p>The number is " + i + "</p>");
}

for...in loop:
o for...in loop is used to iterate over the properties of an object in JavaScript.
o The for...in loop allows you to access each property of an object. It iterates over the
enumerable properties of an object, and for each property, the loop assigns the property
name to the specified variable.
// An object with some properties
var person = {"name": "Clark", "surname": "Kent", "age": "36"};

// Loop through all the properties in the object


for(var prop in person) {
document.write("<p>" + prop + " = " + person[prop] + "</p>");
}

Difference :
a. First, the for...in can loop through both Arrays and Objects while the for...of can only loop
through Arrays, Map, Set, arguments object.
b. The second and the biggest difference between both of these statements are, by default,
the for...in iterates over property names and the for...of iterates over property values.

18. Explain getter and setter properties in JavaScript


Property getters and setters
1. The accessor properties. They are essentially functions that work on getting and setting a value.
2. Accessor properNes are represented by ―geLer‖ and ―seLer‖methods. In an object literal they are
denoted by get and set.
get –It is used to define a getter method to get the property value
set –It is used to define a setter method to set / change the property value
let obj =
{
get propName() {
// getter, the code executed on getting obj.propName
},
set propName(value) {
// setter, the code executed on setting obj.propName = value
}
};
3. An object property is a name, a value and a set of attributes. The
value may be replaced by one or two methods, known as setter and a getter.

Example of getter
const student
{
firstname: ‗abc‘,
get getname()
{
return this.firstname;
}
};
Example of setter
const student
{
firstname: ‗abc‘,
set changename(nm)
{
this.firstname=nm;
}
};
19. Write an HTML Script that displays the following webpage output:

The user enters two numbers in respective text boxes. Write a JavaScript such that when user clicks
"add", a message box displays sum of two entered numbers, if the user clicks on "sub”. Message box
displays subtraction of two numbers and on clicking “mul” the message box displays multiplication of
two numbers.
<html>
<head>
<script>
function add()
{
var num1, num2, r;
//to accept 2 values and stored in variable num1 and num2
num1 = parseInt(document.getElementById("firstnumber").value);
num2 = parseInt(document.getElementById("secondnumber").value);
r= num1 + num2;
alert(r);
}
function sub()
{
var num1, num2, r;
num1 = parseInt(document.getElementById("firstnumber").value);
num2 = parseInt(document.getElementById("secondnumber").value);
r = num1 - num2;
alert(r);
}
function mul()
{
var num1, num2, r;
num1 = parseInt(document.getElementById("firstnumber").value);
num2 = parseInt(document.getElementById("secondnumber").value);
r = num1 * num2;
alert(r);
}
</script>
</head>
<body>
<fieldset>
<p>First Number: <input id="firstnumber"></p>
<p>Second Number: <input id="secondnumber"></p>
//onClick() event to perform addition, subtraction and multiplication
<button onclick="add()">Add</button>
<button onclick="sub()">Sub</button>
<button onclick="mul()">Mul</button>
</fieldset>
</body>
</html>

20. Write a JavaScript program to check whether a number is positive, negative or zero using switch
case.
<html>
<body>
<script type="text/javascript">
var num=prompt("Enter number");
switch (Math.sign(num))
{
case 1:
alert("The number is Positive");
break;
case -1:
alert("The number is Negative");
break;
default:
alert("The number is Zero");
}
</script>
</body>
</html>

21. Write HTML script that displays textboxes for accepting username and password. Write proper
JavaScript such that when the user clicks on submit button
i) All textboxes must get disabled and change the color to ‘RED; and with respective labels
ii) Prompt the error message if the password is less than six characters
<html>
<head>
<script>
function disableTxt()
{
document.getElementById("un").disabled = true;
document.getElementById('un').style.color = "red";
document.getElementById('aaa').style.color = "red";
document.getElementById("pass").disabled = true;
document.getElementById('pass').style.color = "red";
document.getElementById('bbb').style.color = "red";
}
function validateform()
{
var username=document.myform.username.value;
var password=document.myform.password.value;
if (username==null || username=="")
{
alert("Name can't be blank");
return false;
}
else if(password.length<6)
{
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
</head>
<body>
<form name="myform" method="post" action="" onsubmit="return
validateform()" >
<label id = "aaa">Username:</label>
<input type="text" id="un" name="username"/>
<label id = "bbb">Password:</label>
<input type="password" id="pass" name="password"/>
<br>
<br>
<button onclick="disableTxt()">Disable Text field</button>
</form>
</body>
</html>

You might also like