0% found this document useful (0 votes)
8K views

ch4 JS

The document discusses JavaScript fundamentals including variables, data types, strings, and numbers. It covers declaring variables, assigning values, and basic syntax. Key data types include numbers, strings, Booleans, and objects.

Uploaded by

eliasferhan1992
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8K views

ch4 JS

The document discusses JavaScript fundamentals including variables, data types, strings, and numbers. It covers declaring variables, assigning values, and basic syntax. Key data types include numbers, strings, Booleans, and objects.

Uploaded by

eliasferhan1992
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 120

Chapter Four

Java Script
Basic content of the chapter
• JavaScript Fundamentals
• Statement
• Comment
• Variable
• Data Type
What is JavaScript ?
• JavaScript is able to:
• Add new HTML to the page, change the existing content, modify
styles.
• React to user actions, run on mouse clicks, pointer movements, key
presses.
• Get and set cookies, ask questions to the visitor, show messages.
• Remember the data on the client-side (“local storage”).
There are at least three great things about JavaScript:
Full integration with HTML/CSS.
Simple things are done simply.
Supported by all major browsers and enabled by default.
JavaScript Fundamentals

• JavaScript programs can be inserted almost anywhere into an HTML


document using the <script> tag.
• The type and language attributes are not required.
• A script in an external file can be inserted with
<script src="path/to/script.js"></script>
• A single <script> tag can’t have both the src attribute and code inside.
<script src="file.js">
alert(1); // the content is ignored, because src is set
</script>
Code structure
Statements
• Statements are syntax constructs and commands that perform actions.
• We’ve already seen a statement, alert('Hello, world!'), which shows the
message “Hello, world!”.
• We can have as many statements in our code as we want. Statements
can be separated with a semicolon.
• For example, here we split “Hello World” into two alerts:
alert('Hello'); alert('World');
• Usually, statements are written on separate lines to make the code
more readable:
alert('Hello');
alert('World');
• A semicolon may be omitted in most cases when a line break exists.
• This would also work:
alert('Hello')
alert('World')
• Here, JavaScript interprets the line break as an “implicit” semicolon.
This is called an automatic semicolon insertion.
• In most cases, a newline implies a semicolon. But “in most cases”
does not mean “always”!
alert(3 +
1
+ 2);
We recommend putting semicolons between statements even if they
are separated by newlines.
Comments
• It becomes necessary to add comments which describe what the code does
and why.
• Comments can be put into any place of a script.
• They don’t affect its execution because the engine simply ignores them.
• One-line comments start with two forward slash characters //.
• The rest of the line is a comment. It may occupy a full line of its own or
follow a statement.
• Like here:
// This comment occupies a line of its own
• alert('Hello');
• alert('World'); // This comment follows the statement
 Multiline comments start with a forward slash and an
