Knowledgebase

A rough introduction to JavaScript (JS) Print

  • internetivo, javascript, tutorial, vanillajs, web, services, technologies, development, design, developer, coder, programmer, syntax, boolean, basics, scripting
  • 0

How JavaScript aligns with other Web Technologies:

 

  1. HTML is for content
  2. CSS is for presentation
  3. JavaScript is for interactivity

 

  • validate user input in an HTML form before sending the data to a server;
  • build forms that respond to user input without accessing a server;
  • change the appearance of HTML documents and write data to browser Windows;
  • open and close new browser windows or frames;
  • build small but complete client-side programs.

Things you can do with JavaScript — Some examples:

  1. Validate User Input
  • Checking the values in input fields
  • Checking a Password
  • Checking numeric values

2. Forms that respond to user input without accessing a server

  • Forms that load a URL
  • Forms that calculate

3. Write information into HTML documents using Javascript Statements

  • Programmed output via document.write();
  • Adjust document colours
  • Change/rewrite images in a document

4. Open and Close Browser windows and Frames

  • Create new Browser windows with documents or programmed output

5. Build small but complete client-side programs

  • Calculators
  • Games

6. Control Robots

7. Control drones (IOT)

The <script> </script> tag

<html>
<head>
<title>The Script Tag 1</title>
<script>
document.write("<p>Script tags can be placed in the head of an HTML document.</p>");
</script>
</head>
<body>
<h1>The Script Tag: Example 1</h1>
<p>
Script tags can also be placed in the body of an HTML document.
</p>
<script>
document.write("<p>Script tags will be ignored by other browsers that do not understand them.</p>");
</script>
</body>
</html>

JavaScript syntax basics

Comments

Javascript supports single line and multi-line comments:

// Single and multi line comments.
// this is an example of a single line comment.

/*
* this is an example
* of a
* multi line
* comment.
*/

Whitespace

Whitespace is also ignored in JavaScript.

var hello = "Hello";

var world = "World!";

Here’s an example with whitespace added for readability:

var foo = function() {
for ( var i = 0; i < 10; i++ ) {
alert( i );
}
};
foo();

And the same code without whitespace. It much harder to read!

var foo=function() {for(var i=0;i<10;i++){alert(i);}};foo();

Reserved Words

There are a handful of reserved words that can’t be used when declaring user-defined variables and functions. Some of these reserved words are currently implemented, some are saved for future use, and others are reserved for historical reasons.

A list of words and in-depth explanations for each can be found on the Mozilla Developer Network JavaScript Reference site.

Identifiers

Identifiers are used to give variables and functions a unique name so they can subsequently be referred to by that name. The name of an identifier must follow a few rules:

  • Cannot be a reserved word.
  • Can only be composed of letters, numbers, dollar signs, and underscores.
  • The first character cannot be a number.

It’s best practice to name identifiers in a way that will make sense to you and other developers later on.

// Valid identifier names.
var myAwesomeVariable = "a";
var myAwesomeVariable2 = "b";
var my_awesome_variable = "c";
var $my_AwesomeVariable = "d";
var _my_awesome_variable_$ = "e";

Types

Types in JavaScript fall into two categories: primitives or objects. Primitive types include:

  • String
  • Number
  • Boolean
  • Null
  • Undefined

String

Strings are text wrapped in single or double quotation marks. It is best practice to consistently use one or the other. There may be times when the string contains quotation marks that collide with the ones used to create the string. In this case, either escape the characters using a \ backslash or use different quotes around the string.

Strings can be created with double or single quotes.

var a = "I am a string";
var b = 'So am I!';

alert( a );
alert( b );

Sometimes a string may contain quotation marks.

var statement1 = 'He said "JavaScript is awesome!"';
var statement2 = "He said \"JavaScript is awesome!\"";
var welcome = "Hello World";

After the assignment of the literal string "Hello World", the welcome is a string object.

result = welcome.length; //result is the number 11
result = welcome.toUpperCase(); //result is HELLO WORLD
result = welcome.toLowerCase(); //result is hello world
result = welcome.charAt( 0 ); //result is the character H
result = welcome.substring( 0, 5 ); //result is the string Hello
result = welcome.indexOf( "World", 0 ); //return is the number 6.
//If the string is not found indexOf returns -1

Number

Number types are any positive or negative numeric value. There is no distinction between integer and floating point values.

var num1 = 100;
var num2 = 100.10;
var num3 = 0.10;

JavaScript is a loosely typed language. Programmers used to strongly typed languages such as C++ or Java find this difficult to get used to. For example in C/C++/Java the following statements, including the integer division,

int result;
result = 5/10;

the result would equal 0. In JavaScipt there are no explicit integers or floating point numbers. “Unofficially,” you will get one or the other back.

result = 5/10;

the result would be assigned 0.5

JavaScript Precision

Integers are considered accurate up to 15 digits.

The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate:

var result;
result = 0.2 + 0.1; // result will be 0.30000000000000004

The solution to this problem depends on the type of problem you are dealing with. You can round the result, truncate it or work in a smaller unit.

Numbers in JavaScript are “double-precision 64-bit format IEEE 754 values”.

0.1 + 0.2 == 0.3; //false

You can use parseInt to convert Strings to “Integers”

parseInt("20", 10); //20

A special value, NaN (“Not a Number”) is returned if the string is non-numeric.

parseInt("ABC", 10) //NaN

Type Coercion

JavaScript uses type coercion whenever it needs to perform an operation on two operands that need to be the same type and are not.

8 == "8" // true

Relying on type coercion is not a good idea.

null == udefined   // true
false == undefined // false
false == "false" // false
'' == '0' // false
0 == '' // true
0 == '0' // true

