Example

Variables can be defined in several ways. In the older ES6 version, variable is defined using the var keyword[1]. In the newer versions after ES6, variable can be defined using const for constant variables and let for local variables [2][3]. The value of the constant variable cannot be re-declared or re-assigned. Local variables are declared inside the block scope.

//ES6
var x = 1; // defines the variable x and assigns the value 1 to the variable.

//ES6+
const y = 10; // defines the constant varialbe y and assigns the value 10 to the variable. 
let t = 5; // defines the local varialbe t and assigns the value 5 to the variable.

The script below prints "Example" on the screen. The lines that start with// are comments; comments explain the purpose of the codes.[4]

<script type="text/javascript">
function example()
{
    var ex = document.createTextNode('Example'); //make the computer remember "Example", 
                                                 //so whenever you say "ex" the computer will append it with "Example"
    document.body.appendChild(ex);               //put the text on the bottom of the webpage
}
example();

/*
 * The code below does almost the same thing as the code above, 
 * but it shows "Example" in a popup box and is shorter.
 *
 * This is a comment too, by the way.
 */

alert("Example");
</script>

The JavaScript is enclosed by <script></script> html tags. The html tags indicate that it is a script and not text to be put onto the web page the JavaScript is running on. The script below inserts the numbers 1 through 10 at the bottom of a webpage:

<script type="text/javascript">
for(var numOfTimesAround = 1; numOfTimesAround <= 10; numOfTimesAround++){

document.body.innerHTML = document.body.innerHTML + numOfTimesAround + "<br>";
/*
* This puts the number, then a new line, at the end of the web page.
* In javascript, using the + sign combines two words together.
* So writing "Hello" + " World" would make "Hello World".
* Or, writing 1 + "<br>" makes "1<br>", which is what we want.
*/

}

</script>

The for() loop makes whatever code is between the { and the } happen more than one time. In this case, it keeps looping until numOfTimesAround is equal to 10, then it stops.

Differences between Java and Javascript

function sayHi(){
alert("hi!");
}
sayHi = function(){
alert("Bye!");
}
sayHi();
//alerts "Bye!" instead of "hi!" without giving an error

References

  1. "var". MDN Web Docs. Retrieved 2018-03-24.
  2. "const". MDN Web Docs. Retrieved 2018-03-24.
  3. "let". MDN Web Docs. Retrieved 2018-03-24.
  4. [1]

Other websites