JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
One of many JavaScript HTML methods is getElementById() .
JavaScript can change HTML attribute values.
In this example JavaScript changes the value of the src (source) attribute of an image:
<button onclick="document.getElementById('myImage').src='img/pic_bulbon.gif'">Turn on the light</button>
<img id="myImage" src="img/pic_bulboff.gif" style="width:100px">
<button onclick="document.getElementById('myImage').src='img/pic_bulboff.gif'">Turn off the light</button>
JavaScript can change the style of an HTML element.
<p id="txt_size"> JavaScript can change the style of an HTML element. </p>
<button type="button" onclick="document.getElementById('txt_size').style.fontSize='8px'"> 8 px </button>
<button type="button" onclick="document.getElementById('txt_size').style.fontSize='16px'"> 16 px </button>
<button type="button" onclick="document.getElementById('txt_size').style.fontSize='32px'"> 32 px </button>
<button type="button" onclick="document.getElementById('txt_size').style.fontSize='64px'"> 64 px </button>
JavaScript can hide / show HTML elements.
<p id="hide"> JavaScript can hide / show HTML elements. </p>
<button type="button" onclick="document.getElementById('hide').style.display='none'"> hide </button>
<button type="button" onclick="document.getElementById('hide').style.display='block'"> show </button>
In HTML, JavaScript code is inserted between <script> & </script> tags.
Scripts can be placed in the body, or in the head section of an HTML page, or in both.
Scripts can also be placed in an external file with extension .js with the code: <script src="myScript.js"> </script>
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
JavaScript Functions
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.
<script>
function myFunction_001() {document.getElementById("demo").innerHTML = "you pressed the button function 1";}
function myFunction_002() {document.getElementById("demo").innerHTML = "you pressed the button function 2";}
function myFunction_003() {document.getElementById("demo").innerHTML = "TEST THESE FUNCTIONS";}
</script>
<p id="demo">TEST THESE FUNCTIONS </p>
<button type="button" onclick="myFunction_001()"> function 1 </button>
<button type="button" onclick="myFunction_002()"> function 2 </button>
<button type="button" onclick="myFunction_003()"> reset </button>
TEST THESE FUNCTIONS
JavaScript can "display" data in different ways:
writing into an HTML element, using innerHTML.
<p id="demo"> </p> <script> document.getElementById("demo").innerHTML = 5 + 6; <script>
writing into the HTML output using document.write().
<script> document.write(5 + 6); <script>
note: if you call document.write after the document has finished loading, it will overwrite the whole document.
<button type="button" onclick="document.write(5 + 6)"> Try it </button>
writing into an alert box, using window.alert().
<script> window.alert(5 + 6); <script>
note: you can also avoid mentioning the word "window", since in javascript the window object is the global scope object:
<script> alert(5 + 6); <script>
writing into the browser console, using console.log().
<button type="button" onclick="console.log(5 + 6)"> Try it </button>
press F12, select console in the debugger menu and
printing the content of the current window, using the method window.print().
<button onclick="window.print()"> Print this page </button>
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 .
JavaScript statements are composed of values, operators, expressions, keywords, and comments.
Semicolons separate JavaScript statements.
Ending statements with semicolon is not required, but highly recommended.
The statements are executed, one by one, in the same order as they are written.
JavaScript ignores multiple spaces. You can add white space to your script to make it more readable.
A JavaScript program is a list of programming statements to be executed by a computer.
<p id="tot"> </p>
<script>
var x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
document.getElementById("tot").innerHTML = "The value of z is " + z + ".";
</script>
JavaScript Code Blocks
JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
The purpose of code blocks is to define statements to be executed together.
One place you will find statements grouped together in blocks, is in JavaScript functions
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be performed.
JavaScript keywords are reserved words. Reserved words cannot be used as names for variables.
Here is a list of some of the keywords :
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript, and calls (if available) the debugging function
do ... while Executes a block of statements, and repeats the block, while a condition is true
for Marks a block of statements to be executed, as long as a condition is true
function Declares a function
if ... else Marks a block of statements to be executed, depending on a condition
return Exits a function
switch Marks a block of statements to be executed, depending on different cases
try ... catch Implements error handling to a block of statements
var Declares a variable
etc...
JavaScript Syntax
JavaScript uses the Unicode character set.
JavaScript syntax is the set of rules, how JavaScript programs are constructed.
The JavaScript syntax defines two types of values:
Fixed values (called Literals)
The most important syntax rules for literals valuse are:
numbers are written with or without decimals
strings are text, written within double or single quotes
Variable values (called Variables)
variables must be declared using the keyword "var"
Example: var carName;
after the declaration, the variable is empty.
a value must be assigned with the assignment operator "="
carName = Volvo;
you can also assign a value to the variable when you declare it:
var carName = Volvo;
it's a good programming practice to declare all variables at the beginning of a script
you can declare multiple variables in a unique statement:
var person = "John Doe", carName = "Volvo", price = 200;
if you declare again the same variable it will maintain its value:
var carName = "Volvo";
var carName;
if you add values they will be added
var x = 5 + 2 + 3; = 8
if you add strings they will be concatenated:
var y = "Mario" + " " + "Rossi"; = Mario Rossi
if you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated:
var a = "5" + 2 + 3 + 7; = 523
var b = 2 + 3 + "5" + 7; = 557
Variables declared Globally (outside any function) have Global Scope and can be accessed from anywhere in a JavaScript program, also within functions.
Variables declared Locally (inside a function) have Function Scope.
Variables declared inside a simple "block" { } with the var keyword cannot have Block Scope.
Variables declared inside a simple "block" { } with the let keyword can have Block Scope.
note: the let keyword is not fully supported in Internet Explorer 11 or earlier.
Variables declared inside a loop with the let keyword have Loop Scope.
let i = 5; for (let i = 0; i < 10; i++) { // some statements}
// here i is 5
Variables declared inside a loop with the var keyword cannot have Loop Scope.
var i = 5; for (var i = 0; i < 10; i++) { // some statements}
// here i is 10
Variables var and let are quite similar when declared inside a function
Variables var and let are quite similar when declared outside a block (or a loop)
Global variables defined with the var keyword belong to the window object
Global variables defined with the let keyword cannot belong to the window object
Variables defined with var are hoisted to the top and can be initialized also before they are declared
Variables defined with let are hoisted to the top of the block, but can't be initialized until the variable is declared
Variables defined with const behave like let, but they can't be reassigned
JavaScript uses arithmetic operators to compute values:
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
JavaScript uses an assignment operator ( = ) to assign values to variables
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
The "equal to" operator is written like == in JavaScript.
The comparison operators:
== 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
The logical operators:
&& logical and
|| logical or
! logical not
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.
The values can be of various types, such as numbers and strings.
For example, "Mario" + " " + "Rossi", evaluates to "Mario Rossi"
Identifiers are names used to name variables, and keywords, functions and labels.
In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign ($).
Subsequent characters may be letters, digits, underscores, or dollar signs.
All JavaScript identifiers are case sensitive.
Hyphens (like first-name) are not allowed in JavaScript. They are reserved for subtractions.
JavaScript programmers tend to use camel case that starts with a lowercase letter (like firstName)
JavaScript arrays are written with square brackets.
var cars = ["Saab", "Volvo", "BMW"];
JavaScript objects are written with curly braces {}.
Object properties are written as name:value pairs, separated by commas.
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};