Javascript Note
Javascript Note
Javascript Note
What is JavaScript?
HTML—Controls the structure of the web page/to define the content of web
pages.
CSS – Controls the presentation/design / to specify the layout of web pages.
JavaScript—Adds behavior and Interactivity / to program the behavior of web
pages.
JavaScript is the world's most popular programming language.
JavaScript is the programming language of the Web.
JavaScript is easy to learn.
JavaScript Where To
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 = "Paragraphchanged.";}
</script>
</head>
<body>
<p id="demo">AParagraph</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>
<p id="demo">AParagraph</p>
<button type="button" onclick="myFunction()">Try</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: myfile.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>
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.
To add several script files to one page - use several script tags:
<script src="myScript1.js"></script>
<script src="myScript2.js"></script>
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:
<body>
<h1>MyFirstWebPage</h1>
<p>MyFirstParagraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
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():
<script>
document.write(5 + 6);
</script>
Using document.write() after an HTML document is loaded, will delete all existing HTML:
Using window.alert()
You can use an alert box to display data:
<script>window.alert(5 + 6);</script>
Using console.log()
For debugging purposes, you can call the console.log() method in the
browser to display data.
JavaScript Programs
A computer program is a list of "instructions" to be "executed" by a
computer.
In a programming language, these programming instructions are
called statements.
A JavaScript program is a list of programming statements.
JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
This statement tells the browser to write "Hello Dolly." inside an HTML
element with id="demo":
document.getElementById("demo").innerHTML = "Hello Dolly.";
Semicolons;
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:
let a,b,c; //Declare3variables
a=5; //Assign the value 5 to a
b=6; // Assign the value 6 to b
c= a + b; // Assign the sum of a and b to c
When separated by semicolons, multiple statements on one line are
allowed:
a = 5; b = 6; c = a + b;
let x = y + z;
If a JavaScript statement does not fit on one line, the best place to break it is
after an operator:
document.getElementById("demo").innerHTML =
"Hello Dolly!";
One place you will find statements grouped together in blocks, is in JavaScript
functions:
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript
action to be performed.
Our Reserved Words Reference lists all JavaScript keywords.
Here is a list of some of the keywords you will learn about in this tutorial:
Keyword Description
JavaScript Syntax
❮ PreviousNext ❯
JavaScript Values
The JavaScript syntax defines two types of values:
Fixed values
Variable values
Fixed values are called Literals.
JavaScript Literals
The two most important syntax rules for fixed values are:
10.50
1001
Try it Yourself »
"John Doe"
'John Doe'
Try it Yourself »
ADVERTISEMENT
JavaScript Variables
In a programming language, variables are used to store data values.
JavaScript uses the keywords var, let and const to declare variables.
let x;
x = 6;
Try it Yourself »
JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:
(5 + 6) * 10
Try it Yourself »
let x, y;
x = 5;
y = 6;
Try it Yourself »
JavaScript Expressions
An expression is a combination of values, variables, and operators, which
computes to a value.
5 * 10
Try it Yourself »
x * 10
Try it Yourself »
Try it Yourself »
JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.
Try it Yourself »
var x, y;
x = 5 + 6;
y = x * 10;
Try it Yourself »
In these examples, using var or let will produce the same result.
You will learn more about var and let later in this tutorial.
JavaScript Comments
Not all JavaScript statements are "executed".
Try it Yourself »
The rules for legal names are the same in most programming languages.
Note
Numbers are not allowed as the first character in names.
Try it Yourself »
Hyphens:
Hyphens are not allowed in JavaScript. They are reserved for subtractions.
Underscore:
JavaScript programmers tend to use camel case that starts with a lowercase
letter:
firstName, lastName, masterCard, interCity.
Unicode covers (almost) all the characters, punctuations, and symbols in the
world.
JavaScript Comments
❮ PreviousNext ❯
Example
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
Try it Yourself »
This example uses a single line comment at the end of each line to explain the
code:
Example
let x = 5; // Declare x, give it the value of 5
let y = x + 2; // Declare y, give it the value of x + 2
Try it Yourself »
Multi-line Comments
Multi-line comments start with /* and end with */.
Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
Try it Yourself »
ADVERTISEMENT
Adding // in front of a code line changes the code lines from an executable line
to a comment.
Try it Yourself »
Example
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
JavaScript Variables
❮ PreviousNext ❯
Automatically
Using var
Using let
Using const
Try it Yourself »
Note
It is considered good programming practice to always declare variables before
use.
Try it Yourself »
Note
The var keyword was used in all JavaScript code from 1995 to 2015.
Try it Yourself »
Try it Yourself »
Mixed Example
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
Try it Yourself »
The two variables price1 and price2 are declared with the const keyword.
3. Always use const if the type should not be changed (Arrays and Objects)
let x = 5;
let y = 6;
let z = x + y;
From the example above, you can guess that the total is calculated to be 11.
Note
Variables are containers for storing values.
ADVERTISEMENT
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
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:
Note
JavaScript identifiers are case-sensitive.
x = x + 5
(It calculates the value of x + 5 and puts the result into x. The value of x is
incremented by 5.)
Note
The "equal to" operator is written like == in JavaScript.
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.
Example
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';
Try it Yourself »
You declare a JavaScript variable with the var or the let keyword:
var carName;
or:
let carName;
carName = "Volvo";
You can also assign a value to the variable when you declare it:
In the example below, we create a variable called carName and assign the value
"Volvo" to it.
<script>
let carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
Try it Yourself »
Note
It's a good programming practice to declare all variables at the beginning of a
script.
Start the statement with let and separate the variables by comma:
Example
let person = "John Doe", carName = "Volvo", price = 200;
Try it Yourself »
Try it Yourself »
Value = undefined
In computer programs, variables are often declared without a value. The value
can be something that has to be calculated, or something that will be provided
later, like user input.
The variable carName will have the value undefined after the execution of this
statement:
Example
let carName;
Try it Yourself »
The variable carName will still have the value "Volvo" after the execution of
these statements:
Example
var carName = "Volvo";
var carName;
Try it Yourself »
Note
You cannot re-declare a variable declared with let or const.
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using
operators like = and +:
Example
let x = 5 + 2 + 3;
Try it Yourself »
Example
let x = "John" + " " + "Doe";
Try it Yourself »
Example
let x = "5" + 2 + 3;
Try it Yourself »
Note
If you put a number in quotes, the rest of the numbers will be treated as
strings, and concatenated.
Example
let x = 2 + 3 + "5";
Try it Yourself »
JavaScript Dollar Sign $
Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid
variable names:
Example
let $ = "Hello World";
let $$$ = 2;
let $myMoney = 5;
Try it Yourself »
Using the dollar sign is not very common in JavaScript, but professional
programmers often use it as an alias for the main function in a JavaScript
library.
In the JavaScript library jQuery, for instance, the main function $ is used to
select HTML elements. In jQuery $("p"); means "select all p elements".
Example
let _lastName = "Johnson";
let _x = 2;
let _100 = 5;
Try it Yourself »
JavaScript Let
❮ PreviousNext ❯
Block Scope
Before ES6 (2015), JavaScript did not have Block Scope.
ES6 introduced the two new JavaScript keywords: let and const.
Variables declared inside a { } block cannot be accessed from outside the block:
{
let x = 2;
}
// x can NOT be used here
Global Scope
Variables declared with the var always have Global Scope.
Variables declared with the var keyword can NOT have block scope:
Example
Variables declared with varinside a { } block can be accessed from outside the
block:
{
var x = 2;
}
// x CAN be used here
Cannot be Redeclared
Variables defined with let can not be redeclared.
let x = 0;
var x = 0;
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:
Example
var x = 10;
// Here x is 10
{
var x = 2;
// Here x is 2
}
// Here x is 2
Try it Yourself »
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:
Example
let x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
Try it Yourself »
const Yes No No
What is Good?
let and const have block scope.
Browser Support
The let and const keywords are not supported in Internet Explorer 11 or earlier.
The following table defines the first browser versions with full support:
ADVERTISEMENT
Redeclaring
Redeclaring a JavaScript variable with var is allowed anywhere in a program:
Example
var x = 2;
// Now x is 2
var x = 3;
// Now x is 3
Try it Yourself »
Example
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
}
Example
let x = 2; // Allowed
{
let x = 3; // Allowed
}
{
let x = 4; // Allowed
}
Try it Yourself »
Let Hoisting
Variables defined with var are hoisted to the top and can be initialized at any
time.
Example
This is OK:
carName = "Volvo";
var carName;
Try it Yourself »
If you want to learn more about hoisting, study the chapter JavaScript Hoisting.
Variables defined with let are also hoisted to the top of the block, but not
initialized.
JavaScript Const
❮ PreviousNext ❯
Cannot be Reassigned
A variable defined with the const keyword cannot be reassigned:
Example
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
Try it Yourself »
Must be Assigned
JavaScript const variables must be assigned a value when they are declared:
Correct
const PI = 3.14159265359;
Incorrect
const PI;
PI = 3.14159265359;
A new Array
A new Object
A new Function
A new RegExp
Constant Arrays
You can change the elements of a constant array:
Example
// You can create a constant array:
const cars = ["Saab", "Volvo", "BMW"];
Example
const cars = ["Saab", "Volvo", "BMW"];
Try it Yourself »
Constant Objects
You can change the properties of a constant object:
Example
// You can create a const object:
const car = {type:"Fiat", model:"500", color:"white"};
Try it Yourself »
Try it Yourself »
const Yes No No
What is Good?
let and const have block scope.
let and const can not be redeclared.
var is hoisted.
Browser Support
The let and const keywords are not supported in Internet Explorer 11 or earlier.
The following table defines the first browser versions with full support:
Block Scope
Declaring a variable with const is similar to let when it comes to Block Scope.
The x declared in the block, in this example, is not the same as the x declared
outside the block:
Example
const x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
Try it Yourself »
You can learn more about block scope in the chapter JavaScript Scope.
Redeclaring
Redeclaring a JavaScript var variable is allowed anywhere in a program:
Example
var x = 2; // Allowed
var x = 3; // Allowed
x = 4; // Allowed
Redeclaring an existing var or let variable to const, in the same scope, is not
allowed:
Example
var x = 2; // Allowed
const x = 2; // Not allowed
{
let x = 2; // Allowed
const x = 2; // Not allowed
}
{
const x = 2; // Allowed
const x = 2; // Not allowed
}
Example
const x = 2; // Allowed
x = 2; // Not allowed
var x = 2; // Not allowed
let x = 2; // Not allowed
const x = 2; // Not allowed
{
const x = 2; // Allowed
x = 2; // Not allowed
var x = 2; // Not allowed
let x = 2; // Not allowed
const x = 2; // Not allowed
}
Example
const x = 2; // Allowed
{
const x = 3; // Allowed
}
{
const x = 4; // Allowed
}
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:
Example
This is OK:
carName = "Volvo";
var carName;
Try it Yourself »
If you want to learn more about hoisting, study the chapter JavaScript Hoisting.
Variables defined with const are also hoisted to the top, but not initialized.
JavaScript Operators
❮ PreviousNext ❯
Examples:
JavaScript Assignment
The Assignment Operator (=) assigns a value to a variable:
Assignment Examples
let x = 10;
Try it Yourself »
Try it Yourself »
JavaScript Addition
The Addition Operator (+) adds numbers:
Adding
let x = 5;
let y = 2;
let z = x + y;
Try it Yourself »
JavaScript Multiplication
The Multiplication Operator (*) multiplies numbers:
Multiplying
let x = 5;
let y = 2;
let z = x * y;
Try it Yourself »
Arithmetic Operators
Assignment Operators
Comparison Operators
String Operators
Logical Operators
Bitwise Operators
Ternary Operators
Type Operators
JavaScript Arithmetic Operators
Arithmetic Operators are used to perform arithmetic on numbers:
Try it Yourself »
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
Note
Arithmetic operators are fully described in the JS Arithmetic chapter.
ADVERTISEMENT
Assignment
let x = 10;
x += 5;
Try it Yourself »
Operator Example S
= x=y x
+= x += y x
-= x -= y x
*= x *= y x
/= x /= y x
%= x %= y x
**= x **= y x
Note
Assignment operators are fully described in the JS Assignment chapter.
JavaScript Comparison Operators
Operator Description
== equal to
!= not equal
Note
Comparison operators are fully described in the JS Comparisons chapter.
Example
let text1 = "A";
let text2 = "B";
let result = text1 < text2;
Try it Yourself »
Example
let text1 = "20";
let text2 = "5";
let result = text1 < text2;
Try it Yourself »
JavaScript String Addition
The + can also be used to add (concatenate) strings:
Example
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
Try it Yourself »
Example
let text1 = "What a very ";
text1 += "nice day";
Try it Yourself »
Note
When used on strings, the + operator is called the concatenation operator.
Adding Strings and Numbers
Adding two numbers, will return the sum, but adding a number and a string will
return a string:
Example
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;
10
55
Hello5
Try it Yourself »
Note
If you add a number and a string, the result will be a string!
Operator Description
&& logical and
|| logical or
! logical not
Note
Logical operators are fully described in the JS Comparisons chapter.
Operator Description
Note
Type operators are fully described in the JS Type Conversion chapter.
Any numeric operand in the operation is converted into a 32 bit number. The
result is converted back to a JavaScript number.
~ NOT ~5 ~0101
JavaScript Arithmetic
❮ PreviousNext ❯
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Remainder)
++ Increment
-- Decrement
Arithmetic Operations
A typical arithmetic operation operates on two numbers.
Example
let x = 100 + 50;
Try it Yourself »
or variables:
Example
let x = a + b;
Try it Yourself »
or expressions:
Example
let x = (100 + 50) * a;
Try it Yourself »
Operand Operator
100 +
ADVERTISEMENT
Adding
The addition operator (+) adds numbers:
Example
let x = 5;
let y = 2;
let z = x + y;
Try it Yourself »
Subtracting
The subtraction operator (-) subtracts numbers.
Example
let x = 5;
let y = 2;
let z = x - y;
Try it Yourself »
Multiplying
The multiplication operator (*) multiplies numbers.
Example
let x = 5;
let y = 2;
let z = x * y;
Try it Yourself »
Dividing
The division operator (/) divides numbers.
Example
let x = 5;
let y = 2;
let z = x / y;
Try it Yourself »
Remainder
The modulus operator (%) returns the division remainder.
Example
let x = 5;
let y = 2;
let z = x % y;
Try it Yourself »
Incrementing
The increment operator (++) increments numbers.
Example
let x = 5;
x++;
let z = x;
Try it Yourself »
Decrementing
The decrement operator (--) decrements numbers.
Example
let x = 5;
x--;
let z = x;
Try it Yourself »
Exponentiation
The exponentiation operator (**) raises the first operand to the power of the
second operand.
Example
let x = 5;
let z = x ** 2;
Try it Yourself »
Example
let x = 5;
let z = Math.pow(x,2);
Try it Yourself »
Operator Precedence
Operator precedence describes the order in which operations are performed in
an arithmetic expression.
Example
let x = 100 + 50 * 3;
Try it Yourself »
Is the result of example above the same as 150 * 3, or is it the same as 100 +
150?
Multiplication (*) and division (/) have higher precedence than addition (+) and
subtraction (-).
When using parentheses, the operations inside the parentheses are computed
first:
Example
let x = (100 + 50) * 3;
Try it Yourself »
When many operations have the same precedence (like addition and subtraction
or multiplication and division), they are computed from left to right:
Examples
let x = 100 + 50 - 3;
Try it Yourself »
let x = 100 / 50 * 3;
JavaScript Assignment
❮ PreviousNext ❯
Operator Example
= x=y
+= x += y
-= x -= y
*= x *= y
/= x /= y
%= x %= y
**= x **= y
Operator Example
<<= x <<= y
>>= x >>= y
>>>= x >>>= y
Operator Example
&= x &= y
^= x ^= y
|= x |= y
??= x ??= y x = x ??
Note
The Logical assignment operators are ES2020.
The = Operator
The Simple Assignment Operator assigns a value to a variable.
Try it Yourself »
let x = 10 + y;
Try it Yourself »
The += Operator
The Addition Assignment Operator adds a value to a variable.
Try it Yourself »
Try it Yourself »
The -= Operator
The Subtraction Assignment Operator subtracts a value from a variable.
Try it Yourself »
The *= Operator
The Multiplication Assignment Operator multiplies a variable.
Try it Yourself »
Try it Yourself »
The /= Operator
The Division Assignment Operator divides a variable.
Try it Yourself »
The %= Operator
The Remainder Assignment Operator assigns a remainder to a variable.
Try it Yourself »
ADVERTISEMENT
Try it Yourself »
Try it Yourself »
The &= Operator
The Bitwise AND Assignment Operator does a bitwise AND operation on two
operands and assigns the result to the the variable.
Try it Yourself »
The |= Operator
The Bitwise OR Assignment Operator does a bitwise OR operation on two
operands and assigns the result to the variable.
Try it Yourself »
The ^= Operator
The Bitwise XOR Assignment Operator does a bitwise XOR operation on two
operands and assigns the result to the variable.
Try it Yourself »
Try it Yourself »
Try it Yourself »
Try it Yourself »
x = 10;
y = 5;
x y;