Javascript Basics
What is JavaScript?
• JavaScript is a programming language for use in HTML pages
• Invented in 1995 at Netscape Corporation (LiveScript)
• JavaScript has nothing to do with Java
• JavaScript programs are run by an interpreter built into the user's web
browser (not on the server)
What can JavaScript Do?
• JavaScript can dynamically modify an HTML page
• JavaScript can react to user input
• JavaScript can validate user input
• JavaScript can be used to create cookies
• JavaScript is a full-featured programming language
• JavaScript user interaction does not require any communication
with the server
Pros and Cons of JavaScript
• Pros:
• Allows more dynamic HTML pages, even complete web applications
• Cons:
• Requires a JavaScript-enabled browser
• Requires a client who trusts the server enough to run the code the server
provides
• JavaScript has some protection in place but can still cause security
problems for clients
Using JavaScript in your HTML
• JavaScript can be inserted into documents by using the SCRIPT tag
<html>
<head>
<title>Hello World in JavaScript</title>
</head>
<body>
<script type="text/javascript">
document.write("Hello
World!");
</script>
</body>
</html>
Where to Put your Scripts
• You can have any number of scripts
• Scripts can be placed in the HEAD or in the BODY
• In the HEAD, scripts are run before the page is displayed
• In the BODY, scripts are run as the page is displayed
• In the HEAD is the right place to define functions and variables that
are used by scripts within the BODY
Using JavaScript in your HTML
<html>
<head>
<title>Hello World in JavaScript</title>
<script
type="text/javascript">
function helloWorld() {
document.write("Hello
World!");
}
</script>
</head>
<body>
<script
type="text/javascript">
helloWorld();
</script>
</body>
</html>
External Scripts
• Scripts can also be loaded from an external file
• This is useful if you have a complicated script or set of subroutines
that are used in several different documents
<script src="myscript.js"></script>
JavaScript Output
1. JavaScript innerHTML Property
• The innerHTML property is used with the HTML element. JavaScript can be
used to select an element using the document.getElementById(id) method,
and then use the innerHTML property to Inserts content into an HTML
element.
• <p id="demo"></p>
• <script>
• document.getElementById("demo").innerHTML = "Hello, DOM!";
• </script>
JavaScript Output
2. JavaScript console.log() Method
The console.log() method is used for logging messages to the
console. It is a debugging tool available in most web browsers. It is used
during development to output information about the state of the
program.
console.log();
JavaScript Output
3. JavaScript document.write() Method
To use the document.write(), simply call this method and provide
the content you want to be written to the document. This method is
often used for directly adding content to the HTML document while it is
being parsed.
document.write();
JavaScript Output
4. JavaScript window.alert() Method
The window.alert() method is used to display an alert box with a
specified output (or message) and an OK button.
window.alert();
Note: We can skip the window keyword in this method.
JavaScript Output
5. JavaScript window.print() Method
The window.print() method is used to open the browser's print
dialog, allowing the user to print the current page.
window.print();
Input from User
6. JavaScript window.prompt() Method
The window.prompt() method is used to display a dialog box that
prompts the user input. It returns the text entered by the user as a string. It
doesn't display output directly but captures user input.
<script>
let userInput = window.prompt("Please Enter your Input");
if (userInput !== null) {
window.alert("Hello, " + userInput + "!");
}
</script>
Variables and Datatypes in
JavaScript
• JavaScript is a dynamically typed language, meaning that a variable isn’t
associated with a specific type. In other words, a variable can hold a value of
different types.
• let counter = 120; // counter is a number
• counter = false; // counter is now a boolean
• counter = "foo"; // counter is now a string
• To determine the current type of the value stored in a variable, you use the typeof
operator:
• JavaScript has the primitive data types:
• null
• undefined
• boolean
• number
• string
Javascript Variables
• 1. var Keyword
• The var keyword is used to declare a variable. It has a function-scoped or
globally-scoped behaviour.
• var n = 5;
• console.log(n);
• 2. let Keyword
• The let keyword is introduced in ES6, has block scope and cannot be re-
declared in the same scope.
• let n= 10;
• n = 20; // Value can be updated
• // let n = 15; //can not redeclare
• console.log(n)
Javascript Variables
• 3. const Keyword
• The const keyword declares variables that cannot be reassigned. It's block-
scoped as well.
• const n = 100;
• // n = 200; This will throw an error
• console.log(n)
Differences Between var and let
1: Variable scopes
• The var variables belong to the global scope when you define them outside a
function. For example:
• var counter;
• In this example, the counter is a global variable. It means that the counter variable is
accessible by any function.
• When you declare a variable inside a function using the var keyword, the
scope of the variable is local. function name()
{
if(true){
let i=10 console.log("Inside the loop:", i);
}
console.log("Outside the loop:", i);
} name()
Differences Between var and let
2. Creating global properties
• The global var variables are added to the global object as properties. The
global object is window on the web browser
• var counter = 0;
• console.log(window.counter); // 0
• However, the let variables are not added to the global object:
• let counter = 0;
• console.log(window.counter); // undefined
Differences Between var and let
• The var keyword allows you to redeclare a variable without any issue
• var counter = 10;
• var counter;
• console.log(counter); // 10
• If you redeclare a variable with the let keyword, you will get an error:
• let counter = 10;
• let counter; // error
Data Types
The undefined type
• The undefined type is a primitive type that has only one value
undefined. By default, when a variable is declared but not initialized,
it defaults to undefined.
• Consider the following example:
• let counter;
• console.log(counter); // undefined
• console.log(typeof counter); // undefined
The null type
• The null type is the second primitive data type that also has only one
value null. For example:
• let obj = null;
• console.log(typeof obj); // object
• JavaScript defines that null is equal to undefined as follows:
• console.log(null == undefined); // true
The Number type
• JavaScript uses the number type to represent both integer and
floating-point numbers.
• The following statement declares a variable and initializes its value
with an integer:
• let num = 100;
• To represent a floating-point number, you include a decimal point
followed by at least one number. For example:
• let price = 12.5;
• let discount = 0.05;
The Number Type
• Note that JavaScript automatically converts a floating-point number
into an integer if the number appears to be a whole number.
• The reason is that Javascript always wants to use less memory since a
floating-point value uses twice as much memory as an integer value.
For example:
• let price = 200.00; // interpreted as an integer 200
• To get the range of the number type, you use Number.MIN_VALUE
and Number.MAX_VALUE. For example:
• console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
• console.log(Number.MIN_VALUE); // 5e-324
NaN
• NaN stands for Not a Number. It is a special numeric value that
indicates an invalid number. For example, the division of a string by a
number returns NaN:.
• console.log('a'/2); // NaN;
• The NaN has two special characteristics:
• Any operation with NaN returns NaN.
• The NaN does not equal any value, including itself.
• console.log(NaN/2); // NaN
• console.log(NaN == NaN); // false
• typeof(NaN)
The string type
• In JavaScript, a string is a sequence of zero or more characters. A
string literal begins and ends with either a single quote(') or a double
quote (").
• let greeting = 'Hi';
• let message = "Bye";
• If you want to use single quotes or double quotes in a literal string,
you need to use the backslash to escape them. For example:
• let message = 'I\'m also a valid string'; // use \ to escape the single quote (')
The String Type
• JavaScript strings are immutable, meaning that they cannot be
modified once created. However, you can create a new string from an
existing one. For example:
• let str = 'JavaScript';
• str = str + ' String‘;
• Behind the scene, the JavaScript engine creates a new string that
holds the new string 'JavaScript String' and destroys the original
strings 'JavaScript' and ' String‘.
• let s = 'JavaScript';
• s[0] = 'j';
• console.log(s)
The String Type
• Expressions involving a string, the + operator and
• a number will convert the numbers to strings
• x = "The answer is " + 42 // returns "The answer is 42"
• y = 42 + " is the answer" // returns "42 is the answer"
• With other operators, strings are converted to
• numbers
• "37" - 7 // returns 30
• "37" + 7 // returns "377"
The String Type
• Dynamic string
• let title = “mr” ;
• let name = “raj” ;
• let sentence = `We welcome ${title} ${name}` ;//Back Ticks
The boolean type
• The boolean type has two literal values: true and false in lowercase.
The following example declares two variables that hold the boolean
values.
• let inProgress = true;
• let completed = false;
• console.log(typeof completed); // Boolean
• JavaScript allows values of other types to be converted into boolean
values of true or false.
• console.log(Boolean('Hi'));// true
• console.log(Boolean('')); // false
The object type
• In JavaScript, an object is a collection of properties, where each property is
defined as a key-value pair.
• let emptyObject = {};
• let person = {
firstName: 'John',
lastName: 'Doe'
};
• To access an object’s property, you can use
• The dot notation (.)
• console.log(person.firstName);
• The array-like notation ([]).
• console.log(person[‘firstName’]);
JavaScript and the DOM
• The Document Object Model (DOM) is a specification that determines a
mapping between
• programming language objects
• and the elements of an HTML document
• Not specific to JavaScript
• 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
HTML DOM Objects
• Environment objects
• Window, Navigator, Screen, History, Location, Document
• HTML objects
• Anchor, Area, Base, Body, Button, Event, Form, Frame, Frameset, Iframe,
Image, Checkbox, FileUpload, Hidden, Password, Radio, Reset, Submit, Text,
Link, Meta, Object, Option, Select, Style, Table, TableCell, TableRow, TextArea
HTML DOM: Document
• The Document object represents an HTML document and can be
used to access all documents in a page
• A Document contains several collections
• anchors, forms, images, links
• Has several useful methods
• getElementById, getElementsByName, getElementsByTagName, write,
writeln, open, close
HTML DOM: Document
• An instance of Document created, called document
function changeF() {
var cText = document.getElementById("c");
var fText = document.getElementById("f");
...
}
...
<input type="text" id="c" onchange="changeC()">C
<input type="text" id="f" onchange="changeF()">F
HTML DOM: The Document Tree
• 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.
HTML DOM: The Document Tree
HTML DOM Methods
• HTML DOM methods are actions you can perform (on HTML
Elements).
• HTML DOM properties are that you can set or change.
• <script>
• document.getElementById("demo").innerHTML = "Hello World!";
• </script>
• In the example above, getElementById is a method, while innerHTML is a
property.