Why Study Javascript?

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

JavaScript is the world's most popular programming language.

JavaScript is the programming language of the Web.


Why Study JavaScript?
JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages

JavaScript Introduction
JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById().
The example below "finds" an HTML element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript":

<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello
JavaScript!"'>Click Me!</button>
</body>
</html>

JavaScript Can Change HTML Attribute Values

In this example JavaScript changes the value of the src (source) attribute of
an <img> tag:
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attribute values.</p>
<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>
<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the
light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">


<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the
light</button>
</body>
</html>

JavaScript Can Change HTML Styles (CSS)


Changing the style of an HTML element, is a variant of changing an HTML
attribute:

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>


<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click
Me!</button>
</body>
</html>

JavaScript Can Hide HTML Elements

Hiding HTML elements can be done by changing the display style:


<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>


<p id="demo">JavaScript can hide HTML elements.</p>
<button type="button" onclick="document.getElementById('demo').style.display='none'">Click
Me!</button>
</body>
</html>
JavaScript Can Show HTML Elements
Showing hidden HTML elements can also be done by changing the display style:
<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>


<p>JavaScript can show hidden HTML elements.</p>
<p id="demo" style="display:none">Hello JavaScript!</p>
<button type="button" onclick="document.getElementById('demo').style.display='block'">Click
Me!</button>
</body>
</html>

JavaScript Where To write


In HTML, JavaScript code is inserted between <script> and </script> tags.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
</body>
</html>

JavaScript Functions and Events

A JavaScript function is a block of JavaScript code, that can be executed when


"called" for.
For example, a function can be called when an event occurs, like when the user
clicks a button.
JavaScript in <head> or <body>
You can place any number of scripts in an HTML document.
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in
both.
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML
page.
The function is invoked (called) when a button is clicked:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h2>Demo JavaScript in Head</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML
page.

The function is invoked (called) when a button is clicked:


<!DOCTYPE html>
<html>
<body>

<h2>Demo JavaScript in Body</h2>

<p id="demo">A Paragraph</p>

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
External JavaScript
Scripts can also be placed in external files:

External file: myScript.js

function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
External scripts are practical when the same code is used in many different web
pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:
<script src="myScript.js"></script>

<!DOCTYPE html>
<html>
<body>

<h2>Demo External JavaScript</h2>


<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>This example links to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>
<script src="myScript.js"></script>
</body> </html>

You can place an external script reference in <head> or <body> as you like.
The script will behave as if it was located exactly where the <script> tag is
located.
External scripts cannot contain <script> tags.

External JavaScript Advantages


Placing scripts in external files has some advantages:
 It separates HTML and code
 It makes HTML and JavaScript easier to read and maintain
 Cached JavaScript files can speed up page loads
To add several script files to one page - use several script tags:
Example
<script src="myScript1.js"></script>
<script src="myScript2.js"></script>

External References
An external script can be referenced in 3 different ways:
 With a full URL (a full web address)
 With a file path (like /js/)
 Without any path
This example uses a full URL to link to myScript.js:
<script src="https://www.abc.com/js/myScript.js"></script>

This example uses a file path to link to myScript.js:

<script src="/js/myScript.js"></script>

This example uses no path to link to myScript.js:

<script src="myScript.js"></script>

JavaScript Output
JavaScript Display Possibilities

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
the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the

HTML content:
<html>
<body>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>

Changing the innerHTML property of an HTML element is a common way to display


data in HTML.

Using document.write()
For testing purposes, it is convenient to use document.write():
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>

Using document.write() after an HTML document is loaded, will delete all


existing HTML:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button type="button" onclick="document.write(5 + 6)">Try it</button>
</body>
</html>

The document.write() method should only be used for testing.

Using window.alert()
You can use an alert box to display data:
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>

You can skip the window keyword.


In JavaScript, the window object is the global scope object. This means that
variables, properties, and methods by default belong to the window object. This
also means that specifying the window keyword is optional:
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
alert(5 + 6);
</script>

</body>
</html>
Using console.log()

For debugging purposes, you can call the console.log() method in the browser to
display data.
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>

</body>
</html>

JavaScript Print
JavaScript does not have any print object or print methods.
You cannot access output devices from JavaScript.
The only exception is that you can call the window.print() method in the browser
to print the content of the current window.
<!DOCTYPE html>
<html>
<body>

<button onclick="window.print()">Print this page</button>

</body>
</html>

JavaScript Statements

