JavaScript Basis: Syntax & Structure

February 08, 2019 0 Comments

JavaScript Basis: Syntax & Structure

 

 

Programming languages are defined by rules. The syntax is what we follow when we write our code, which forms the logical structure of our programs.

Let's dive right into the basic components of JavaScript. We will look at values, unicode, semi-colon, indentation, white spacing, commentary, case sensitivity, keywords..ect.

By taking the time to learn the basics, we will be well on our way to building more functional and readable code.

JavaScript: the Values

There are two types of values in JavaScript: Fixed values( or literals) and variables.

Literals

Literals are defined as values written in our code, such as numbers, strings, booleans, as well as literals for objects and arrays.

Examples:

18 // A number 'Toy' // A string (can be in double "" or single '' quotes) false // A boolean (can be true or false) ['a', 'b'] // An array {color: 'red', shape: 'Circle'} // An object

Variables

Variables are named values that store data. We declare our variables with the var, let or const keywords and assign values with the sign =.

For instance, the key is defined as a variable.

const key;
key = pluto;

Important:

Don’t use var. It should be used when you working with legacy code. It's the old pre-ES6 syntax.

Use let it if your variable needs to be updated within the program.

Use const it if your variable holds a constant value. It cannot be updated.

Camel Case

What if more than one word is our variable name? How do we declare a variable we need to name "first-item" for example?

We can't use hyphens such as "first-item" just because they are reserved for JavaScript subtractions.

Underscores such us first_name? We coul... but it has a tendency to make our code look messy and confusing.

What solution do we propose?

camel case! e.g. firstItem.

The first word is lower-case, the first letter of any subsequent words are upper-case. 

 

Unicode

JavaScript uses a set of characters with unicode. Unicode covers almost all the characters, punctuations and symbols!. This is great because we can write our names in any language and even emojis can be used as variable names

Semicolons

JavaScript programs are built up with instructions known as statements. Such as:

  
let a = 500;
a = b + c;
const time = Date.now(); 

JavaScript statements often end in a semicolon ;. But semicolons aren’t always mandatory! JavaScript does not have any issues if you don’t use them.

// valid!
let a = 500
a = b + c
const time = Date.now()

But again, there are some situations in which they are obligatory. For example, when we use a for loop, such as:

for (i = 0; i < .length; i++) { } 

When using a block statement however, semicolons are not to be included after the curly braces, for example:

