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 an expression.
const x = 2;

// function is a 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, and 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 the purposes, leave instructions for other developers, or add 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

II. Comparison operators

Javascript comparison operators include the following.

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

III. Logical operators

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

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

JavaScript can be 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.

1. defer attribute

The defer attribute specifies scripts that 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. Still, it defers the actual execution of the JavaScript until 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>

2. 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 to function accordingly.

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