let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>A <b>JavaScript program</b> is a list of <b>statements</b> to be executed by a computer.</p>
<p id="demo"></p>
<script>
let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
document.getElementById("demo").innerHTML = "The value of z is " + z + ".";
</script>
</body>
</html>

JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.

JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action
to be performed.
Here is a list of some of the keywords you will learn about in this tutorial:

Keyword Description
Var Declares a variable
Let Declares a block variable
Const Declares a block constant
If Marks a block of statements to be executed on a condition
Switch Marks a block of statements to be executed in different cases
For Marks a block of statements to be executed in a loop
Function Declares a function
Return Exits a function
Try Implements error handling to a block of statements

JavaScript keywords are reserved words. Reserved words cannot be used as


names for variables.
JavaScript Values
The JavaScript syntax defines two types of values:
 Fixed values
 Variable values
Fixed values are called Literals.
Variable values are called Variables.

JavaScript Literals
The two most important syntax rules for fixed values are:

1. Numbers are written with or without decimals:

<script>
document.getElementById("demo").innerHTML = 10.50;
</script>

2. Strings are text, written within double or single quotes:

<script>
document.getElementById("demo").innerHTML = 'John Doe';
</script>

JavaScript Variables
In a programming language, variables are used to store data values.
JavaScript uses the keywords var, let and const to declare variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p>In this example, x is defined as a variable.


Then, x is assigned the value of 6:</p>

<p id="demo"></p>
<script>
let x;
x = 6;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Operators</h2>
<p>JavaScript uses arithmetic operators to compute values (just like algebra).</p>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = (5 + 6) * 10;
</script>

</body>
</html>

JavaScript Expressions
An expression is a combination of values, variables, and operators, which
computes to a value.
The computation is called an evaluation.
For example, 5 * 10 evaluates to 50:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Expressions</h2>
<p>Expressions compute to values.</p>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 * 10;
</script>

</body>
</html>

<script>
let x, y;
x = 5 + 6;
y = x * 10;
document.getElementById("demo").innerHTML = y;
</script>

JavaScript Comments
Not all JavaScript statements are "executed".
Code after double slashes // or between /* and */ is treated as a comment.
Comments are ignored, and will not be executed:

JavaScript Identifiers / Names


Identifiers are JavaScript names.
Identifiers are used to name variables and keywords, and functions.
The rules for legal names are the same in most programming languages.
A JavaScript name must begin with:
 A letter (A-Z or a-z)
 A dollar sign ($)
 Or an underscore (_)
Subsequent characters may be letters, digits, underscores, or dollar signs.
Numbers are not allowed as the first character in names.
This way JavaScript can easily distinguish identifiers from numbers.

JavaScript is Case Sensitive


All JavaScript identifiers are case sensitive.
The variables lastName and lastname, are two different variables:
let lastname, lastName;
lastName = "Doe";
lastname = "Peterson";

JavaScript Variables
Variables are Containers for Storing Data

JavaScript Variables can be declared in 4 ways:


 Automatically
 Using var
 Using let
 Using const

In this first example, x, y, and z are undeclared variables.


They are automatically declared when first used:
x = 5;
y = 6;
z = x + y;

Example using var


var x = 5;
var y = 6;
var z = x + y;

Note
The var keyword was used in all JavaScript code from 1995 to 2015.
The let and const keywords were added to JavaScript in 2015.
The var keyword should only be used in code written for older browsers.

Example using Let


<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>

<p>In this example, x, y, and z are variables.</p>


<p id="demo"></p>

<script>
let x = 5;
let y = 6;
let z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>

</body>
</html>

Example using const


<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>

<p>In this example, x, y, and z are variables.</p>

<p id="demo"></p>

<script>
const x = 5;
const y = 6;
const z = x + y;
document.getElementById("demo").innerHTML = "The value of z is: " + z;
</script>

</body>
</html>

Mixed Example
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
When to Use var, let, or const?
1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed (Arrays and Objects)
4. Only use let if you can't use const
5. Only use var if you MUST support old browsers.

JavaScript Identifiers

All JavaScript variables must be identified with unique names.


These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
 Names can contain letters, digits, underscores, and dollar signs.
 Names must begin with a letter.
 Names can also begin with $ and _ (but we will not use it in this tutorial).
 Names are case sensitive (y and Y are different variables).
 Reserved words (like JavaScript keywords) cannot be used as names.
