Javascript
JavaScript Tutorial for beginners and
professionals is a solution of client side
dynamic pages.
JavaScript is an object-based scripting
language that is lightweight and cross-
platform
.
JavaScript is not compiled but translated. The
JavaScript Translator (embedded in browser)
is responsible to translate the JavaScript
code.
Where JavaScript is used?
• JavaScript is used to create interactive websites. It
is mainly used for:
• Client-side validation
• Dynamic drop-down menus
• Displaying data and time
• Displaying popup windows and dialog boxes (like
alert dialog box, confirm dialog box and prompt
dialog box)
• Displaying clocks etc.
Why also use client-side scripting?
client-side scripting (JavaScript) benefits:
usability: can modify a page without having
to post back to the server (faster UI)
efficiency: can make small, quick changes to
page without waiting for server
event-driven: can respond to user actions like
clicks and
3 Places to put JavaScript code
• Between the body tag of html
• Between the head tag of html
• In .js file (external javaScript)
Between Body Tags
• <html>
• <body>
• <script type="text/javascript">
• alert("Hello Javatpoint");
• </script>
• </body>
• </html>
Between Head Tag
• <html>
• <head>
• <script type="text/javascript">
• function msg( )
• {
• alert("Hello Javatpoint");
• }
• </script>
• </head>
•
• <body>
• <p>Welcome to JavaScript</p>
• <form>
• <input type="button" value="click" onclick="msg()"/>
• </form>
• </body>
• </html>
JS OUTPUT
JavaScript can "display" data in different ways:
• Writing into an HTML element,
using innerHTML.
• Writing into the HTML output
using document.write().
• Writing into an alert box, using window.alert().
• Writing into the browser console,
using console.log()
using innerHTML
• To access an HTML element, JavaScript can
use document.getElementById(id) method.
• The id attribute defines the HTML element.
• The innerHTML property defines the HTML
content:
• Changing the innerHTML property of an HTML
element is a common way to display data in HTML.
using innerHTML
• <!DOCTYPE html>
• <html>
• <body>
• <h2>My First Web Page</h2>
• <p>My First Paragraph.</p>
• <p id="demo"> hi</p>
• <script>
• document.getElementById("demo").innerHTML = 'hello'
• </script>
• </body>
• </html>
Using document.write()
• For testing purposes, it is convenient to use document.write():
<!DOCTYPE html>
• <html>
• <body>
• <h2>My First Web Page</h2>
• <p>My first paragraph.</p>
• <script>
• document.write(‘hello’);
• </script>
• </body>
• </html>
Using window.alert()
• You can use an alert box to display data
• <!DOCTYPE html>
• <html>
• <body>
• <h2>My First Web Page</h2>
• <p>My first paragraph.</p>
• <script>
• window.alert("hello");
• </script>
• </body>
• </html>
Using console.log()
• For debugging purposes, you can use the console.log() method
to display data.
• <!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
javaScript Programs
• A computer program is a list of "instructions" to be "executed"
by the computer.
• In a programming language, these program instructions are
called statements.
JavaScript statements are composed of:
• Var, Operators, Expressions, Keywords, and Comments.
• JavaScript is a programming language.
• JavaScript statements are separated by semicolons:
JS Comments
• Single line // or <!
• Multiple lines /* */
Operators
• There are following types of operators in
JavaScript.
• Arithmetic Operators
• Comparison (Relational) Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
• Special Operators
Assignment Operator
Logical Operators
Function, class ,module
JS Variables
• A JavaScript variable is simply a name of storage location. There are two types of variables in
JavaScript : local variable and global variable.
• There are some rules while declaring a JavaScript variable (also known as identifiers).
• Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
• After first letter we can use digits (0 to 9), for example value1.
• JavaScript variables are case sensitive, for example x and X are different variables.
•
var length = 16; // Number
var fname = "Johnson"; // String
var person = {firstName:"John",lastName:"Doe"}; // Object
name=person.lastname;
name=person["lastname"];
To be able to operate on variables, it is important to know something about the type.
Let variable in JS
let myName = "my name"; Declare using let
let myName = "my name";
let myName = "not my name";
console.log(myName);
//output => SyntaxError: redeclaration of let name
• scope of let variable
• The let variable has block scope, meaning let variable will be accessible only
inside the block it's declared if we try of access outside of the scope, it will show
a Reference Error.
let myAge = 20;
if(myAge > 18) {
let myName = "my name";
console.log(myName) //output => "my name"
}
console.log(myName); //output => ReferenceError
Const variable in JS
• What is the The new version of javascript (ES6)
introduces two new methods of declaring
variables in javascript, one was using the const
keyword to declare constant variables.
• Example of const variable:
const myName = "my name";
const myName = "my name";
myName = "my new name";
console.log(myName);
//TypeError: invalid assignment to const myName'
Data type
var x; if (x === undefined) { alert ("only declared, but not defined.") };
if(sVal === '' || sVal === null
• When adding a number and a string, JavaScript
will treat the number as a string.
• var x = 16 + "Volvo"; will be traeted as
var x = "16" + "Volvo";
var x = "Volvo" + 16; volvo16
JavaScript evaluates expressions from left to right.
Different sequences can produce different results:
var x = 16 + 4 + "Volvo"; 20Volvo
var x = "Volvo" + 16 + 4; Volvo164
Declaring Variable Types
• When you declare a new variable, you can
declare its type using the "new" keyword:
• var carname = new String;
var x = new Number;
var y = new Boolean;
var cars = new Array;
var person = new Object; a
Four ways to create an array
• You can use an array literal:
var colors = ["red", "green", "blue"];
• You can use new Array() to create an empty array:
– var colors = new Array();
– You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue"; colors[1]="green";
• You can use new Array(n) with a single numeric
argument to create an array of that size
– var colors = new Array(3);
• You can use new Array(…) with two or more arguments
to create an array containing those values:
– var colors = new Array("red","green", "blue");
Variable Scope
JavaScript local variable
• A JavaScript local variable is declared inside block or
function. It is accessible within the function or block
o
<script>
function abc(){
var x=10;//local variable
}
</script
Global variable
• A JavaScript global variable is accessible from any function. A variable i.e. declared
outside the function or declared with window object is known as
Global variable
• <script>
• var data=200;//gloabal variable
• function a(){
• document.writeln(data);
• }
• function b(){
• document.writeln(data);
• }
• a();//calling JavaScript function
• b();
• </script>
Decision Making
If ,Switch
• JavaScript If-else
• The JavaScript if-else statement is
used to execute the code whether
condition is true or false. There are three
forms of if statement in JavaScript.
• If Statement
• If else statement
• if else if statement
Functions
• JavaScript Functions
• JavaScript functions are used to perform operations. We
can call JavaScript function many times to reuse the code.
• Advantage of JavaScript function
• There are mainly two advantages of JavaScript functions.
• Code reusability: We can call a function several times so it
save coding.
• Less coding: It makes our program compact. We don’t
need to write many lines of code each time to perform a
common task.
• function functionName([arg1, arg2, ...argN]){
• //code to be executed
• return(optional)
• }
• <script>
• function msg(){
• alert("hello! this is message");
• }
• </script>
• <input type="button" onclick="msg()" value="call function"/>
JavaScript Function Arguments We can call function by passing arguments.
Let’s see the example of function that has one argument.
• <script>
• function getcube(number){
• alert(number*number*number);
• }
• </script>
• <form>
• <input type="button" value="click" onclick="getcube(4)"/>
• </form>
Return Value
• <script>
• function getInfo(){
• return "hello javatpoint! How r u?";
• }
• </script>
• <script>
• document.write(getInfo());
• </script>
Calling Function
• <html>
• <body>
• <script>
• function myfun(){
• for (i=1; i<=10; i++)
• {
• document.write(i + "<br/>" )
• }
• }
• </script>
• <script>
• document.write(myfun());
• </script>
• </body>
• </html>
<script>
function getcube(number)
{
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>