Basics

I. Syntax

1. semi-colons;

In Javascript, every expression needs a semi-colon at the end.

An expression is a line of code that returns a value. Statements that are not expressions don’t need semi-colons.

// variable is expression
const x = 2;

// function is statement
function hello() {}

if (x > 1) { // if is statement
    console.log("Hello World"); // console.log is expression
}

2. { curly braces }

Curly braces identify JS objects and code blocks such as functions, conditional statements, loops.

// function
function hello() {}

// if
if (condition) {
    // code...
}

// loop
for (condition) {
    // code...
}

// JS object
const obj = { key: "value" }

3. console.log

The console is a panel that displays important messages.

Data can be printed, or logged to the console with console.log().

> console.log('hello')
hello

4. Comments

Comments can explain what the purposes, leave instructions for other developers, or add any other useful annotations.

We can write single-line comments with // and multi-line comments between /* and */

// this is a single-line comment

/*
  this is
  a multi-line
  comments
*/

5. JavaScript is Case Sensitive

All JavaScript identifiers are case sensitive.

For example, the variables lastName and lastname are two different variables.

Arithmetic Operators

Arithmetic Operators perform mathematical calculations on numbers. The built-in arithmetic operators include:

  • + addition
  • - subtraction
  • * multiplication
  • / division
  • % modulo

Comparison operators

Javascript comparison operators includes the following

  • >
  • <
  • >=
  • <=
  • ===
  • !==

Logical operators

  • &&: and
  • ||: or
  • !: not

the <script> element allows HTML files to load and execute JavaScript.

The JavaScript can either go embedded inside of the <script> tag or the script tag can reference an external file.

<head>
    <link rel="stylesheet" href="style.css">
    <script src="./script.js"></script>
</head>

Scripts are loaded sequentially, so if one script depends on another script, they should be placed in that very order inside the HTML file.

defer attribute

The defer attribute specifies scripts should be executed after the HTML file is completely parsed.

When the HTML parser encounters a <script> element with the defer attribute, it loads the script but defers the actual execution of the JavaScript until after it finishes parsing the rest of the elements in the HTML file.

Here is an example of the defer tag:

<script src="example.js" defer></script>

async attribute

The async attribute loads and executes the script asynchronously with the rest of the webpage.

Different from defer, async will execute immediately after it has been downloaded.

async is useful for scripts that are independent of other scripts in order to function accordingly.

<script src="example.js" async></script>