0% found this document useful (0 votes)
39 views

Chapter 1

The document discusses the basics of JavaScript programming including: 1. Features of JavaScript such as giving users control over browsers, client-side validation, and simple computations. 2. Key concepts like objects, properties, methods, and main events. Objects have properties that define their characteristics. 3. Variables and how they store and can change data values using the var keyword. It also covers JavaScript operators, functions, accessing properties, and conditional statements like if, else if, and else.

Uploaded by

sakshi lad
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Chapter 1

The document discusses the basics of JavaScript programming including: 1. Features of JavaScript such as giving users control over browsers, client-side validation, and simple computations. 2. Key concepts like objects, properties, methods, and main events. Objects have properties that define their characteristics. 3. Variables and how they store and can change data values using the var keyword. It also covers JavaScript operators, functions, accessing properties, and conditional statements like if, else if, and else.

Uploaded by

sakshi lad
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

1.

Basics of JavaScript Programming

1. Explain features of JavaScript.


Ans:

1) Giving the user more control over the browser: Example: Here you can
change the background color of this page as well as the text on the browser's
status bar.
2) Client – Side Technology: JavaScript is a client-side technology. It is mainly
used for giving client-side validation. It is an object-based scripting language.
3) Performing simple computations on the client side: Using a JavaScript
calculator, we perform simple calculations on the client side. Example. This is
a JavaScript calculator: type an arithmetic expression, and JavaScript will
compute its value.
4) Validating The User’s Input: In the JavaScript calculator, try to type some
letters instead of numeric input, you will get an error: Invalid input character.
Note that, JavaScript helps the browser perform output validation without
wasting the user’s time by the web server access.

2. Define Object, Property, method, Dot syntax, main event.


Ans:
In JavaScript, an object is a standalone entity, with properties and type. Compare it
with a cup, for example. A cup is an object, with properties. A cup has a color, a design,
weight, a material it is made of, etc. The same way, JavaScript objects can have
properties, which define their characteristics.
An object is a collection of properties, and a property is an association between a
name (or key) and a value. A property's value can be a function, in which case the
property is known as a method. Properties are the values associated with a JavaScript
object.
The syntax for accessing the property of an object is:
objectName.property // person.age

Example: person.firstname + " is " + person.age + " years old.";


An object property name can be any valid JavaScript string, or anything that can be
converted to a string, including the empty string.
Examples are as follows:
var myObj = new Object(),
str = 'myString',
rand = Math.random(),
obj = new Object();
myObj.type = 'Dot syntax';
myObj['date created'] = 'String with space';
myObj[str] = 'String value';
myObj[rand] = 'Random Number';
myObj[obj] = 'Object';
myObj[''] = 'Even an empty string';

console.log(myObj);

3. Define values and variables


Ans:

Variable means anything that can vary. JavaScript includes variables which hold the
data value and it can be changed anytime.

JavaScript uses reserved keyword var to declare a variable. A variable must have a
unique name. You can assign a value to a variable using equal to (=) operator when
you declare it or before using it.

Syntax:

var <variable-name>;

var <variable-name> = <value>;

Example: Variable Declaration & Initialization

var one = 1; // variable stores numeric value

var two = 'two'; // variable stores string value

var three; // declared a variable without assigning a value


4. Explain JavaScript Operators
Ans: JavaScript supports the following types of operators.

1) Arithmetic Operators

Arithmetic operators perform arithmetic on numbers (literals or variables).

Operator Description

+ Addition

- Subtraction

* Multiplication

** Exponentiation

/ Division

% Modulus (Remainder)

++ Increment

-- Decrement

2) Comparison Operators
Assume variable A holds 10 and variable B holds 20, then −
Sr.No. Operator & Description
1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the
condition becomes true.
Ex: (A == B) is not true.
2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are not
equal, then the condition becomes true.
Ex: (A != B) is true.
3 > (Greater than)
Checks if the value of the left operand is greater than the value of the right
operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.
4 < (Less than)
Checks if the value of the left operand is less than the value of the right
operand, if yes, then the condition becomes true.
Ex: (A < B) is true.
5 >= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to the value
of the right operand, if yes, then the condition becomes true.
Ex: (A >= B) is not true.
6 <= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of
the right operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.

