JavaScript Display Possibilities
JavaScript can "display" data in different ways:
Writing into an HTML element, using innerHTML or innerText.
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, you can use the document.getElementById(id) method.
Use the id attribute to identify the HTML element.
Then use the innerhtml property to change the HTML content of the HTML element:
My First Web Page
My First Paragraph
Using innerText
To access an HTML element, use the document.getElementById(id) method.
Then use the innerText property to change the inner text of the HTML element:
Example
My First Web Page
My First Paragraph
Note
Use innerHTML when you want to change an HTML element.
Use innerText when you only want to change the plain text.
Using document.write()
For testing purposes, it is convenient to use document.write():
Example
My First Web Page
My first paragraph.
Using document.write() after an HTML document is loaded, will delete all existing HTML:
My First Web Page
My first paragraph.
The document.write() method should only be used for testing.
Activate Debugging
F12 on your keyboard will activate debugging.
Then select "Console" in the debugger menu.
Then click Run again.
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.
Example
Demo JavaScript in Head
A Paragraph.
Demo JavaScript in Body
A Paragraph.
Demo External JavaScript
A Paragraph.
This example links to "myScript.js".
(myFunction is stored in "myScript.js")
External JavaScript
A Paragraph.
This example uses a full web URL to link to "myScript.js".
(myFunction is stored in "myScript.js")
External JavaScript
A Paragraph.
This example uses a file path to link to "myScript.js".
(myFunction is stored in "myScript.js")
------------------------------------------------------------------------------------------
Writing into the HTML output
Never call document.write after the document has finished loading.
It will overwrite the whole document.
Writing into an HTML element
Writing into a window alert box
Writing in the browser console
A JavaScript program is a list of statements to be executed by a computer.
JavaScript Numbers
Number can be written with or without decimals.
JavaScript Strings
Strings can be written with double or single quotes.
JavaScript Variables
In this example, x is defined as a variable.
Then, x is assigned the value of 6:
JavaScript Operators
JavaScript uses arithmetic operators to compute values (just like algebra).
Assigning JavaScript Values
In JavaScript the = operator is used to assign values to variables.
JavaScript Expressions
Expressions compute to values.
JavaScript Expressions
Expressions compute to values.
JavaScript Expressions
Expressions compute to values.
The var Keyword Creates Variables
JavaScript Comments are NOT Executed
JavaScript is Case Sensitive
Try to change lastName to lastname.
---------------------------------------------------------
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:
Example
x = 5;
y = 6;
z = x + y;
Note
It is considered good programming practice to always declare variables before use.
From the examples you can guess:
x stores the value 5
y stores the value 6
z stores the value 11
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
let x = 5;
let y = 6;
let z = x + y;
Mixed Example
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
The two variables price1 and price2 are declared with the const keyword.
These are constant values and cannot be changed.
The variable total is declared with the let keyword.
The value total can be changed.
The two variables price1 and price2 are declared with the const keyword.
These are constant values and cannot be changed.
The variable total is declared with the let keyword.
The value total can be changed.
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.
Just Like Algebra
Just like in algebra, variables hold values:
let x = 5;
let y = 6;
Just like in algebra, variables are used in expressions:
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.
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.
The Assignment Operator
In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.
This is different from algebra. The following does not make sense in algebra:
x = x + 5
In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.
(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 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.
Example
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';
Declaring a JavaScript Variable
Creating a variable in JavaScript is called "declaring" a variable.
You declare a JavaScript variable with the var or the let keyword:
var carName;
or:
let carName;
After the declaration, the variable has no value (technically it is undefined).
To assign a value to the variable, use the equal sign:
carName = "Volvo";
You can also assign a value to the variable when you declare it:
let carName = "Volvo";
In the example below, we create a variable called carName and assign the value "Volvo" to it.
Then we "output" the value inside an HTML paragraph with id="demo":
Example
Note
It's a good programming practice to declare all variables at the beginning of a script.
One Statement, Many Variables
You can declare many variables in one statement.
Start the statement with let and separate the variables by comma:
Example
let person = "John Doe", carName = "Volvo", price = 200;
A declaration can span multiple lines:
Example
let person = "John Doe",
carName = "Volvo",
price = 200;
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.
A variable declared without a value will have the value undefined.
The variable carName will have the value undefined after the execution of this statement:
Example
let carName;
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 Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:
Example
let x = 5 + 2 + 3;
You can also add strings, but strings will be concatenated:
Example
let x = "John" + " " + "Doe"; --> John Doe
Also try this:
Example
let x = "5" + 2 + 3; --> 523
Note
If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated.
Now try this:
Example
let x = 2 + 3 + "5"; --> 55
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;
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".
JavaScript Underscore (_)
Since JavaScript treats underscore as a letter, identifiers containing _ are valid variable names:
Example
let _lastName = "Johnson";
let _x = 2;
let _100 = 5;
Using the underscore is not very common in JavaScript, but a convention among professional programmers is to use it as an alias for "private (hidden)" variables.
const
The const keyword was introduced in ES6 (2015)
Variables defined with const cannot be Redeclared
Variables defined with const cannot be Reassigned
Variables defined with const have Block Scope
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
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;
When to use JavaScript const?
Always declare a variable with const when you know that the value should not be changed.
Use const when you declare:
A new Array
A new Object
A new Function
A new RegExp
Constant Objects and Arrays
The keyword const is a little misleading.
It does not define a constant value. It defines a constant reference to a value.
Because of this you can NOT:
Reassign a constant value
Reassign a constant array
Reassign a constant object
But you CAN:
Change the elements of constant array
Change the properties of constant object
Constant Arrays
You can change the elements of a constant array:
Example
// You can create a constant array:
const cars = ["Saab", "Volvo", "BMW"];
// You can change an element:
cars[0] = "Toyota";
// You can add an element:
cars.push("Audi");
But you can NOT reassign the array:
Example
const cars = ["Saab", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"]; // ERROR
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"};
// You can change a property:
car.color = "red";
// You can add a property:
car.owner = "Johnson";
But you can NOT reassign the object:
Example
const car = {type:"Fiat", model:"500", color:"white"};
car = {type:"Volvo", model:"EX60", color:"red"}; // ERROR
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.
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:
Chrome 49 Edge 12 Firefox 36 Safari 11 Opera 36
Mar, 2016 Jul, 2015 Jan, 2015 Sep, 2017 Mar, 2016
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
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
}
Reassigning an existing const variable, in the same scope, is 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
}
Redeclaring a variable with const, in another scope, or in another block, is 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;
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.
Meaning: Using a const variable before it is declared will result in a ReferenceError:
Example
alert (carName);
const carName = "Volvo";
Javascript operators are used to perform different types of mathematical and logical computations.
Examples:
The Assignment Operator = assigns values
The Addition Operator + adds values
The Multiplication Operator * multiplies values
The Comparison Operator > compares values
There are different types of JavaScript operators:
Arithmetic Operators
Assignment Operators
Comparison Operators
String Operators
Logical Operators
Bitwise Operators
Ternary Operators
Type Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
Operator Example Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
**= x **= y x = x ** y
Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
All the comparison operators above can also be used on strings:
Note that strings are compared alphabetically:
JavaScript String Addition
The + can also be used to add (concatenate) strings:
Example
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
The += assignment operator can also be used to add (concatenate) strings:
Example
let text1 = "What a very ";
text1 += "nice day";
The result of text1 will be:
What a very nice day
Note
When used on strings, the + operator is called the concatenation operator.
Note
If you add a number and a string, the result will be a string!
&& logical and
|| logical or
! logical not
JavaScript Type Operators
Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type
JavaScript Bitwise Operators
Bit operators work on 32 bits numbers.
Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number.
Operator Description Example Same as Result Decimal
& AND 5 & 1 0101 & 0001 0001 1
| OR 5 | 1 0101 | 0001 0101 5
~ NOT ~ 5 ~0101 1010 10
^ XOR 5 ^ 1 0101 ^ 0001 0100 4
<< left shift 5 << 1 0101 << 1 1010 10
>> right shift 5 >> 1 0101 >> 1 0010 2
>>> unsigned right shift 5 >>> 1 0101 >>> 1 0010 2
The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed numbers.
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.
~00000000000000000000000000000101 will return 11111111111111111111111111111010
Bitwise operators are fully described in the JS Bitwise chapter.
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
Example
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}
JavaScript Function Syntax
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code
Automatically (self invoked)
You will learn a lot more about function invocation later in this tutorial.
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":
Example
Calculate the product of two numbers, and return the result:
// Function is called, the return value will end up in x
let x = myFunction(4, 3);
function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}
Why Functions?
With functions you can reuse code
You can write code that can be used many times.
You can use the same code with different arguments, to produce different results.
The () Operator
The () operator invokes (calls) the function:
Example
Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
Accessing a function without () returns the function and not the function result:
Local Variables
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables can only be accessed from within the function.
Example
// code here can NOT use carName
function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}
// code here can NOT use carName
Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the function is completed.