Thursday, May 5, 2016

JavaScript Syntax


JavaScript syntax is the set of rules, how JavaScript programs are constructed.

JavaScript Programs

computer program is a list of "instructions" to be "executed" by the computer.
In a programming language, these program instructions are called statements.
JavaScript is a programming language.
JavaScript statements are separated by semicolons.

Example

var x = 5;
var y = 6;
var z = x + y;
NoteIn HTML, JavaScript programs can be executed by the web browser.

JavaScript Statements

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

JavaScript Values

The JavaScript syntax defines two types of values: Fixed values and variable values.
Fixed values are called literals. Variable values are called variables.

JavaScript Literals

The most important rules for writing fixed values are:
Numbers are written with or without decimals:
10.50

1001
Strings are text, written within double or single quotes:
"John Doe"

'John Doe'

JavaScript Variables

In a programming language, variables are used to store data values.
JavaScript uses the var keyword 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:
var x;

x = 6;

JavaScript Operators

JavaScript uses an assignment operator ( = ) to assign values to variables:
var x = 5;
var y = 6;
JavaScript uses arithmetic operators ( + - *  / ) to compute values:
(5 + 6) * 10

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:
Expressions can also contain variable values:
x * 10
The values can be of various types, such as numbers and strings.
For example, "John" + " " + "Doe", evaluates to "John Doe":
"John" + " " + "Doe"

JavaScript Keywords

JavaScript keywords are used to identify actions to be performed.
The var keyword tells the browser to create a new variable:
var x = 5 + 6;
var y = x * 10;

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:
var x = 5;   // I will be executed
// var x = 6;   I will NOT be executed

JavaScript Identifiers

Identifiers are names.
In JavaScript, identifiers are used to name variables (and keywords, and functions, and labels).
The rules for legal names are much the same in most programming languages.
In JavaScript, the first character must be a letter, an underscore (_), or a dollar sign ($).
Subsequent characters may be letters, digits, underscores, or dollar signs.
NoteNumbers are not allowed as the first character.
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.
lastName = "Doe";
lastname = "Peterson";
JavaScript does not interpret VAR or Var as the keyword var.

JavaScript and Camel Case

Historically, programmers have used three ways of joining multiple words into one variable name:
Hyphens:
first-name, last-name, master-card, inter-city.
Underscore:
first_name, last_name, master_card, inter_city.
Camel Case:
FirstName, LastName, MasterCard, InterCity.
camelCase
In programming languages, especially in JavaScript, camel case often starts with a lowercase letter:
firstName, lastName, masterCard, interCity.
NoteHyphens are not allowed in JavaScript. It is reserved for subtractions.

JavaScript Output


JavaScript does NOT have any built-in print or display functions.

JavaScript Display Possibilities

JavaScript can "display" data in different ways:
  • Writing into an alert box, using window.alert().
  • Writing into the HTML output using document.write().
  • Writing into an HTML element, using innerHTML.
  • Writing into the browser console, using console.log().

Using window.alert()

You can use an alert box to display data:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

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

</body>
</html>

Using document.write()

For testing purposes, it is convenient to use document.write():

Example

<!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 fully loaded, will delete all existing HTML:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<button onclick="document.write(5 + 6)">Try it</button>

</body>
</html>
NoteThe document.write() method should be used only for testing.

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:

Example

<!DOCTYPE html>
<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>
NoteTo "display data" in HTML, (in most cases) you will set the value of an innerHTML property.

Using console.log()

In your browser, you can use the console.log() method to display data.
Activate the browser console with F12, and select "Console" in the menu.

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
console.log(5 + 6);
</script>

</body>
</html>

JavaScript Introduction



JavaScript is the most popular programming language in the world.
This page contains some examples of what JavaScript can do.

JavaScript Can Change HTML Content

One of many HTML methods is getElementById().
This example uses the method to "find" an HTML element (with id="demo"), and changes the element content (innerHTML) to "Hello JavaScript":

Example

document.getElementById("demo").innerHTML = "Hello JavaScript";


JavaScript Can Change HTML Attributes

This example changes an HTML image, by changing the src attribute of an <img> tag:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Can Change Images</h1>

<img id="myImage" onclick="changeImage()" src="pic_bulboff.gif" width="100"height="180">

<p>Click the light bulb to turn on/off the light.</p>

<script>
function changeImage() {
    var image = document.getElementById('myImage');
    if (image.src.match("bulbon")) {
        image.src = "pic_bulboff.gif";
    } else {
        image.src = "pic_bulbon.gif";
    }
}
</script>

</body>
</html>

JavaScript Can Change HTML Styles (CSS)

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

Example

document.getElementById("demo").style.fontSize = "25px";

JavaScript Can Validate Data

JavaScript is often used to validate input:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Can Validate Input</h1>

<p>Please input a number between 1 and 10:</p>

<input id="numb">

<button type="button" onclick="myFunction()">Submit</button>

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

<script>
function myFunction() {
    var x, text;

    // Get the value of the input field with id="numb"    x = document.getElementById("numb").value;

    // If x is Not a Number or less than one or greater than 10    if (isNaN(x) || x < 1 || x > 10) {
        text = "Input not valid";
    } else {
        text = "Input OK";
    }
    document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html> 

Did You Know?

NoteJavaScript and Java are completely different languages, both in concept and design.
JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
ECMA-262 is the official name. ECMAScript 6 (released in June 2015) is the latest official version of JavaScript.

CSS Colors

Colors are displayed combining RED, GREEN, and BLUE light.

Colors in CSS are most often specified by:
  • a valid color name - like "red"
  • an RGB value - like "rgb(255, 0, 0)"
  • a HEX value - like "#ff0000"

Color Names

Colors set by using color names:

Example

ColorName
 Red
 Green
 Blue
 Orange
 Yellow
 Cyan
 Black
Note: Color names are case-insensitive: "Red" is the same as "red" or "RED".

RGB (Red, Green, Blue)

RGB color values can be specified using this formula: rgb(red, green, blue).
Each parameter (red, green, blue) defines the intensity of the color between 0 and 255.
For example, rgb(255,0,0) is displayed as red, because red is set to its highest value (255) and the others are set to 0. Experiment by mixing the RGB values below:
RedGreenBlue
25500
rgb(255, 0, 0)

Example

ColorRGB
 rgb(255,0,0)
 rgb(0,255,0)
 rgb(0,0,255)
 rgb(255,165,0)
 rgb(255,255,0)
 rgb(0,255,255)
Shades of grey are often defined using equal values for all the 3 light sources:

Example

ColorRGB
 rgb(0,0,0)
 rgb(128,128,128)
 rgb(255,255,255)

Hexadecimal Colors

RGB values can also be specified using hexadecimal color values in the form: #RRGGBB, where RR (red), GG (green) and BB (blue) are hexadecimal values between 00 and FF (same as decimal 0-255).
For example, #FF0000 is displayed as red, because red is set to its highest value (FF) and the others are set to the lowest value (00). Note: HEX values are case-insensitive: "#ff0000" is the same as "FF0000".

Example

ColorHEX
 #FF0000
 #00FF00
 #0000FF
 #FFA500
 #FFFF00
 #00FFFF
Shades of grey are often defined using equal values for all the 3 light sources:

Example

ColorHEX
 #000000
 #808080
 #FFFFFF