3) Logical (or Relational) Operators


Assume variable A holds 10 and variable B holds 20, then −
Sr.No. Operator & Description
1 && (Logical AND)
If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the
Logical NOT operator will make it false.
Ex: ! (A && B) is false.

4) Assignment Operators
JavaScript supports the following assignment operators −
Sr.No. Operator & Description
1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
2 += (Add and Assignment)
It adds the right operand to the left operand and assigns the result to the
left operand.
Ex: C += A is equivalent to C = C + A
3 −= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the result
to the left operand.
Ex: C -= A is equivalent to C = C - A
4 *= (Multiply and Assignment)
It multiplies the right operand with the left operand and assigns the result
to the left operand.
Ex: C *= A is equivalent to C = C * A
5 /= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to
the left operand.
Ex: C /= A is equivalent to C = C / A
6 %= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the left
operand.
Ex: C %= A is equivalent to C = C % A

5) Conditional (or ternary) Operators


The conditional operator first evaluates an expression for a true or false value and
then executes one of the two given statements depending upon the result of the
evaluation.
Sr.No. Operator and Description
1 ? : (Conditional )
If Condition is true? Then value X : Otherwise value Y

5. What is Function Definition expression in JavaScript?

Ans:

JavaScript functions are defined with the function keyword. You can use a function
declaration or a function expression.

Function Declaration syntax:


function functionName(parameters)
{
// code to be executed
}
Example
function myFunction(a, b)
{
return a * b;
}
6. How to access JavaScript Properties?

Ans:

A property access expression evaluates to the value of an object property or an array


element. The syntax for accessing the property of an object is:

objectName.property // person.age

or

objectName["property"] // person["age"]

or

objectName[expression] // x = "age"; person[x]

7. Describe Conditional statements in JavaScript.


Ans: In JavaScript we have the following conditional statements:

if Statement
if statement is used to specify a block of JavaScript code to be executed if a condition
is true.

Syntax
if (condition)
{
// block of code to be executed if the condition is true
}

Example
Make a "Good day" greeting if the hour is less than 18:00:
if (hour < 18)
{
greeting = "Good day";
}

The result of greeting will be:


Good day

else Statement
else statement is used to specify a block of code to be executed if the condition is
false.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
} else
{
// block of code to be executed if the condition is false
}

Example
If the hour is less than 18, create a "Good day" greeting, otherwise "Good
evening":
if (hour < 18)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}

The result of greeting will be:


Good day

else if Statement
else if statement is used to specify a new condition if the first condition is false.
Syntax
if (condition1)
{
// block of code to be executed if condition1 is true
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is
true
}
else
{
// block of code to be executed if the condition1 is false and condition2 is
false
}

Example
If time is less than 10:00, create a "Good morning" greeting, if not, but time is
less than 20:00, create a "Good day" greeting, otherwise a "Good evening":
if (time < 10)
{
greeting = "Good morning";
}
else if (time < 20)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}

The result of greeting will be:


Good day

Switch Statement
 The switch statement is used to perform different actions based on different
conditions.
 Use the switch statement to select one of many code blocks to be executed.

Syntax
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Example
The getDay() method returns the weekday as a number between 0 and 6.
(Sunday=0, Monday=1, Tuesday=2 ..)
This example uses the weekday number to calculate the weekday name:
switch (new Date().getDay())
{
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
The result of day will be:
Monday

8. Describe different loop statements in JavaScript.


Ans: JavaScript supports different kinds of loops:

 for - loops through a block of code a number of times


 for/in - loops through the properties of an object
 while - loops through a block of code while a specified condition is true
 do/while - also loops through a block of code while a specified condition is
true

for loop
The 'for' loop includes the following three important parts −
 The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
 The test statement which will test if a given condition is true or not. If the
condition is true, then the code given inside the loop will be executed,
otherwise the control will come out of the loop.
 The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Flow Chart
The flow chart of a for loop in JavaScript would be as follows −

Syntax
for (initialization; test condition; iteration statement)
{
Statement(s) to be executed if test condition is true
}

Example
<html>
<body>
<script type = "text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");