if (name == "Silvia") { // code } // <- no ';'
//or,
function people(name) { // code } // <- no ';'

If we’re using an object however, like:

const person = { firstName: "Silvia", lastName: "Brown", age: 30, eyeColor: "green" }; // the ';' is mandatory

Indentation

Technically, we could write a whole program of JavaScript on one line. But itwould be almost impossible to read and maintain. That's why lines and indentation are used. The conditional statement can be used as an example:

if (loginSuccessful === 1) { // run code } else { // abort }

By applying indentation we’ll have a code cleaner, more maintainable and readable! Look:

if (loginAttempts < 5){ if (loginAttempts < 3){ alert("< 3"); } else { alert("between 3 and 5"); } } else { if (loginAttempts > 10){ alert("> 10"); } else { alert("between 5 and 10"); } }

 

White Space

JavaScript requires only one space between keywords, names, and identifiers, or any white space will be completely ignored. This means that there is no difference in the language between the following statements:

const visitedCities="Rome, "+"Florence, "+"Venice"; const visitedCities = "Rome, " + "Florence, " + "Venice";

Don't tou think the second one's more readable?

Another example:

let x=1*y; let x = 1 * y; 

Again, the second line is much easier to read and debug!

 

Commenting

A comment is code which can not be executed. They are useful for illustrating some code in a program. And also to' comment' on a code section to prevent execution- often used to test an alternative piece of code. JavaScript has two types of comments:

// Comment goes here
/* Comment goes here */

When writing code you may have some complex logic that is confusing, this is a perfect opportunity to include some comments in the code that will explain what is going on. Not only will this help you remember it later on, but if you someone else views your code, they will also be able to understand the code (hopefully)!

 

Identifiers

JavaScript Identifiers are names given to variables, functions, etc.

While naming your variables in JavaScript, keep the following rules in mind.

  1. You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.
  2. JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 5demo is an invalid variable name but _5demo is a valid one.
  3. JavaScript variable names are case-sensitive. For example, Name and name are two different variables.

Examples:

// Valid :)
Name name NAME _name Name1 $name
// Invalid :(
1name [email protected] name! 

 

Case Sensitivity

JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters. The while keyword, for example, must be typed “while”, not “While” or “WHILE”. Similarly, online, Online, OnLine, and ONLINE are four distinct variable names.

The following will throw an error:

function test() { alert("This is a test!"); }
function show_alert() { Test(); // error! test(); is correct }

Reserved Words

What reserved words are there in JavaScript?

 Reserved words of the JavaScript langauge are listed below. (Some of these words are actually used in the Java language, and are reserved in JavaScript for compatibility purposes or as possible extensions.) When choosing names for your JavaScript variables, avoid these reseved words!

break, do, instanceof, typeof, case, else, new, var, catch, finally, return, void, continue, for, switch, while, debugger, function, this, with, default, if, throw, delete, in, try, class, enum, extends, super, const, export, import.

See the full list of reserved keywords.

JavaScript Operators

Operators in JavaScript are very similar to operators that appear in other programming languages. The definition of an operator is a symbol that is used to perform an operation. Most often these operations are arithmetic (addition, subtraction, etc), but not always.

Arithmetical operators + - * and / are primarily used when performing calculations within JavaScript, such as

(2 + 2) * 100

The assignment operator = is used to assign values to our variables

JavaScript Expressions

Expressions are units of code that can be evaluated and resolve to a value. Expressions in JS can be divided in categories.;

  • Arithmetic expressions
  • String expressions
  • Primary expressions
  • Array and object initializers expressions
  • Logical expressions
  • Left-hand-side expressions
  • Property access expressions
  • Object creation expressions
  • Function definition expressions
  • Invocation expressions

ARITHMETIC EXPRESSIONS

Under this category go all expressions that evaluate to a number:

1 / 2 i++ i -= 2 i * 2 

STRING EXPRESSIONS

Expressions that evaluate to a string:

'A ' + 'string' 'A ' += 'string' 

PRIMARY EXPRESSIONS

Under this category go variable references, literals and constants:

2 0.02 'something' true false this //the current object undefined i //where i is a variable or a constant 

but also some language keywords:

function class function* //the generator function yield //the generator pauser/resumer yield* //delegate to another generator or iterator async function* //async function expression await //async function pause/resume/wait for completion /pattern/i //regex () // grouping 

ARRAY AND OBJECT INITIALIZERS EXPRESSIONS

[] //array literal {} //object literal [1,2,3] {a: 1, b: 2} {a: {b: 1}} 

LOGICAL EXPRESSIONS

Logical expressions make use of logical operators and resolve to a boolean value:

a && b a || b !a 

LEFT-HAND-SIDE EXPRESSIONS

new //create an instance of a constructor super //calls the parent constructor ...obj //expression using the spread operator 

PROPERTY ACCESS EXPRESSIONS

object.property //reference a property (or method) of an object object[property] object['property'] 

OBJECT CREATION EXPRESSIONS

new object() new a(1) new MyRectangle('name', 2, {a: 4}) 

FUNCTION DEFINITION EXPRESSIONS

function() {} function(a, b) { return a * b } (a, b) => a * b a => a * 2 () => { return 2 } 

INVOCATION EXPRESSIONS

The syntax for calling a function or method

a.x(2) window.resize() 

Conclusion

This article was intended to provide an overview of JavaScript 's basic syntax and structure. We have looked at many of the common conventions, but remember that you can be somewhat flexible-especially when you work with your own specific standards in collaborative work environments.

Syntax and structuring play an important role both in the functionality of our programs and in the readability and maintenance of codes.

We hope you found this article useful!


Tag cloud