Note
JavaScript identifiers are case-sensitive.
JavaScript Data Types
JavaScript variables can hold numbers like 100 and text values like "John Doe".
In programming, text values are called text strings.
JavaScript can handle many types of data, but for now, just think of numbers and
strings.
Strings are written inside double or single quotes. Numbers are written without
quotes.
If you put a number in quotes, it will be treated as a text string.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>Strings are written with quotes.</p>
<p>Numbers are written without quotes.</p>
<p id="demo"></p>
<script>
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';
document.getElementById("demo").innerHTML = pi + "<br>" + person + "<br>" + answer;
</script> </body> </html>

One Statement, Many Variables


You can declare many variables in one statement.

Start the statement with let and separate the variables by comma:

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>You can declare many variables in one statement.</p>
<p id="demo"></p>
<script>
let person = "John Doe", carName = "Volvo", price = 200;
document.getElementById("demo").innerHTML = carName;
</script>
</body>
</html>
Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable declared with var, it will not lose its value.
The variable carName will still have the value "Volvo" after the execution of these statements:
Example
var carName = "Volvo";
var carName;
Note : You cannot re-declare a variable declared with let or const.

This will not work:


let carName = "Volvo";
let carName;

JavaScript Dollar Sign $


Since JavaScript treats a dollar sign as a letter, identifiers containing $ are
valid variable names:
let $ = "Hello World";
let $$$ = 2;
let $myMoney = 5;
<script>
let $$$ = 2;
let $myMoney = 5;
document.getElementById("demo").innerHTML = $$$ + $myMoney;
</script>

JavaScript Underscore (_)


Since JavaScript treats underscore as a letter, identifiers containing _ are valid
variable names:

let _lastName = "Johnson";


let _x = 2;
let _100 = 5;

JavaScript Let
The let keyword was introduced in ES6 (2015)

Variables defined with let cannot be Redeclared

Variables defined with let must be Declared before use

Variables defined with let have Block Scope

Block Scope
Before ES6 (2015), JavaScript had Global Scope and Function Scope.

ES6 introduced two important new JavaScript keywords: let and const.

These two keywords provide Block Scope in JavaScript.

Variables declared inside a { } block cannot be accessed from outside the


block:
{
let x = 2;
}
// x can NOT be used here

Variables declared with the var keyword can NOT have block scope.

Variables declared inside a { } block can be accessed from outside the block.

{
var x = 2;
}
// x CAN be used here

Redeclaring Variables
Redeclaring a variable using the var keyword can impose problems.

Redeclaring a variable inside a block will also redeclare the variable outside the
block:

var x = 10;
// Here x is 10

{
var x = 2;
// Here x is 2
}
// Here x is 2

Redeclaring a variable using the let keyword can solve this problem.

Redeclaring a variable inside a block will not redeclare the variable outside the
block:

let x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}

// Here x is 10

Difference Between var, let and const


Scope Redeclare Reassign Hoisted Binds this
var No Yes Yes Yes Yes
let Yes No Yes No No
const Yes No No No No

What is Good?
let and const have block scope.

let and const can not be redeclared.

let and const must be declared before use.

let and const does not bind to this.

let and const are not hoisted.

What is Not Good?

var does not have to be declared.

var is hoisted.

var binds to this.

Redeclaring
Redeclaring a JavaScript variable with var is allowed anywhere in a program:

var x = 2;
// Now x is 2

var x = 3;
// Now x is 3
With let, redeclaring a variable in the same block is NOT allowed:
var x = 2; // Allowed
let x = 3; // Not allowed

{
let x = 2; // Allowed
let x = 3; // Not allowed
}

{
let x = 2; // Allowed
var x = 3; // Not allowed
}

Redeclaring a variable with let, in another block, IS allowed:

let x = 2; // Allowed

{
let x = 3; // Allowed
}

{
let x = 4; // Allowed
}

Let Hoisting
Variables defined with var are hoisted to the top and can be initialized at any
time.

Meaning: You can use the variable before it is declared:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Hoisting</h2>
<p>With <b>var</b>, you can use a variable before it is declared:</p>
<p id="demo"></p>
<script>
carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
var carName;
</script>
</body>
</html>

Variables defined with let are also hoisted to the top of the block, but not
initialized.

Meaning: Using a let variable before it is declared will result in


a ReferenceError:

carName = "Saab";
let carName = "Volvo";
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Hoisting</h2>
<p>With <b>let</b>, you cannot use a variable before it is declared.</p>
<p id="demo"></p>
<script>
try {
carName = "Saab";
let carName = "Volvo";
}
catch(err) {
document.getElementById("demo").innerHTML = err;
}
</script>
</body>
</html>

You might also like