for(count = 0; count < 10; count++) {


document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
</body>
</html>
Output:
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!

while Loop
The most basic loop in JavaScript is the while loop which would be discussed in this
chapter. The purpose of a while loop is to execute a statement or code block
repeatedly as long as an expression is true. Once the expression becomes false, the
loop terminates.

Flow Chart
The flow chart of while loop looks as follows −
Syntax
while (expression)
{
Statement(s) to be executed if expression is true
}

Example

<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;
document.write("Starting Loop ");
while (count < 10) {
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");
//-->
</script>
</body>
</html>

Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
for...in loop

It is used to loop through an object's properties.

Syntax
for (variablename in object)
{
statement or block to execute
}

Example
<script type = "text/javaScript">
// JavaScript program to illustrate for..in loop

// creating an Object
var languages = { first : "C", second : "Java",
third : "Python", fourth : "PHP",
fifth : "JavaScript" };

// iterate through every property of the


// object languages and print all of them
// using for..in loops
for (itr in languages)
{
document.write(languages[itr] + "<br >");
}

< /script>

Output:
C
Java
Python
PHP

do while loop
do while loop is similar to while loop with only difference that it checks for condition
after executing the statements, and therefore is an example of Exit Control Loop.

Syntax:
do
{
statements..
}
while (condition);
Flowchart:

1. do while loop starts with the execution of the statement(s). There is no


checking of any condition for the first time.
2. After the execution of the statements, and update of the variable value, the
condition is checked for true or false value. If it is evaluated to true, next
iteration of loop starts.
3. When the condition becomes false, the loop terminates which marks the end
of its life cycle.
4. It is important to note that the do-while loop will execute its statements
atleast once before any condition is checked, and therefore is an example
of exit control loop.

Example:
<script type = "text/javaScript">
// JavaScript program to illustrate do-while loop

var x = 21;

do
{
// The line while be printer even
// if the condition is false
document.write("Value of x:" + x + "<br />");

x++;
} while (x < 20);

< /script>
Output:
Value of x: 21

Continue Statement

The continue statement terminates execution of the statements in the current iteration
of the current or labeled loop, and continues execution of the loop with the next
iteration.

In this example we use a for loop together with the continue statement.

Loop through a block of code, but skip the value of "3":

var text = ""


var i;
for (i = 0; i < 5; i++)
{
if (i === 3)
{
continue;
}
text += "The number is " + i + "<br>";
}

text += "The number is " + i + "<br>";


}

9. What are javaScript Accessors(setters and getters)


Ans:
 Getters and setters exist in most object-oriented programming languages,
including JavaScript.
 They are code constructs that help developers access the properties of objects
in a secure way.
 With getters, you can access (“get”) the values of properties from external code,
while setters let you change (“set”) their values.
 It gives simpler syntax.
 It allows equal syntax for properties and methods.
 It can secure better data quality
 A JavaScript object can have multiple properties and methods that store static
data and dynamic functionality. Properties are static key-value pairs, while
methods are functions specific to the object.
 For example, Car.color could be a property, while Car.drive() could be a
method of the Carobject. With a getter, you can access the color property of
the Car object and with a setter, you can modify its value (for instance,
from blue to black).
 To get the properties of the Car object, you need to call the getter methods.
Example:
var obj = {
Ex: 'this is the value of foo',
getEx: function()
{
return this.Ex;
},
setEx: function(val)
{
this.Ex = val;
}
}

console.log(obj.getEx());
// "this is the value of foo"

obj.setEx('hello');

console.log(obj.getEx());
// "hello"

You might also like