Int222 JS Primerunit1
Int222 JS Primerunit1
BY : DIVYA THAKUR
UID:28300
JAVASCRIPT PRIMER
Why is it called JavaScript?
• When JavaScript was created, it initially had another name: “LiveScript”.
• But Java was very popular at that time, so it was decided that positioning a new
language as a “younger brother” of Java would help.
• But as it evolved, JavaScript became a fully independent language with its own
specification called ECMAScript, and now it has no relation to Java at all.
JAVASCRIPT
• JavaScript was initially created to “make web pages alive”.
• The programs in this language are called scripts. They can be written right in a web
page’s HTML and run automatically as the page loads.
• Scripts are provided and executed as plain text. They don’t need special preparation or
compilation to run.
• In this aspect, JavaScript is very different from another language called Java.
• Today, JavaScript can execute not only in the browser, but also on the server, or actually
on any device that has a special program called the JavaScript engine.
• The browser has an embedded engine sometimes called a “JavaScript virtual machine”.
CODE EDITORS
• There are two main types of code editors: IDEs and lightweight editorS :
IDE
• The term IDE (Integrated Development Environment) refers to a powerful editor
with many features that usually operates on a “whole project.” As the name
suggests, it’s not just an editor, but a full-scale “development environment.”
• An IDE loads the project (which can be many files), allows navigation between
files, provides autocompletion based on the whole project (not just the open
file), and integrates with a version management system (like git), a testing
environment, and other “project-level” stuff.
• “Lightweight editors” are not as powerful as IDEs, but they’re fast, elegant
and simple.
• They are mainly used to open and edit a file instantly.
• The main difference between a “lightweight editor” and an “IDE” is that an
IDE works on a project-level, so it loads much more data on start, analyzes the
project structure if needed and so on. A lightweight editor is much faster if we
need only one file.
• There are many options, for instance:
• Sublime Text (cross-platform, shareware).
• Notepad++ (Windows, free).
• Vim and Emacs .
JAVASCRIPT SYNTAX
• JavaScript programs can be inserted almost anywhere into an HTML document (HEAD &
BODY)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>.
• EXAMPLE:
<!DOCTYPE HTML>
<html>
<body>
<p>Before the script...</p>
<script>
alert( 'Hello, world!' );
</script>
<p>...After the script.</p>
</body>
</html>
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;
Constants:
• 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!
• When a programmer is sure that a variable will never change, they can declare it
with const to guarantee and clearly communicate that fact to everyone.
SCOPE
• Scope determines the accessibility (visibility) of variables.
• Before ES6 (2015), JavaScript had only Global Scope and Function
Scope(local scope)
• ES6 introduced two important new JavaScript keywords: let and const.
• These two keywords provide Block Scope in JavaScript.
• JavaScript has 3 types of scope:
• Block scope
• Function scope
• Global scope
• 1. Block Scope:
• Variables declared inside a { } block cannot be accessed from outside the
block:
• Variables declared with the var keyword can NOT have block scope.
• Variables declared inside a { } block can be accessed from outside the block.
EXAMPLE: {
var x = 2;
}
// x CAN be used here
• 2. Local Scope
• Variables declared within a JavaScript function, become LOCAL to the function
, i.e it can only be accessed within a function.
• Example:
let a = "hello";
function greet()
{
let b = "World"
console.log(a + b);
}
greet();
console.log(a + b); // error
• As we know from the chapter Data types, there are eight data types in JavaScript.
Seven of them are called “primitive”, because their values contain only a single
thing (be it a string or a number or whatever).
• In contrast, objects are used to store keyed collections of various data and more
complex entities. In JavaScript, objects penetrate almost every aspect of the
language. So we must understand them first before going in-depth anywhere else.
• An object can be created with figure brackets {…} with an optional list of
properties. A property is a “key: value” pair, where key is a string (also called a
“property name”), and value can be anything.
• We can imagine an object as a cabinet with signed files. Every piece of data is
stored in its file by the key. It’s easy to find a file by its name or add/remove a file.
• An empty object (“empty cabinet”) can be created using one of two syntaxes:
let user = new Object(); // "object constructor" syntax
let user = {}; // "object literal" syntax
• Usually, the figure brackets {...} are used. That declaration is called an object
literal.
• JavaScript object is a non-primitive data-type that allows you to store multiple
collections of data.
• Note: If you are familiar with other programming languages, JavaScript objects
are a bit different. You do not need to create classes in order to create objects.
• Example:
// object
const student = {
firstName: 'ram',
class: 10
};
Here, student is an object that stores values such as strings and numbers.
• JavaScript Object Declaration
• The syntax to declare an object is:
const object_name = {
key1: value1,
key2: value2 }
• Accessing Object Properties:
• You can access the value of a property by using its key.
1. Using dot Notation
• Here's the syntax of the dot notation.
objectName.key
2. Using bracket Notation
• Here is the syntax of the bracket notation.
objectName["propertyName"]
JavaScript Methods and this Keyword
• In JavaScript, objects can also contain functions. For example,
// object containing method
const person = {
name: 'John',
greet: function() { console.log('hello'); }
};
• In the above example, a person object has two keys (name and greet), which have
a string value and a function value, respectively.
• Hence basically, the JavaScript method is an object property that has a function
value.
Accessing Object Methods
• You can access an object method using a dot notation. The syntax is: objectName.methodKey()
• You can access property by calling an objectName and a key. You can access a method by calling an objectName
and a key for that method along with (). For example,
// accessing method and property
const person = {
name: 'John',
greet: function() { console.log('hello'); }
};
// accessing property
person.name; // John
// accessing method
person.greet(); // hello
<body onload="add()"> // Execute a JavaScript immediately after a page has been loaded
<script>
var i=Number(prompt("Enter 1st variable"));
var j=Number(prompt("enter 2nd varialbe"));
function add()
{
document.write("the sum is ",(i+j));
}
</script>
</body>
</html>
Javascript Event Example:
<html>
<input type="button" value="Hover" id="btn"
onmouseover="this.style.background='red'; this.style.color='yellow'"
onmouseout="this.style.background='cadetblue';
this.style.color='white'"/>
</html>
Javascript Example 2 :
<html> <input type="button" value="Click me" id="btn"
onmouseover="changeColorOnMouseOver(this)"
onmouseout="changeColorOnMouseOut(this)"/>
<script type="text/javascript">
function changeColorOnMouseOver(x)
{
x.style.background='red';
x.style.color='yellow';
}
function changeColorOnMouseOut(x)
{
x.style.background='cadetblue';
x.style.color='white';
}
</script>
</html>
2. Using the new keyword
• You can also create an array using JavaScript's new keyword.
const array2 = new Array("eat", "sleep");
• In both of the above examples, we have created an array having two
elements.
Note: It is recommended to use array literal to create an array.
• Here are more examples of arrays:
// empty array
const myList = [ ];
// array of numbers
const numberArray = [ 2, 4, 6, 8];
// array of strings
const stringArray = [ 'eat', 'work', 'sleep'];
// array with mixed data types
const newData = ['work', 'exercise', 1, true];
• You can also store arrays, functions and other objects inside an array. For example,
const newData = [
{'task1': 'exercise'},
[1, 2 ,3],
function hello() { console.log('hello')}
];
• The unshift() method adds an element at the beginning of the array. For example,
let dailyActivities = ['eat', 'sleep'];
//add an element at the start
dailyActivities.unshift('work');
console.log(dailyActivities); // ['work', 'eat', 'sleep']
• Change the Elements of an Array
• You can also add elements or change the elements by accessing the
index value.
let dailyActivities = [ 'eat', 'sleep'];
// this will add the new element 'exercise' at the 2 index
dailyActivities[2] = 'exercise';
console.log(dailyActivities); // ['eat', 'sleep', 'exercise']
• Remove an Element from an Array
• You can use the pop() method to remove the last element from an array.
The pop() method also returns the returned value. For example,
let dailyActivities = ['work', 'eat', 'sleep', 'exercise'];
// remove the last element
dailyActivities.pop();
console.log(dailyActivities); // ['work', 'eat', 'sleep']
• If you need to remove the first element, you can use the shift() method.
• The shift() method removes the first element and also returns the removed
element. For example,
let dailyActivities = ['work', 'eat', 'sleep'];
// remove the first element
dailyActivities.shift();
console.log(dailyActivities); // ['eat', 'sleep']
Array length
You can find the length of an element (the number of elements in an array) using the
length property. For example,
Note: You need to use catch or finally statement after try statement. Otherwise,
the program will throw an error Uncaught SyntaxError: Missing catch or finally
after try.
Example 2: try...catch...finally Example
const numerator= 100, denominator = 'a';
try {
console.log(numerator/denominator);
console.log(a);
}
catch(error) {
console.log('An error caught');
console.log('Error message: ' + error);
}
finally {
console.log('Finally will execute every time');
}
JavaScript throw Statement
• In JavaScript, the throw statement handles user-defined exceptions. For example,
if a certain number is divided by 0, and if you need to consider Infinity as an
exception, you can use the throw statement to handle that exception.
• The syntax of throw statement is:
throw expression;
Here, expression specifies the value of the exception.
For example,
const number = 5;
throw number/0; // generate an exception when divided by 0
JavaScript throw with try...catch
• The syntax of try...catch...throw is:
try { // body of try
throw exception; }
catch(error) { // body of catch }
Note: When the throw statement is executed, it exits out of the block
and goes to the catch block. And the code below the throw statement
is not executed.
Example 1: try...catch...throw Example
const number = 40;
try {
if(number > 50) {
console.log('Success');
}
else {
throw new Error('The number is low'); // user-defined throw statement
}
// if throw executes, the below code does not execute
console.log('hello');
}
catch(error) {
console.log('An error caught');
console.log('Error message: ' + error);
}
Java Script DOM:
• With the HTML DOM, JavaScript can access and change all the elements of
an HTML document.
• When a web page is loaded, the browser creates a Document Object Model
of the page.
• With the object model, JavaScript gets all the power it needs to create
dynamic HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page
Changing HTML Content
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Validation</h2>
<form action="/action_page.php" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
<p>If you click submit, without filling out the text field,
your browser will display an error message.</p>
</body>
</html>
• The HTML DOM is a standard object model and programming
interface for HTML. It defines:
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements
• In other words: The HTML DOM is a standard for how to get, change,
add, or delete HTML elements.
Dom Object
• When an HTML document is loaded into a web browser, it becomes a
document object.
• The document object is the root node of the HTML document.
• The document object is a property of the window object.
• The document object is accessed with:
• window.document or document
Example: The url property
• <!DOCTYPE html>
• <html>
• <body>
• <h1>Window Document Object</h1>
• <h2>The URL Property</h2>
• <p id="p1"></p>
• <script>
• let url = window.document.URL;
• document.getElementById("p1").innerHTML = url;
• </script>
• </body>
• </html>
JavaScript - HTML DOM Methods
• HTML DOM methods are actions you can perform (on HTML Elements).
• HTML DOM properties are values (of HTML Elements) that you can set
or change.
• The DOM Programming Interface:
• The HTML DOM can be accessed with JavaScript (and with other programming
languages).
• In the DOM, all HTML elements are defined as objects.
• The programming interface is the properties and methods of each object.
• A property is a value that you can get or set (like changing the content of an
HTML element).
• A method is an action you can do (like add or deleting an HTML element).
• <html><body>
• <p id="id"></p>
• <script>
• document.getElementById("id").innerHTML = "This is a paragraph";
• </script></body></html>
• The first parameter is the type of the event (like "click" or "mousedown" or any
other HTML DOM Event.)
• The second parameter is the function we want to call when the event occurs.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to execute a function when a user
clicks on a button.</p>
<button id="myBtn">Try it</button>
<script>
document.getElementById("myBtn").addEventListener("click", myFunction);
function myFunction() {
alert ("Hello World!");
}
</script>
</body>
</html>
Example :
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to attach a click event to a button.</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
document.getElementById("myBtn").addEventListener("click", displayDate());
function displayDate() {
document.getElementById("demo").innerHTML = Date();}
</script>
</body>
</html>
Add Many Event Handlers to the Same Element
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to add many events on the same button.</p>
<button id="myBtn">Try it</button>
<p id="demo"></p> <script>
var x = document.getElementById("myBtn");
x.addEventListener("mouseover", myFunction);
x.addEventListener("click", mySecondFunction);
x.addEventListener("mouseout", myThirdFunction);
function myFunction() {
document.getElementById("demo").innerHTML += "Moused over!<br>";
}
function mySecondFunction() {
document.getElementById("demo").innerHTML += "Clicked!<br>";
}
function myThirdFunction() {
document.getElementById("demo").innerHTML += "Moused out!<br>";
} </script> </body> </html>
Using the removeEventListener() method
• The Javascript removeEventListener() is an inbuilt function that is
used to remove removes an event handler that was previously added
using the addEventListener() function from the element.
• element.removeEventListener(event, listener)