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

FOP- Java Script_Unit 2 (1)

The document outlines a Faculty Orientation Program on JavaScript, focusing on data types, variables, operators, and core statements. It details JavaScript's primitive types including numbers, strings, booleans, undefined, and null, as well as composite types like objects. Additionally, it covers type conversion, operators, and provides examples of syntax and usage in JavaScript.

Uploaded by

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

FOP- Java Script_Unit 2 (1)

The document outlines a Faculty Orientation Program on JavaScript, focusing on data types, variables, operators, and core statements. It details JavaScript's primitive types including numbers, strings, booleans, undefined, and null, as well as composite types like objects. Additionally, it covers type conversion, operators, and provides examples of syntax and usage in JavaScript.

Uploaded by

meghshamjade50
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Faculty Orientation Program

Java Script
By:
Dr. Khyati R Nirmal
Associate Professor
Department of Computer Engineering
SNJB’s LS KBJ CoE, Chandwad
Unit 2
Data Types and Variables
Syllabus
• JavaScript’s Primitive Types- Numbers, Hexadecimal Literals, Octal
Literals, Special Values, Data Representation Issues, Data
Representation Issues, Strings, Undefined and Null; Composite
Types-Objects, The typeof Operator, Type Conversion, Variables.
• Operators, Expressions, and Statements- Statement Basics,
Whitespace, Termination: Semicolons and Returns, Blocks.
Operators- Assignment Operator, Arithmetic Operators, Bitwise
Operators, Bitwise Shift Operators, Increment/Decrement, Logical
Operators, void Operator, Object Operators
• Core JavaScript Statements- if Statements, switch, while Loops, do-
while Loops, for Loops, for Loops, Object-Related Statements,
Object Loops Using for… in
JavaScript’s Primitive Types
JavaScript supports five primitive data types:

• Number
• String
• Boolean
• Undefined
• null
JavaScript’s Primitive Types
• These types are referred to as primitive types because
they are the basic building blocks from which more
complex types can be built.
• Of the five, only number, string, and Boolean are real
data types in the sense of actually storing data.
• Undefined and null are types that arise under special
circumstances.
JavaScript’s Primitive Types: Numbers
• JavaScript includes both integer and floating-point values.
• All numbers are represented in IEEE 754-1985 double-precision
floating-point format.
• This representation permits exact representation of integers in
the range –253 to 253 and floating-point magnitudes as large as
±1.7976 x 10308 and as small as ±2.2250 x 10-308.
• Numeric literals in JavaScript can be written in a wide variety of
ways, including scientific notation. When using scientific
notation, the exponent is specified with the letter e (which is
not case-sensitive).
JavaScript’s Primitive Types: Numbers
• Formally (according to the ECMA-262 grammar), decimal literals
have one of the following three forms (parentheses indicate
optional components):
• DecimalDigits.(DecimalDigits)(Exponent)

• DecimalDigits(Exponent)
• DecimalDigits(Exponent)
JavaScript’s Primitive Types: Numbers
• In plain English, this means that all of the following are valid ways
to specify numbers:
• 10
• 177.5
• -2.71
• .333333e77
• -1.7E12
• 3.E-5
• 128e+100
• Note that you should not include leading zeros in your integers. The
reason is that JavaScript also allows numeric literals to be specified
in bases other than ten (decimal).
JavaScript’s Primitive Types: Numbers
• Hexadecimal
• Programmers often find it convenient to write numbers in hexadecimal (base-
16) notation, particularly when performing bitwise operations.
• JavaScript’s hex syntax should be familiar to readers with previous
programming experience: a leading zero, followed by the letter x (not case-
sensitive), followed by one or more hexadecimal digits.
• Hexadecimal digits are the numbers zero through nine and letters A through F
(not case-sensitive), which represent the values zero through fifteen.
• Eg.
0x0
0XF8f00
0x1a3C5e7
JavaScript’s Primitive Types: Numbers
• Octal Literals
• Octal literals begin with a leading zero, and octal digits are the
numbers zero through seven.
• The following are all valid octal literals:

00
0777
24513600
JavaScript’s Primitive Types: Special Values
• Numeric data can take on several special values.
• When a numeric expression or variable exceeds the maximum
representable positive value, it takes on the special value Infinity.
• Likewise, when an expression or variable becomes less than the
lowest representable negative value, it takes on the value –
Infinity.
• For example, Infinity minus 100 is still Infinity; it does not become
a representable number. All Infinity values compare equal to each
other.
• Similarly, all –Infinity values compare equal.
JavaScript’s Primitive Types: Special Values
• var x = 1.7976931348623157e308; // set x to max value
• x = x + 1e292; // increment x
• alert(x); // show resulting value to user
JavaScript’s Primitive Types: Special Values
• The other important special value is NaN, which means “not a
number.”
• Numeric data takes on this value when it is the result of an
undefined operation.
• Common examples of operations that result in NaN are dividing
zero by zero, taking the sine of Infinity, and attempting to add
Infinity to –Infinity.
• The NaN value is also sticky, but unlike the infinite values it never
compares equal to anything. Because of this, you must use the
isNaN() method or compare the value to itself to determine if a
value is NaN.
• The isNaN() method returns a Boolean indicating whether the
value is NaN
JavaScript’s Primitive Types: Special Values
var x = 0 / 0; // assign NaN to x
if (x != x) // check via self-equality
{
// do something
}
if (isNaN(x)) // check via explicit call
{
// do something
}
Data Representation Issues
• If you’re working with integers, keep in mind that only
integers in the range –253 to 253 can be represented
exactly.
• As soon as your value (or an intermediate value in an
expression) falls outside of this range, its numeric
value becomes an inexact approximation. This can
lead to some surprising behavior
Data Representation Issues
var x = 9007199254740992; // 2^53
if (x == x + 1)
alert("True! Large integers are only
approximations!");
Data Representation Issues
var x = .3333;
x = x * 5;
alert(x);
String
• A string is simply text. In JavaScript, a string is a sequence
of characters surrounded by single or double quotes.
• For example,
var string1 = "This is a string";
var string2 = 'So am I';
• Unlike many other languages, JavaScript draws no
distinction between single characters and strings of
characters
String
• you can extract characters from strings using the charAt()
method.
• var myName = "Thomas";
• var thirdLetter = myName.charAt(2);

• To determine the length of a string using the length()


method:
var strlen = myName.length();
Special Characters and Strings
• Any alphabetic, numeric, or punctuation characters can be placed in a string, but
there are some natural limitations.
• For instance, the newline character is the character that causes output to move
down one line on your display. Typing this directly into a string using your ENTER key
would result in a string literal like this:
var myString = "This is the first line.
This is the second line."
• which is a syntax error, since the two separate lines appear as
two different statements to JavaScript, particularly when semicolons
are omitted.
var myString = "This is the first line.\nThis is the second
line."
Special Characters and Strings
Quotes and Strings
• When it comes to special characters, quotes deserve special
notice
• The following are examples of validly escaped quotes inside of
strings:
var string1 = "These quotes \"are\" valid!";
var string2 = 'Isn\'t JavaScript great?';
• The following strings are not valid:
var invalid1 = "This will not work!';
var invalid2 = 'Neither 'will this';
Boolean
• Booleans derive their name from George Boole, the
19th century logician who developed the true/false
system of logic upon which digital circuits would later be
based.
• With this in mind, it should come as no surprise that
Booleans take on one of two values: true or false.
• Comparison expressions such as x << y evaluate to a
Boolean value depending upon whether the comparison
is true or false.
• So the condition of a control structure such as if/else is
evaluated to a Boolean to determine what code to
execute
Boolean
var doIncrement = true;
if (doIncrement) // if doIncrement is true then
increment x
{
x = x + 1;
}
Boolean
• Booleans are commonly included as object properties
indicating an on/off state.
• For example, the cookieEnabled property of Internet
Explorer’s Navigator object (navigator.cookieEnabled) is a
Boolean that has value true when the user has persistent
cookies enabled and false otherwise.
• An example of accessing the property is
Boolean
if (navigator.cookieEnabled)
{
alert("Persistent cookies are enabled");
}
else
{
alert("Persistent cookies are not enabled");
}
Undefined and Null
• The undefined type is used for variables or object properties
that either do not exist or have not been assigned a value.
• The only value an undefined type can have is undefined.
• For example, declaring a variable without assigning it a
value,
var x;
gives x the undefined type and value
Undefined demo
function Sum(val1, val2) function Sum(val1, val2)
{ {
var result = val1 + val2;
var result = val1 + val2;
return result;
}
var result = Sum(5, 5); }
alert(result);// undefined var result = Sum(5, 5);
alert(result);// undefined
Undefined and Null
• The null value indicates an empty value; it is essentially a
placeholder that represents “nothing.”
• // demonstration of arithmetic operations using undefined and
null
undefined + 1; // NaN
null + 1; // 1
Composite Types
• An object is a composite type that can contain
primitive and composite types.
• The main distinction between primitive types and
composite types is that primitive types contain only
data in the form of a fixed set of values (e.g.,
numbers); objects can contain primitive data as well
as code (methods) and other objects.
Composite Types: Object
• An object is a collection that can contain primitive or
composite data, including functions and other objects.
• The data members of an object are called properties, and
member functions are known as methods.
• Some readers may prefer to think of properties as the
characteristics of the object and the things the object does
as its methods, but the meaning is the same.
Composite Types: Object
• Properties are accessed by placing a period and the property name immediately
following the object name.
• For instance, the version information of the browser is stored in the appVersion
property of the Navigator object.
• One way of accessing this property is
• alert("Your browser version is: " + navigator.appVersion);
Composite Types: Object
• Methods of objects are accessed in the same way but with trailing parentheses
immediately following the method name.
• These parentheses indicate to the interpreter that the property is a method
that you want to invoke.
• The Window object has a method named close, which closes the current browser
window:
window.close();
• If the method takes arguments, the arguments are included in the parentheses.
We’ve seen a common example of this usage, the write method of the Document
object:
document.write("This text is written to the document.");
Object: Built-in Objects
• JavaScript provides many powerful objects for developers to use.
• These include browser-specific objects such as Window, which contains
information and methods related to the browser window.
• For example, as we mentioned previously, window.open() could be used to
create a window.
• Objects such as Document contain more objects that map to the various
features and tags of the document in the window. For instance, to see the
last modification date of the document, we could reference the
document.lastModified property.
• Also available are numerous objects defined in the JavaScript language
that simplify common tasks. Examples of such objects are Date, Math, and
RegExp.
• Finally, each data type in JavaScript has a corresponding object. So there are
String, Number, Boolean, Array
Creating Objects
• User-defined objects are created using the new keyword
followed by the name of the object and parentheses.
• The reason for the parentheses is that objects are created
using constructors, methods that create a fresh instance of
an object for you to use.
• The parentheses tell the interpreter that you want to
invoke the constructor method for the given object
var myString = new String();
Creating Objects

• One nice feature of objects in JavaScript is that you can


add properties to them dynamically.
• For example, to create your own object and populate it
with two text fields, you might do the following:
var myLocation = new Object();
myLocation.city = “Nashik";
myLocation.state = “Maharashtra";
The typeof Operator
• Values Returned by the typeof Operator
Type Conversion
• Automatic type conversion is one of the most powerful
features of JavaScript, as well as the most dangerous for the
sloppy programmer.
• Type conversion is the act of converting data of one type into
a different type.
• It occurs automatically in JavaScript when you change the
type of data stored in a variable:
var x = "3.14";
x = 3.14;
Type Conversion
• The type of x changes from string to number.
• Besides the automatic conversion inherent in JavaScript, it is
also possible for programmers to force the conversion using
methods like toString() or parseInt().
• Consider this code:
var x = "10" - 2;
• it converts the string "10" into the number 10, performs the
subtraction, and stores the number 8 in x.
Type Conversion
• var x = 21.84e22; // a number
• document.write(x); // x is automatically
converted to a string here
Conversion Rules for Primitive Types
• Result of Conversion to a Boolean
Conversion Rules for Primitive Types
• Result of Converting to a Number
Conversion Rules for Primitive Types
• Result of Converting to a String
Syllabus
• JavaScript’s Primitive Types- Numbers, Hexadecimal Literals, Octal
Literals, Special Values, Data Representation Issues, Data
Representation Issues, Strings, Undefined and Null; Composite
Types-Objects, The typeof Operator, Type Conversion, Variables.
• Operators, Expressions, and Statements- Statement Basics,
Whitespace, Termination: Semicolons and Returns, Blocks.
Operators- Assignment Operator, Arithmetic Operators, Bitwise
Operators, Bitwise Shift Operators, Increment/Decrement, Logical
Operators, void Operator, Object Operators
• Core JavaScript Statements- if Statements, switch, while Loops, do-
while Loops, for Loops, for Loops, Object-Related Statements,
Object Loops Using for… in
Operators
• JavaScript supports a variety of operators. Some of them, like those for arithmetic and
comparison, are easy for even those new to programming to understand.
• Others, like the bitwise AND (&), increment (++), and some conditional (?:) operators

Operator Meaning Example Result


+ Addition var x = 5, y = 7; Variable sum contains 12.
var sum; sum = x+y;
- Subtraction var x = 5, y = 7; Variable diff1 contains –2
var diff1, diff2; while
diff1 = x–y; diff2 = y–x; variable diff2 contains 2.
* Multiplication var x = 8, y = 4; Variable product contains
var product; product = 32
x*y;
Operators

Operat Meaning Example Result


or
/ Division var x = 36, y = 9, z = 5; Variable div1 contains
var div1, div2; 4 while
div1 = x / y; div2 = x / z; variable div2 contains
7.2.
% Modulus var x = 24, y = 5, z = 6; Variable mod1
var mod1, mod2; mod1 = contains 4 while
x%y; variable mod2
mod2 = x%z; contains 0.
String Concatenation Using +
the + operator performs string concatenation
document.write("JavaScript is " +great.");

Negation
use of the – symbol besides subtraction is to negate a
value.
var x = -5;
x = -x;
// x now equals 5
Bitwise Operators
Comparison Operators
Bitwise Shift Operators
Increment and Decrement
• The ++ operator is used to increment
• For example, with
var x=3;
x++;
• the value of x is set to 4.
• Of course you could also write the increment portion of the
previous example as
x=x+1;
• Similar to the ++ operator is the –– operator, used to decrement
(subtract one from) its operand. So,
var x=3;
x--;
• leaves a value of 2 in the variable x
Post- and Pre-Increment/Decrement
• A subtle nuance of the increment (++) and decrement (– –) operators is the
position of the operator in relation to the operand.
• When the increment operator appears on the left of the operand, it is termed
a pre-increment
• while if it appears on the right, it is a post-increment.
Comparison Operators
Comparison Operators Demo
var x = 1;
var y = 5;
if (x = y)
alert("Values are the same");
else
alert("Values are different");
Comparison Operators Demo
alert(5 == "5");
Comparison Operators Demo
alert(5 === "5");
Comparing Strings
• While it is clear what comparison operators mean for numbers,
what about strings?
• For example, is the following expression true?
"thomas" >> "fritz“

• When you compare strings, JavaScript evaluates the comparison


based on strings’ lexicographic order.
• Lexicographic order is essentially alphabetic order, with a few
extra rules thrown in to deal
• with upper- and lower-case characters as well as to accommodate
strings of different lengths.
Comparing Strings
• The following general rules apply:
• Lowercase characters are less than uppercase characters.
• Shorter strings are less than longer strings.
• Letters occurring earlier in the alphabet are less than those
occurring later.
• Characters with lower ASCII or Unicode values are less than those
with larger values.
Logical Operators
• The logical operators && (AND), || (OR), and ! (NOT) are
useful to combine such values together in order to
implement more complicated logic.
?: Operator
• to create a quick conditional branch.
• The basic syntax for this operator is
• (expression) ? if-true-statement : if-false-statement;
• where expression is any expression that will evaluate eventually to true or false.
• If expression evaluates true, if-true-statement is evaluated. Otherwise, iffalse-
statement is executed. In this example,
• (x >> 5) ? alert("x is greater than 5") : alert("x is less than 5");
• less compact if style syntax, as shown here:
if (x >> 5)
alert("x is greater than 5");
else
alert("x is less than 5");
Comma Operator
• The comma operator (,) allows multiple expressions to be strung
together and treated as one expression. Expressions strung
together with commas evaluate
• to the value of the right-most expression. For example, in this
assignment, the final assignment will return the value 56 as a
side-effect; thus, the variable a is
• set to this value:
• var a,b,c,d;
• a = (b=5, c=7, d=56);
• document.write('a = '+a+' b = '+b+' c = '+c+' d = ' + d);
typeof
• The typeof operator returns a string indicating the data type
of its operand. The script fragment here shows its basic use:
• a = 3;
• name = "Howard";
• alert(typeof a); // displays number
• alert(typeof name); // displays string
typeof
Object Operators

1. index operator
A more common use of square brackets is the array index operator ([ ]) used to access the elements of arrays.
For example, here we define an array called
myArray:
var myArray = [2, 4, 8, 10];
To display the individual elements of the array starting from the first position (0),
we would use a series of statements like these:
alert(myArray[0]);
alert(myArray[1]);
alert(myArray[2]);
alert(myArray[3]);
New

The new operator is used to create objects. The following script creates a new instance of the
Date object and places it in the variable today.
var today = new Date();
alert(today);
The result is shown here:
Delete

In JavaScript, the delete operator is used to remove a property from an object and to remove
an element from an array.

For Example:
var myArray = ['1', '3', '78', '1767'];
document.write("myArray before delete = " + myArray);
delete myArray[2]; document.write("myArray after delete = " + myArray);
Notice that the third item, 78, has been removed from the array:
Operator Precedence and Associativity
Syllabus
• JavaScript’s Primitive Types- Numbers, Hexadecimal Literals, Octal
Literals, Special Values, Data Representation Issues, Data
Representation Issues, Strings, Undefined and Null; Composite
Types-Objects, The typeof Operator, Type Conversion, Variables.
• Operators, Expressions, and Statements- Statement Basics,
Whitespace, Termination: Semicolons and Returns, Blocks.
Operators- Assignment Operator, Arithmetic Operators, Bitwise
Operators, Bitwise Shift Operators, Increment/Decrement, Logical
Operators, void Operator, Object Operators
• Core JavaScript Statements- if Statements, switch, while Loops, do-
while Loops, for Loops, for Loops, Object-Related Statements,
Object Loops Using for… in

You might also like