Osblog's JavaScript Corner: Your pocket JS code guide!

Words
988
Reading
5 min
Listen
Play
9y

Please refer to the official github repository of https://javascript.info here.

In this tutorial we will explore the concepts of JS code structure available here. We will try to explore in more detail and in terms a beginner can understand.

Why do you need this guide ?

In this article, we look at the nitty-gritties of the JavaScript programming language, albeit briefly and emphasis will be put on the key points. This guide will be beneficial to the new coder and the those coders who are switching from C, C++ or other programming languages to the JavaScript !

Lets Begin!

Code Structure

Separate statements within a code are marked out using semicolons:

alert('Hello’); alert ('World)

Alternatively, a line break can also be sued to set out the limits of a statement:

alert ('Hello’)
alert ('World)\

The above instance is known as an “automatic semicolon insertion”. However, this method is not guaranteed to work every time. For example:

alert ('There will be an error after this message)
[1, 2].forEach (alert)

The above code displays the first alert, but then proceeds to open an error message stating that it cannot read property '2’ of undefined.

Generally, it is a prerequisite for many to use semicolons as delimiters for statements within a code.

In the case of code blocks (enclosed within curly brackets {...}), semicolons are not an absolute necessity. For instance:

function f () { // no semicolon is required here
}
for
( ;;) { // semicolon is not necessary here
}

For the above codes, inserting a semicolon would not change the output. This is because semicolons that come after code blocks are always ignored during compilation.

Strict Mode

If a programmer need to enjoy full, unrestricted features of the richly-endowed modern JavaScript language, it is obligatory for them to start their scripts with “use strict”.

'use strict

Notably, the code might still work without implementing the “use strict” directive at the beginning of the code. However, this comes with its shortcomings, as some features – a considerable proportion, still perform in the obsolete compatibility mode.

A portion of new features, classes included, discreetly activate the strict mode without consent
from the programmer.

Variables

To declare variables, the following are used:

  • let

  • const ( this defines constant values that remain the same throughout)

  • var

The following rules guide the naming of variables:

  • It can consist of both digits and letter, though the first character must be a letter.

  • Special characters such as $ and _ are treated as letters.

  • Albeit being rarely used, non-Latin and hieroglyphic characters are also permitted.

Variables can store any data type, regardless of the value.

let x =5;
x = John;

There is a total of 7 data types available. These include:

  • number – this includes both fractions (floating-point) and whole numbers (integers).

  • string – a combination of characters

  • boolean – this defines logical values, which can either be true or false.

  • null – these are empty values which do not exist.

  • undefined – these are values without a designated data type assigned to them.

  • object

  • symbol

To establish the data type of a value, the typeof operator is used. This, however, does not work in all instances. For example:

typeof null == object // error in the language
typeof function () {} == function //functions are treated specially 

Interaction

Since the browser is acting as the integrated development environment in this case, the following functions form the core basis of the user interface:

prompt(question[, default])

The above function poses a question to the user, and return either the user’s answer or null if they opt to press “cancel” on the dialog box.

confirm(question)

This provides a close question, where the answer is either true or false, conventionally displayed as “Yes’ or “no”.

alert(message)

This will display the message entered within the function.

All of the above functions are modal, meaning that the site’s visitor cannot navigate further within the webpage until they respond to the query.

Operators

The following operastors are permitted in JavaScript;

Arithmetic

The four conventional signs +, -, *, and / are allowed. Additionally, ** is used for exponentials, while % is used to calculate quotients.

Where strings are involved, the + sign is used to concatenate them. If only one of the operands is a string while the other(s) is/are, the rest of the operands are implicitly converted into strings.

For instance:

alert( '1’+ 2); //’12’ . string
alert( 1 + '2); //’12’ . string

Assignments
These can either be simple e.g. a=b or combined e.g. a*=2

Bitwise
These work with integers at the simplified bit-level, as their name suggests.

Ternary
These have three parameters, where one is a condition, and the other two are statements.

cond? resultA: resultB

If the cond is true, resultA is returned, otherwise, resultB returns.

Logical operators

They are two, AND && and OR ||. They evaluate a statement and return the result if conditions are met.

Comparisons

This compares the equality of two values, regardless of data type, and returns either true or false.

All values are converted into numbers, with the exception of null and undefined, as they equal each other.

alert( 0 ==false); //true
alert(0 == '); // true

On the other hand, if the strict equality operator === is used, conversion does not occur, and are values are treated differently.

Greater than and less than comparisons convert all data types into numbers except strings, which are paralleled character-by-character.

Loops

There are three types of loops in JavaScript:

  • the while loop
while (condition) {
}
  • the do while loop
do{
} while (condition);
  • for loop
for(let I =0; i< 10; i++) {
}

To exit from a loop, the break and continue directives are used.

The “switch” construct

Instead of using nested if, one can opt for the “switch” construct. The strict equality operator === is used for comparison in this case.

let age = prompt ('Your Age?, 18);
switch (age) {
case 18: alert( Wont work); // the result of this prompt is a string, not a number
case 18: alert(This works!);
beak; 
default: alert(Any value not equal to one above);
}

Functions

In JavaScript, functions are defined in three different formats:

  • Function Declaration

The functions appears in the main code block.

function sum(a, b) {
let result = a + b;
return result:
}
  • Function Expression

The functions appears as an expression.

let sum = function(a, b) {
let result = a + b;
return result:
}

Here, a function may have a specific name like sum, which is only visible within the function itself.

  • Arrow functions
// expression at theright side
let sum = (a, b) => a+ b;
// or multi-line syntax with { … }, need return here:
let sum = (a, b) => {
//..
return a + b;
}
// without arguments
let sayHi = () =>alert(Hello);
// with a single argument
let double = n => n *2;

Below is a brief recap of functions:

  • They can have local variables, which are located and only visible from within the functions themselves

  • Their parameters can have default values,e.g. sum(a=1, b=2)

  • They always return a value, even if it is undefined.

Wait for more installments of Osblog's JavaScript Corner for more such tutorials! Till then, bye bye!



Posted on Utopian.io - Rewarding Open Source Contributors

Osblog's JavaScript Corner: Your pocket JS code guide! | Ecency