To avoid type coercion, use the === and !== operators.

8 === "8"           // falsenull === udefined   // false
false === undefined // false
false === "false" // false
'' === '0' // false
0 === '' // false
0 === '0' // false

Boolean

Boolean types are either true or false.

var okay = true;
var fail = false;

Null and Undefined

Null and undefined are special types in JavaScript. Null types are a value that represent the absence of a value, similar to many other programming languages. Undefined types represent a state in which no value has been assigned at all. This type is created in two ways: by using the undefined keyword or by not defining a value at all.

// Achieve a null value
var foo = null;
// Two ways to achieve an undefined value.
var bar1 = undefined;
var bar2;

Objects

Everything else is in JavaScript is considered an Object. While there are numerous built-in objects, here we will cover:

  • Object
  • Array
  • Function

Conditional Statements

In JavaScript we have the following conditional statements:

  • if statement — use this statement to execute some code only if a specified condition is true
  • if…else statement — use this statement to execute some code if the condition is true and another code if the condition is false
  • if…else if….else statement — use this statement to select one of many blocks of code to be executed
  • switch statement — use this statement to select one of many blocks of code to be executed

If Statement

Use the if statement to execute some code only if a specified condition is true.

Syntax

if (condition) {
// code to be executed if condition is true
}

Example

if ( age < 16 ) {
entry = "free";
}

If…else Statement

Use the if….else statement to execute some code if a condition is true and another code if the condition is not true.

Syntax

if ( condition ) {
// code to be executed if condition is true
} else {
// code to be executed if condition is not true
}

Example

if ( age < 16 ) {
entry = "free";
} else {
entry = "£10";
}

If…else if….else Statement

Use the if….else if…else statement to select one of several blocks of code to be executed.

Syntax

if ( condition1 ) {
// code to be executed if condition1 is true
} else if ( condition2 ) {
// code to be executed if condition2 is true
} else {
// code to be executed if neither condition1 nor condition2 is true
}

Example

if ( age < 12 ) {
entry = "free";
} else if ( age < 18 ) {
entry = "£10";
} else {
entry = "£20";
}

Question

Are these equivalent and why?

if ( age < 12 ) {
entry = "free";
} else if ( age < 18 ) {
entry = "£10";
} else {
entry = "£20";
}
if ( age < 18 ) {
entry = "£10" ;
} else if ( age < 12 ) {
entry = "free";
} else {
entry = "£20";
}

The JavaScript Switch Statement

Syntax

switch( n ) {
case 1:
// execute code block 1
break;
case 2:
// execute code block 2
break;
default:
// code to be executed if n is different from case 1 and 2
}

Example

var day = new Date().getDay();
switch ( day ) {
case 0:
message = "Today is Sunday";
break;
case 1:
message = "Today is Monday";
break;
case 2:
message = "Today is Tuesday";
break;
case 3:
message = "Today is Wednesday";
break;
case 4:
message = "Today is Thursday";
break;
case 5:
message = "Today is Friday";
break;
case 6:
message = "Today is Saturday";
break;
}
document.write( message );

Example with default

var day = new Date().getDay();
switch ( day )
{
case 0:
message = "Today is Sunday";
break;
case 6:
message = "Today is Saturday";
break;
default:
message = "Looking forward to the weekend";
}
document.write( message );

Comparison Operators

Comparison operators are used in logical statements to determine equality or difference between variables or values.

 

Logical Operators

Logical operators are used to determining the logic between variables or values

 

JavaScript Loops

In JavaScript we have the following loops:

  • for — loops through a block of code a number of times
  • for/in — loops through the properties of an object
  • while — loops through a block of code while a specified condition is true
  • do/while — also loops through a block of code while a specified condition is true

The For Loop

The for loop is often the tool you will use when you want to create a loop.

Syntax

for (initial statement; boolean expression; statement) {
// the code block to be executed
}
  • initial statement This statment is executed before looping begins.
  • boolean expression This expression is evaluated to true or false. If true the loop is entered.
  • Statement This statement is executed at the end of each loop.

Example

for ( counter=0; counter < 10; counter++ ) {
document.write( "<p>" );
document.write( "Counter is: " + counter );
document.write( "<p>" );
}

The While Loop

The for loop is often the tool you will use when you want to create a loop.

Syntax

while ( boolean expression ) {
// the code block to be executed
}
  • boolean expression This expression is evaluated to true or false. If true the loop is entered.
  • Statement(s) Code block to be executed

Example

counter = 0;
while( counter < 10 ) {
document.write( "<p>" );
document.write( "Counter is: " + counter );
document.write( "</p>" );
counter++;
}

The Break Statement

The break statement breaks the loop and continues executing the code after the loop (if any):

Example

counter = 0;
while ( true ) { //potentially infinite loop
if ( counter > 5 ) break;
counter++;
}

The Continue Statement

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

Example

counter = 0;
while ( counter < 6 ) {
counter++;
if ( counter % 2 == 0 ) continue;
document.write( "Counter is now: " + counter );
}

JavaScript Dialog Boxes

alert();

Show a dialogue box with a message

Example

alert( "Your Message Goes Here!" );

confirm();

Show a dialogue box and return a boolean

Example

var answer = confirm( "Are you sure you want to close...." );
if ( answer == true ) {
alert( "You said OK!" );
} else {
alert( "You said Cancel!" );
}

prompt();

Show a dialogue box and return a string

Example

var answer = prompt( "Enter something here:", "anything will do" );
alert( "You said " + answer );

Line breaks in dialog boxes

To display line breaks inside a popup box, use a backslash followed by the character n.

Example

alert( "Hello,\nHow are you?" );

 

 

@Credits: Medium - The Geekiest One in Zero Equals False


Was this answer helpful?
Back