asterisk /* and end with an asterisk and a forward slash
*/.
 Like this:
 /* An example with two messages.
 This is a multiline comment.
 */
 alert('Hello');
 alert('World’);
 There may not be /*...*/ inside another /*...*/.
Variables
 Most of the time, a JavaScript application needs to work with
information. Here are two examples:
 An online shop – the information might include goods being
sold and a shopping cart.
 A chat application – the information might include users,
messages, and much more.
 Variables are used to store this information.
 A variable is a “named storage” for data. We can use variables to store
goodies, visitors, and other data.
 To create a variable in JavaScript, use the let keyword.
 The statement below creates (in other words: declares) a variable with
the name “message”:
let message;
var message;
const message;
 Now, we can put some data into it by using the assignment operator =:
let message;
message = 'Hello'; // store the string 'Hello' in the variable named message
 The string is now saved into the memory area associated with the
variable.
 We can access it using the variable name:
let message;
message = 'Hello!';
alert(message); // shows the variable content
 To be concise, we can combine the variable declaration and
assignment into a single line:
let message = 'Hello!'; // define the variable and assign the value
alert(message); // Hello!
 We can also declare multiple variables in one line:
let user = 'John', age = 25, message = 'Hello’;
 In older scripts, you may also find another keyword: var instead of let:
var message = 'Hello';
 The var keyword is almost the same as let. It also declares a variable,
but in a slightly different, “old-school” way.
 A variable should be declared only once.
 A repeated declaration of the same variable is an error:
let message = "This";
// repeated 'let' leads to an error
let message = "That"; // SyntaxError: 'message' has already been declared
 So, we should declare a variable once and then refer to it without let.
Variable naming
 There are two limitations on variable names in JavaScript:
 The name must contain only letters, digits, or the symbols $ and _.
 The first character must not be a digit.
 Examples of valid names:
let userName;
let test123;
 When the name contains multiple words, camelCase is commonly used.
That is: words go one after another, each word except first starting with a
capital letter: myVeryLongName.
 What’s interesting – the dollar sign '$' and the underscore '_' can also be
used in names.
• Variables named apple and APPLE are two different variables.
• There is a list of reserved words, which cannot be used as variable
names because they are used by the language itself.
For example: let, class, return, and function are reserved.
• To declare a constant (unchanging) variable, use const instead of let:
const myBirthday = '18.04.1982';
• Variables declared using const are called “constants”. They cannot be
reassigned. An attempt to do so would cause an error:
const myBirthday = '18.04.1982’;
myBirthday = '01.01.2001'; // error, can't reassign the constant!
Exercise
1. Declare two variables: admin and name.
2. Assign the value "John" to name.
3. Copy the value from name to admin.
4. Show the value of admin using alert (must output “John”).
• Answer:
let admin, name; // can declare two variables at once
name = "John";
admin = name;
alert( admin ); // "John"
Data types
 A value in JavaScript is always of a certain type. For example, a string
or a number.
 We can put any type in a variable. For example, a variable can at one
moment be a string and then store a number:
 let message = "hello";
 message = 123456;
 Programming languages that allow such things, such as JavaScript, are
called “dynamically typed”, meaning that there exist data types, but
variables are not bound to any of them.
There are 8 basic data types in JavaScript.
 Seven primitive data types:
 number for numbers of any kind: integer or floating-point, integers are
limited by ±(253-1).
 bigint for integer numbers of arbitrary length.
 string for strings. A string may have zero or more characters, there’s
no separate single-character type.
 boolean for true/false.
 null for unknown values – a standalone type that has a single value
null.
 undefined for unassigned values – a standalone type that has
a single value undefined.
 symbol for unique identifiers.
 And one non-primitive data type:
 object for more complex data structures.
 The typeof operator allows us to see which type is stored in a
variable.
Number
 The number type represents both integer and floating point numbers
 Besides regular numbers, there are so-called “special numeric values”
which also belong to this data type: Infinity, -Infinity and NaN.
 Infinity represents the mathematical Infinity ∞. It is a special value
that’s greater than any number.
 We can get it as a result of division by zero:
alert( 1 / 0 ); // Infinity
alert( Infinity ); // Infinity
 NaN represents a computational error. It is a result of an incorrect or
an undefined mathematical operation, for instance:
alert( "not a number" / 2 ); // NaN, such division is erroneous
BigInt
 In JavaScript, the “number” type cannot safely represent integer values
larger than (253-1) (that’s 9007199254740991), or less than -(2 53-1) for
negatives.
 For most purposes ±(253-1) range is quite enough, but sometimes we need
the entire range of really big integers, e.g. for cryptography or microsecond-
precision timestamps.
 BigInt type was recently added to the language to represent integers of
arbitrary length.
 A BigInt value is created by appending n to the end of an integer:
 // the "n" at the end means it's a BigInt
const bigInt = 1234567890123456789012345678901234567890n;
String
 A string in JavaScript must be surrounded by quotes.
 let str = "Hello";
 let str2 = 'Single quotes are ok too';
 let phrase = `can embed another ${str}`;
 In JavaScript, there are 3 types of quotes.
 Double quotes: "Hello".
 Single quotes: 'Hello'.
 Backticks: `Hello`.
 Double and single quotes are “simple” quotes. There’s practically no
difference between them in JavaScript.
 Backticks are “extended functionality” quotes. They allow us to embed
variables and expressions into a string by wrapping them in ${…}, for
example:
let name = "John";
// embed a variable
alert( `Hello, ${name}!` ); // Hello, John!”
// embed an expression
alert( `the result is ${1 + 2}` ); // the result is 3
String length
 The length property has the string length:
alert( `My\n`.length ); // 3
 Note that \n is a single “special” character, so the length is indeed 3
Strings are immutable
• Strings can’t be changed in JavaScript. It is impossible to change a
character.
• Let’s try it to show that it doesn’t work:
• let str = 'Hi';
• str[0] = 'h'; // error
• alert( str[0] );
Accessing characters
 To get a character at position pos, use square brackets [pos] or call the
method str.at(pos).
 The first character starts from the zero position:
let str = `Hello`;
// the first character
alert( str[0] ); // H
alert( str.at(0) ); // H
// the last character
alert( str[str.length - 1] ); // o
alert( str.at(-1) );
Accessing characters
• As you can see, the .at(pos) method has a benefit of allowing negative
position.
• If pos is negative, then it’s counted from the end of the string.
• So .at(-1) means the last character, and .at(-2) is the one before it, etc.
• The square brackets always return undefined for negative indexes
Changing the case
• Methods toLowerCase() and toUpperCase() change the case:
alert( 'Interface'.toUpperCase() ); // INTERFACE
alert( 'Interface'.toLowerCase() ); // interface
Or, if we want a single character lowercased:
alert( 'Interface'[0].toLowerCase() ); // 'i'
Searching for a substring
 There are multiple ways to look for a substring within a string.
 str.indexOf
 The first method is str.indexOf(substr, pos).
 It looks for the substr in str, starting from the given position pos, and returns
the position where the match was found or -1 if nothing can be found.
 For instance:
let str = 'Widget with id';
alert( str.indexOf('Widget') ); // 0, because 'Widget' is found at the beginning
alert( str.indexOf('widget') ); // -1, not found, the search is case-sensitive
alert( str.indexOf("id") ); // 1, "id" is found at the position 1 (..idget with id)
 The optional second parameter allows us to start searching
from a given position.
 For instance, the first occurrence of "id" is at position 1. To
look for the next occurrence, let’s start the search from
position 2:
let str = 'Widget with id';
alert( str.indexOf('id', 2) ) // 12
 There is also a similar method str.lastIndexOf(substr, position) that
searches from the end of a string to its beginning.
 It would list the occurrences in the reverse order.
includes, startsWith, endsWith
 The more modern method str.includes(substr, pos) returns
true/false depending on whether str contains substr within.
 It’s the right choice if we need to test for the match, but don’t
need its position:
alert( "Widget with id".includes("Widget") ); // true
alert( "Hello".includes("Bye") ); // false
 The optional second argument of str.includes is the
position to start searching from:
alert( "Widget".includes("id") ); // true
alert( "Widget".includes("id", 3) ); // false, from position 3 there
is no "id"
 The methods str.startsWith and str.endsWith do exactly what
they say:
 alert( "Widget".startsWith("Wid") ); // true, "Widget" starts with
"Wid"
 alert( "Widget".endsWith("get") ); // true, "Widget" ends with "get"
Getting a substring
• There are 3 methods in JavaScript to get a substring:
substring, substr and slice
str.slice(start [, end])
• Returns the part of the string from start to (but not including) end.
let str = "stringify";
alert( str.slice(0, 5) ); // 'strin', the substring from 0 to 5 (not including 5)
alert( str.slice(0, 1) ); // 's', from 0 to 1, but not including 1, so only character at 0
• If there is no second argument, then slice goes till the end of the string:
let str = "stringify";
alert( str.slice(2) ); // 'ringify', from the 2nd position till the end
• Negative values for start/end are also possible. They mean the position is
counted from the string end:
let str = "stringify";
// start at the 4th position from the right, end at the 1st from the right
alert( str.slice(-4, -1) ); // 'gif’
str.substring(start [, end])
 Returns the part of the string between start and end (not including end).
 This is almost the same as slice, but it allows start to be greater than end
(in this case it simply swaps start and end values).
For instance:
let str = "stringify";
// these are same for substring
alert( str.substring(2, 6) ); // "ring"
alert( str.substring(6, 2) ); // "ring"
// ...but not for slice:
alert( str.slice(2, 6) ); // "ring" (the same)
alert( str.slice(6, 2) ); // "" (an empty string)
 Negative arguments are (unlike slice) not supported, they are treated as 0.
str.substr(start [, length])
• Returns the part of the string from start, with the given length.
• In contrast with the previous methods, this one allows us to specify the
length instead of the ending position:
• let str = "stringify";
• alert( str.substr(2, 4) ); // 'ring', from the 2nd position get 4 characters
• The first argument may be negative, to count from the end:
• let str = "stringify";
• alert( str.substr(-4, 2) ); // 'gi', from the 4th position get 2 characters
method selects… negatives
from start to end (not
slice(start, end) allows negatives
including end)

between start and end (


substring(start, end) negative values mean 0
not including end)

from start get length ch


substr(start, length) allows negative start
aracters
 str.trim() – removes (“trims”) spaces from the beginning and end of
the string.
 str.repeat(n) – repeats the string n times.
 Uppercase the first character
 Write a function ucFirst(str) that returns the string str with the
uppercased first character, for instance:
ucFirst("john") == "John";
Boolean (logical type)
 The boolean type has only two values: true and false.
 This type is commonly used to store yes/no values: true means “yes,
correct”, and false means “no, incorrect”.
 For instance:
 let nameFieldChecked = true; // yes, name field is checked
 let ageFieldChecked = false; // no, age field is not checked
 Boolean values also come as a result of comparisons:
 let isGreater = 4 > 1;
 alert( isGreater ); // true (the comparison result is "yes")
The “null” value
• The special null value does not belong to any of the types described above.
• It forms a separate type of its own which contains only the null value:
• let age = null;
• In JavaScript, null is not a “reference to a non-existing object” or a “null
pointer” like in some other languages.
• It’s just a special value which represents “nothing”, “empty” or “value
unknown”.
• The code above states that age is unknown.
The “undefined” value
• The special value undefined also stands apart. It makes a type of its
own, just like null.
• The meaning of undefined is “value is not assigned”.
• If a variable is declared, but not assigned, then its value is undefined:
• let age;
• alert(age); // shows "undefined"
• Technically, it is possible to explicitly assign undefined to a variable:
• let age = 100;
• // change the value to undefined
• age = undefined;
• alert(age); // "undefined"
Objects
 The object type is special.
 All other types are called “primitive” because their values can
contain only a single thing (be it a string or a number or
whatever).
 In contrast, objects are used to store collections of data and more
complex entities.
 The symbol type is used to create unique identifiers for objects.
The typeof operator
 The typeof operator returns the type of the operand.
 It’s useful when we want to process values of different types
differently or just want to do a quick check.
 A call to typeof x returns a string with the type name:
typeof undefined // "undefined"
typeof 0 // "number"
typeof 10n // "bigint"
typeof true // "boolean"
typeof "foo" // "string"
typeof Symbol("id") // "symbol"
typeof Math // "object" (1)
typeof null // "object" (2)
typeof alert // "function" (3)
You may also come across another syntax: typeof(x). It’s the same as
typeof x.
Arrays
 Objects allow you to store keyed collections of values.
 to store ordered collections.
 There are two syntaxes for creating an empty array:
 let arr = new Array();
 let arr = [];
 let fruits = ["Apple", "Orange", "Plum"];
 Array elements are numbered, starting with zero.
 We can get an element by its number in square brackets:
 let fruits = ["Apple", "Orange", "Plum"];
 alert( fruits[0] ); // Apple
 alert( fruits[1] ); // Orange
 alert( fruits[2] ); // Plum
 We can replace an element:
fruits[2] = 'Pear'; // now ["Apple", "Orange", "Pear"]
 …Or add a new one to the array:
fruits[3] = 'Lemon'; // now ["Apple", "Orange", "Pear", "Lemon"]
 The total count of the elements in the array is its length:
let fruits = ["Apple", "Orange", "Plum"];
alert( fruits.length ); // 3
 We can also use alert to show the whole array.
let fruits = ["Apple", "Orange", "Plum"];
alert( fruits ); // Apple,Orange,Plum
 An array can store elements of any type.
 For instance:
 // mix of values
 let arr = [ 'Apple', { name: 'John' }, true, function() { alert('hello'); } ];
 // get the object at index 1 and then show its name
 alert( arr[1].name ); // John
 // get the function at index 3 and run it
 arr[3](); // hello
• We can explicitly calculate the last element index and then access it:
fruits[fruits.length - 1].
• let fruits = ["Apple", "Orange", "Plum"];
• alert( fruits[fruits.length-1] ); // Plum
• Luckily, there’s a shorter syntax: fruits.at(-1):
• let fruits = ["Apple", "Orange", "Plum"];
• // same as fruits[fruits.length-1]
• alert( fruits.at(-1) ); // Plum
• In other words, arr.at(i):
• is exactly the same as arr[i], if i >= 0.
• for negative values of i, it steps back from the end of the array.
Methods pop/push, shift/unshift
It supports two operations:
• push adds an element to the end.
• pop takes an element from the end.
• So new elements are added or taken always from the “end”.
• For stacks, the latest pushed item is received first, that’s also called
LIFO (Last-In-First-Out) principle. For queues, we have FIFO (First-
In-First-Out).
• Arrays in JavaScript can work both as a queue and as a stack. They
allow you to add/remove elements, both to/from the beginning or the
end.
• Methods that work with the end of the array:
pop
• Extracts the last element of the array and returns it:
• let fruits = ["Apple", "Orange", "Pear"];
• alert( fruits.pop() ); // remove "Pear" and alert it
• alert( fruits ); // Apple, Orange
• Both fruits.pop() and fruits.at(-1) return the last element of the array, but
fruits.pop() also modifies the array by removing it.
push
• Append the element to the end of the array:
• let fruits = ["Apple", "Orange"];
• fruits.push("Pear");
• alert( fruits ); // Apple, Orange, Pear
• The call fruits.push(...) is equal to fruits[fruits.length] = ....
• Methods that work with the beginning of the array:
shift
• Extracts the first element of the array and returns it:
• let fruits = ["Apple", "Orange", "Pear"];
• alert( fruits.shift() ); // remove Apple and alert it
• alert( fruits ); // Orange, Pear
unshift
• Add the element to the beginning of the array:
• let fruits = ["Orange", "Pear"];
• fruits.unshift('Apple');
• alert( fruits ); // Apple, Orange, Pear
 Methods push and unshift can add multiple elements at once:
 let fruits = ["Apple"];
 fruits.push("Orange", "Peach");
 fruits.unshift("Pineapple", "Lemon");
 // ["Pineapple", "Lemon", "Apple", "Orange", "Peach"]
 alert( fruits );
 push(...items) adds items to the end.
 pop() removes the element from the end and returns it.
 shift() removes the element from the beginning and returns it.
 unshift(...items) adds items to the beginning.
splice
How to delete an element from the array?
 The arrays are objects, so we can try to use delete:
 let arr = ["I", "go", "home"];
 delete arr[1]; // remove "go"
 alert( arr[1] ); // undefined
 // now arr = ["I", , "home"];
 alert( arr.length ); // 3
 The element was removed, but the array still has 3 elements, we can
see that arr.length == 3.
 The arr.splice method can do everything: insert, remove and replace
elements.
 The syntax is:
arr.splice(start[, deleteCount, elem1, ..., elemN])
 It modifies arr starting from the index start: removes deleteCount
elements and then inserts elem1, ..., elemN at their place. Returns the
array of removed elements.
 let arr = ["I", "study", "JavaScript"];
 arr.splice(1, 1); // from index 1 remove 1 element
 alert( arr ); // ["I", "JavaScript"]
• In the next example we remove 3 elements and replace them with the
other two:
let arr = ["I", "study", "JavaScript", "right", "now"];
// remove 3 first elements and replace them with another
arr.splice(0, 3, "Let's", "dance");
alert( arr ) // now ["Let's", "dance", "right", "now"]
• Here we can see that splice returns the array of removed elements:
let arr = ["I", "study", "JavaScript", "right", "now"];
// remove 2 first elements
let removed = arr.splice(0, 2);
alert( removed ); // "I", "study" <-- array of removed elements
• The splice method is also able to insert the elements without any
removals. For that we need to set deleteCount to 0:
let arr = ["I", "study", "JavaScript"];
// from index 2
// delete 0
// then insert "complex" and "language"
arr.splice(2, 0, "complex", "language");
alert( arr ); // "I", "study", "complex", "language", "JavaScript"
• Negative indexes allowed
• Here and in other array methods, negative indexes are allowed. They
specify the position from the end of the array, like here:
• let arr = [1, 2, 5];
• // from index -1 (one step from the end)
• // delete 0 elements,
• // then insert 3 and 4
• arr.splice(-1, 0, 3, 4);
• alert( arr ); // 1,2,3,4,5
• filter returns an array of all matching elements:
let users = [
{id: 1, name: "John"},
{id: 2, name: "Pete"},
{id: 3, name: "Mary"}
];
// returns array of the first two users
let someUsers = users.filter(item => item.id < 3);
alert(someUsers.length); // 2
Transform an array
• Let’s move on to methods that transform and reorder an array.
map
• The arr.map method is one of the most useful and often used.
• It calls the function for each element of the array and returns the array
of results.
• let lengths = ["Bilbo", "Gandalf", "Nazgul"].map(item => item.length);
• alert(lengths); // 5,7,6
reverse
• The method arr.reverse reverses the order of elements in arr.
• For instance:
• let arr = [1, 2, 3, 4, 5];
• arr.reverse();
• alert( arr ); // 5,4,3,2,1
• It also returns the array arr after the reversal.
split
The str.split(delim) method does exactly that. It splits the string into an array by the given
delimiter delim.
• In the example below, we split by a comma followed by space:
• let names = 'Bilbo, Gandalf, Nazgul';
• let arr = names.split(', ');
• for (let name of arr) {
• alert( `A message to ${name}.` ); // A message to Bilbo (and other names)
• }
• The split method has an optional second numeric argument – a limit
on the array length. If it is provided, then the extra elements are
ignored. In practice it is rarely used though:
• let arr = 'Bilbo, Gandalf, Nazgul, Saruman'.split(', ', 2);
• alert(arr); // Bilbo, Gandalf
join
• The call arr.join(glue) does the reverse to split. It creates a string of arr
items joined by glue between them.
• For instance:
• let arr = ['Bilbo', 'Gandalf', 'Nazgul'];
• let str = arr.join(';'); // glue the array into a string using ;
• alert( str ); // Bilbo;Gandalf;Nazgul
Interaction: alert, prompt, confirm
• alert
• This one we’ve seen already. It shows a message and waits for the user to
press “OK”.
• For example:
• Alert("Hello");
• prompt
• The function prompt accepts two arguments:
• result = prompt(title, [default]);
• It shows a modal window with a text message, an input field for the visitor,
and the buttons OK/Cancel.
• Title: The text to show the visitor.
• Default: An optional second parameter, the initial value for the input field.
 let age = prompt('How old are you?', 100);
 alert(`You are ${age} years old!`); // You are 100 years old!
 confirm
 The syntax:
 result = confirm(question);
 The function confirm shows a modal window with a question and two
buttons: OK and Cancel.
 The result is true if OK is pressed and false otherwise.
 For example:
 let isBoss = confirm("Are you the boss?");
 alert( isBoss ); // true if OK is pressed
Type Conversions
• Most of the time, operators and functions automatically convert the values
given to them to the right type.
• For example, alert automatically converts any value to a string to show it.
Mathematical operations convert values to numbers.
• There are also cases when we need to explicitly convert a value to the expected
type.
• String conversion happens when we need the string form of a value.
• We can also call the String(value) function to convert a value to a string:
• let value = true;
• alert(typeof value); // boolean
• value = String(value); // now value is a string "true"
• alert(typeof value); // string
• String conversion is mostly obvious. A false becomes "false", null becomes
"null", etc.
Numeric Conversion
• Numeric conversion in mathematical functions and expressions
happens automatically.
• For example, when division / is applied to non-numbers:
• alert( "6" / "2" ); // 3, strings are converted to numbers
• We can use the Number(value) function to explicitly convert a value to
a number:
• let str = "123";
• alert(typeof str); // string
• let num = Number(str); // becomes a number 123
• alert(typeof num); // number
 Explicit conversion is usually required when we read a value from a string-based
source like a text form but expect a number to be entered.
 If the string is not a valid number, the result of such a conversion is NaN. For
instance:
 let age = Number("an arbitrary string instead of a number");
 alert(age); // NaN, conversion failed
Numeric conversion rules:
 Value Becomes…
 undefined NaN
 Null 0
 true and false 1 and 0
 string Whitespaces (includes spaces, tabs \t, newlines \n etc.) from the start and
end are removed. If the remaining string is empty, the result is 0. Otherwise, the
number is “read” from the string. An error gives NaN.
Examples:
• alert( Number(“ 123 ") ); // 123
• alert( Number("123z") ); // NaN (error reading a number at "z")
• alert( Number(true) ); // 1
• alert( Number(false) ); // 0
• Please note that null and undefined behave differently here: null
becomes zero while undefined becomes NaN.
Boolean Conversion
 can be performed explicitly with a call to Boolean(value).
 The conversion rule:
 Values that are intuitively “empty”, like 0, an empty string, null,
undefined, and NaN, become false.
 Other values become true.
 For instance:
• alert( Boolean(1) ); // true
• alert( Boolean(0) ); // false
• alert( Boolean("hello") ); // true
• alert( Boolean("") ); // false
• alert( Boolean(“ ") ); // true
Functions
• Functions are the main “building blocks” of the program. They allow the
code to be called many times without repetition.
• Function Declaration
• To create a function we can use a function declaration.
• It looks like this:
function showMessage() {
alert( 'Hello everyone!' );
}
function name(parameter1, parameter2, ... parameterN) {
// body
}
 Our new function can be called by its name: showMessage().
 A variable declared inside a function is only visible inside that
function.
 For example:
function showMessage() {
let message = "Hello, I'm JavaScript!"; // local variable
alert( message );
}
showMessage(); // Hello, I'm JavaScript!
alert( message ); // <-- Error! The variable is local to the function
• A parameter is the variable listed inside the parentheses in the function
declaration (it’s a declaration time term).
• An argument is the value that is passed to the function when it is
called (it’s a call time term).
JavaScript - Placement in HTML File
• There is a flexibility given to include JavaScript code anywhere in an
HTML document. However the most preferred ways to include
JavaScript in an HTML file are as follows −
• Script in <head>...</head> section.
• Script in <body>...</body> section.
• Script in <body>...</body> and <head>...</head> sections.
• Script in an external file and then include in <head>...</head> section.
JavaScript in <head>...</head> section
• If you want to have a script run on some event, such as when a user clicks
somewhere, then you will place that script in the head as follows −
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
JavaScript in <body>...</body> section
• If you need a script to run as the page loads so that the script generates
content in the page, then the script goes in the <body> portion of the
document. In this case, you would not have any function defined using
JavaScript. Take a look at the following code.
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.write("Hello World")
</script>
<p>This is web page body </p>
</body>
</html>
JavaScript in <body> and <head> Sections
• You can put your JavaScript code in <head> and <body> section altogether as follows −
<html>
<head>
<script type="text/javascript">
function sayHello() {
alert("Hello World")
}
</script>
</head>
<body>
<script type="text/javascript">
document.write("Hello World")
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
JavaScript in External File
• you are not restricted to be maintaining identical code in multiple HTML files. The script tag
provides a mechanism to allow you to store JavaScript in an external file and then include it into
your HTML files.
• Here is an example to show how you can include an external JavaScript file in your HTML code
using script tag and its src attribute.
<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>
• To use JavaScript from an external file source, you need to write all your JavaScript source code in a
simple text file with the extension ".js" and then include that file as shown above.
• For example, you can keep the following content in filename.js file and then you can use sayHello
function in your HTML file after including the filename.js file.
function sayHello() {
alert("Hello World")
}
DOM (Document Object Model)
• The Document Object Model, or DOM for short, represents all page
content as objects that can be modified.
• The document object is the main “entry point” to the page. We can
change or create anything on the page using it.
• For instance:
• // change the background color to red
• document.body.style.background = "red";
• // change it back after 1 second
• setTimeout(() => document.body.style.background = "", 1000);
• The topmost tree nodes are available directly as document properties:
• <html> = document.documentElement
• The topmost document node is document.documentElement. That’s
the DOM node of the <html> tag.
• <body> = document.body
• Another widely used DOM node is the <body> element –
document.body.
• <head> = document.head
• The <head> tag is available as document.head.
• document.getElementById or just id
• If an element has the id attribute, we can get the element using the
method document.getElementById(id), no matter where it is.
• For instance:
<div id="elem">
<div id="elem-content">Element</div>
</div>
<script>
// get the element
let elem = document.getElementById('elem');
// make its background red
elem.style.background = 'red';
</script>
• elem.getElementsByClassName(className) returns elements that
have the given CSS class.
• document.getElementsByName(name) returns elements with the given
name attribute, document-wide. Very rarely used.
• // 1. The table with `id="age-table"`.
• let table = document.getElementById('age-table')
• // 2. All label elements inside that table
• table.getElementsByTagName('label')
• document.querySelectorAll('#age-table label')
• // 3. The first td in that table (with the word "Age")
• table.rows[0].cells[0]
• // or
• table.getElementsByTagName('td')[0]
• // or
• table.querySelector('td')
• // 4. The form with the name "search"
• // assuming there's only one element with name="search" in the document
• let form = document.getElementsByName('search')[0]
• // or, form specifically
• document.querySelector('form[name="search"]')
• // 5. The first input in that form.
• form.getElementsByTagName('input')[0]
• // or
• form.querySelector('input')
• // 6. The last input in that form
• let inputs = form.querySelectorAll('input') // find all inputs
• inputs[inputs.length-1] // take the last one
innerHTML
• The innerHTML property allows to get the HTML inside the element as a
string.
• We can also modify it. So it’s one of the most powerful ways to change the
page.
• The example shows the contents of document.body and then replaces it
completely:
<body>
<p>A paragraph</p>
<div>A div</div>
<script>
alert( document.body.innerHTML ); // read the current contents
document.body.innerHTML = 'The new BODY!'; // replace it
</script>
</body>
Regular expressions
• Regular expressions is a powerful way of doing search and replace in strings
Character classes
• Consider a practical task – we have a phone number like "+7(903)-123-45-67",
and we need to turn it into pure numbers: 79031234567.
• To do so, we can find and remove anything that’s not a number. Character classes
can help with that.
• A character class is a special notation that matches any symbol from a certain set.
• For the start, let’s explore the “digit” class. It’s written as \d and corresponds to
“any single digit”.
• For instance, let’s find the first digit in the phone number:
let str = "+7(903)-123-45-67";
let regexp = /\d/;
alert( str.match(regexp) ); // 7
• Without the flag g, the regular expression only looks for the first
match, that is the first digit \d.
Let’s add the g flag to find all digits:
let str = "+7(903)-123-45-67";
let regexp = /\d/g;
alert( str.match(regexp) ); // array of matches: 7,9,0,3,1,2,3,4,5,6,7
// let's make the digits-only phone number of them:
alert( str.match(regexp).join('') ); // 79031234567
• \d (“d” is from “digit”)
• A digit: a character from 0 to 9.
• \s (“s” is from “space”)
• A space symbol: includes spaces, tabs \t, newlines \n and few other
rare characters, such as \v, \f and \r.
• \w (“w” is from “word”)
• A “wordly” character: either a letter of Latin alphabet or a digit or an
underscore _. Non-Latin letters (like cyrillic or hindi) do not belong to
\w.
• For instance, \d\s\w means a “digit” followed by a “space character”
followed by a “wordly character”, such as 1 a.
• A regexp may contain both regular symbols and character classes.
• For instance, CSS\d matches a string CSS with a digit after it:
• let str = "Is there CSS4?";
• let regexp = /CSS\d/
• alert( str.match(regexp) ); // CSS4
• Also we can use many character classes:
• alert( "I love HTML5!".match(/\s\w\w\w\w\d/) ); // ' HTML5'
Inverse classes
• For every character class there exists an “inverse class”, denoted with the same
letter, but uppercased.
• The “inverse” means that it matches all other characters, for instance:
• \D
• Non-digit: any character except \d, for instance a letter.
• \S
• Non-space: any character except \s, for instance a letter.
• \W
• Non-wordly character: anything but \w, e.g a non-latin letter or a space.
• In the beginning of the chapter we saw how to make a number-only phone
number from a string like +7(903)-123-45-67: find all digits and join them.
• let str = "+7(903)-123-45-67";
• alert( str.match(/\d/g).join('') ); // 79031234567
• An alternative, shorter way is to find non-digits \D and remove them
from the string:
• let str = "+7(903)-123-45-67";
• alert( str.replace(/\D/g, "") ); // 79031234567
• A dot is “any character”
• A dot . is a special character class that matches “any character except a
newline”.
• For instance:
• alert( "Z".match(/./) ); // Z
• Or in the middle of a regexp:
• let regexp = /CS.4/;
• alert( "CSS4".match(regexp) ); // CSS4
• alert( "CS-4".match(regexp) ); // CS-4
• alert( "CS 4".match(regexp) ); // CS 4 (space is also a character)
• Anchors: string start ^ and end $
• The caret ^ and dollar $ characters have special meaning in a regexp.
They are called “anchors”.
• The caret ^ matches at the beginning of the text, and the dollar $ – at
the end.
• For instance, let’s test if the text starts with Mary:
• let str1 = "Mary had a little lamb";
• alert( /^Mary/.test(str1) ); // true
• The pattern ^Mary means: “string start and then Mary”.
• Similar to this, we can test if the string ends with snow using snow$:
• let str1 = "its fleece was white as snow";
• alert( /snow$/.test(str1) ); // true
Document Object Model

• The document object represents the whole html document.


• When html document is loaded in the browser, it becomes a document
object.
• It is the root element that represents the html document.
• It has properties and methods. By the help of document object, we can
add dynamic content to our web page.
• As mentioned earlier, it is the object of window. So window.document
Is same as document
Properties of document object
Let's see the properties of document object that can be accessed and
modified by the document
Methods of document object
We can access and change the contents of document by its methods.
The important methods of document object are as follows:

Method Description
write("string") writes the given string on the doucment.

writeln("string") writes the given string on the doucment with newline


character at the end.

getElementById() returns the element having the given id value.

getElementsByName() returns all the elements having the given name value.

getElementsByTagName() returns all the elements having the given tag name.

getElementsByClassName() returns all the elements having the given class name.
• Accessing field value by document object
• In this example, we are going to get the value of input text by user. Here, we
are using document.form1.name.value to get the value of name field.
1. <script type="text/javascript">
2. function printvalue(){
3. var name=document.form1.name.value;
4. alert("Welcome: "+name);
5. }
6. </script>
7.
8. <form name="form1">
9. Enter Name:<input type="text" name="name"/>
10.<input type="button" onclick="printvalue()" value="print name"/>
11.</form>
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">

<input type="button" onclick="totalelements()" value="Total Genders">


</form>
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);

}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by getElementByTag
Name() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
Javascript - innerHTML

• The innerHTML property can be used to write the dynamic html on


the html document.
• It is used mostly in the web pages to generate the dynamic html such
as registration form, comment form, links etc.
• Example of innerHTML property
• In this example, we are going to create the html form when user clicks
on the button.
<script type="text/javascript" >
function showcommentform() {
var data="Name:<input type='text' name='name'><br>Comment:<br><textarea
rows='5' cols='80'></textarea>
<br><input type='submit' value='Post Comment'>";
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>
JavaScript Form Validation

• It is important to validate the form submitted by the user because it


can have inappropriate values. So, validation is must to authenticate
user.
• JavaScript provides facility to validate the form on the client-side so
data processing will be faster than server-side validation.
• Most of the web developers prefer JavaScript form validation.
• Through JavaScript, we can validate name, password, email, date,
mobile numbers and more fields.
JavaScript Form Validation Example
1. <script>
2. function validateform(){
3. var name=document.myform.name.value;
4. var password=document.myform.password.value;
5. if (name==null || name==""){
6. alert("Name can't be blank");
7. return false;
8. }else if(password.length<6){
9. alert("Password must be at least 6 characters long.");
10. return false;
11. }
12. }
13. </script>
14. <body>
15. <form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >
16. Name: <input type="text" name="name"><br/>
17. Password: <input type="password" name="password"><br/>
18. <input type="submit" value="register">
19. </form>
JavaScript Retype Password Validation
1. <script type="text/javascript">
2. function matchpass(){
3. var firstpassword=document.f1.password.value;
4. var secondpassword=document.f1.password2.value;
5.
6. if(firstpassword==secondpassword){
7. return true;
8. }
9. else{
10. alert("password must be same!");
11. return false;
12. }
13. }
14. </script>
15.
16. <form name="f1" action="register.jsp" onsubmit="return matchpass()">
17. Password:<input type="password" name="password" /><br/>
18. Re-enter Password:<input type="password" name="password2"/><br/>
19. <input type="submit">
20. </form>
JavaScript Number Validation
1. <script>
2. function validate(){
3. var num=document.myform.num.value;
4. if (isNaN(num)){
5. document.getElementById("numloc").innerHTML="Enter Numeric value only";
6. return false;
7. }else{
8. return true;
9. }
10.}
11.</script>
12.<form name="myform" onsubmit="return validate()" >
13.Number: <input type="text" name="num"><span id="numloc"></span><br/>
14.<input type="submit" value="submit">
15.</form>
JavaScript validation with image
• Let’s see an interactive JavaScript form validation example that displays correct and incorrect image if input is correct or
incorrect.
1. <script>
2. function validate(){
3. var name=document.f1.name.value;
4. var password=document.f1.password.value;
5. var status=false;
6.
7. if(name.length<1){
8. document.getElementById("nameloc").innerHTML=
9. " <img src='unchecked.gif'/> Please enter your name";
10.status=false;
11.}else{
12.document.getElementById("nameloc").innerHTML=" <img src='checked.gif'/>";
13.status=true;
14.}
1. if(password.length<6){
2. document.getElementById("passwordloc").innerHTML=
3. " <img src='unchecked.gif'/> Password must be at least 6 char long";
4. status=false;
5. }else{
6. document.getElementById("passwordloc").innerHTML=" <img src='checked.gif'/>";
7. }
8. return status;
9. }
10.</script>
11.
1.<form name="f1" action="#" onsubmit="return validate()">
2.<table>
3.<tr><td>Enter Name:</td><td><input type="text" name="name"/>
4.<span id="nameloc"></span></td></tr>
5.<tr><td>Enter Password:</
td><td><input type="password" name="password"/>
6.<span id="passwordloc"></span></td></tr>
7.<tr><td colspan="2"><input type="submit" value="register"/></td></tr>
8.</table>
9.</form>
JavaScript email validation
• We can validate the email by the help of JavaScript.
• There are many criteria that need to be follow to validate the email id
such as:
• email id must contain the @ and . character
• There must be at least one character before and after the @.
• There must be at least two characters after . (dot).
• Let's see the simple example to validate the email field.
1. <script>
2. function validateemail()
3. {
4. var x=document.myform.email.value;
5. var atposition=x.indexOf("@");
6. var dotposition=x.lastIndexOf(".");
7. if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
8. alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
9. return false;
10. }
11.}
12.</script>
1.<body>
2.<form name="myform" method="post" action="#" onsubmit="return
validateemail();">
3.Email: <input type="text" name="email"><br/>
4.
5.<input type="submit" value="register">
6.</form>
Browser Object Model
1.Browser Object Model (BOM)
• The Browser Object Model (BOM) is used to interact with the
browser.
• The default object of browser is window means you can call all the
functions of window by specifying window or directly. For example:
1.window.alert("hello javatpoint");
JavaScript Objects
• A javaScript object is an entity having state and behavior (properties
and method). For example: car, pen, bike, chair, glass, keyboard,
monitor etc.
• JavaScript is an object-based language. Everything is an object in
JavaScript.
• JavaScript is template based not class based. Here, we don't create
class to get the object. But, we direct create objects.
Creating Objects in JavaScript
• There are 3 ways to create objects.
• By object literal
• By creating instance of Object directly (using new keyword)
• By using an object constructor (using new keyword)
1) JavaScript Object by object literal
• The syntax of creating object using object literal is given below:
1.object={property1:value1,property2:value2.....propertyN:valueN}
• As you can see, property and value is separated by : (colon).
• Let’s see the simple example of creating object in JavaScript.
1.<script>
2.emp={id:102,name:"Shyam Kumar",salary:40000}
3.document.write(emp.id+" "+emp.name+" "+emp.salary);
4.</script>
2) By creating instance of Object
• The syntax of creating object directly is given below:
1.var objectname=new Object();
• Here, new keyword is used to create object.
• Let’s see the example of creating object directly.
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
• 101 Ravi 50000
• 3) By using an Object constructor
• 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.
• The example of creating object by object constructor is given below.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);


</script>
• Browser Object Model
1.Browser Object Model (BOM)
• The Browser Object Model (BOM) is used to interact with the
browser.
• The default object of browser is window means you can call all the
functions of window by specifying window or directly. For example:
1.window.alert("hello javatpoint");
Methods of window object
The important methods of window object are as follows:
Method Description
alert() displays the alert box containing message with ok button.

confirm() displays the confirm dialog box containing message with ok


and cancel button.
prompt() displays a dialog box to get input from the user.
open() opens the new window.
close() closes the current window.
setTimeout() performs action after specified time like calling function,
evaluating expressions etc.
• Example of open() in javascript
• It displays the content in a new window.
1.<script type="text/javascript">
2.function msg(){
3.open("http://www.javatpoint.com");
4.}
5.</script>
6.<input type="button" value="javatpoint" onclick="msg()"/>
Methods of JavaScript history object
There are only 3 methods of history object.

No. Method Description


1 forward() loads the next page.
2 back() loads the previous
page.
3 go() loads the given page
number.
• Example of history object
• Let’s see the different usage of history object.
1.history.back();//for previous page
2.history.forward();//for next page
3.history.go(2);//for next 2nd page
4.history.go(-2);//for previous 2nd page

You might also like