2022-02-18

JavaScript Basic Syntax

JavaScript Syntax

JavaScript syntax refers to the set of rules that dictate how programs written in JavaScript should be structured.

Statements

In JavaScript, a statement is a piece of code that performs an action. Statements are often terminated with a semicolon (;). For example:

js
let x = 5;

In this example, let x = 5; is a statement which declares a variable x and assigns the value 5 to it.

Expressions

An expression is any valid unit of code that resolves to a value. Expressions can include variables, literals, operators, and function calls. For example:

js
x * 10;

Identifiers

Identifiers are names. In JavaScript, identifiers are used to name variables, functions, and labels. There are certain rules when naming identifiers:

  • Identifiers can contain letters, digits, underscores, and dollar signs.
  • Identifiers cannot start with a digit.
  • Identifiers are case-sensitive (myVar and myvar are different identifiers).
  • Reserved words (like JavaScript keywords) cannot be used as identifiers.

Keywords

Keywords are reserved words in JavaScript that have special meanings. They are used to control the flow of a program (like if, else, for, while), declare variables (like let, const, var), define functions (like function), and more. Keywords cannot be used as identifiers.

Comments

Comments are used to explain the code and make it more understandable. They don't affect the execution of the code. JavaScript supports both single-line and multi-line comments.

Single-line comments start with two forward slashes (//):

js
// This is a single-line comment

Multi-line comments start with a forward slash and an asterisk (/_), and end with an asterisk and a forward slash (_/):

js
/*
This is a
multi-line comment
*/

Variables

Variables are fundamental to any programming language. In JavaScript, a variable is a symbolic name for a value. Variables are used to store data, which can then be manipulated and referenced throughout your program.

Variable Declaration

In JavaScript, you can declare variables using var, let, or const. Each of these keywords has different characteristics:

  • var: This keyword declares a variable, optionally initializing it to a value.
js
var name;
  • let: This keyword declares a block-scoped local variable, optionally initializing it to a value.
js
let name;
  • const: This keyword declares a block-scoped, read-only named constant.
js
const name = 'John';

Note that const requires initialization; you cannot declare a const variable without assigning a value to it immediately.

Variable Assignment

After declaring a variable, you can assign a value to it using the assignment operator (=).

js
let name;
name = 'John';

You can also declare and assign a value to a variable at the same time.

js
let name = 'John';

Variable Scope

The scope of a variable determines where it can be accessed within your code. JavaScript has two types of scope: global scope and local scope.

  • Global Scope: A variable declared outside a function or declared with the var keyword inside a function becomes a global variable and can be accessed from any part of the code.
js
var globalVar = 'I am global!';
  • Local Scope: A variable that is declared inside a function or block is local to that function or block. It cannot be accessed from outside the function or block.
js
function myFunction() {
  let localVar = 'I am local!';
}

However, let and const declared inside a block {} are block-scoped, meaning they can only be accessed within the nearest enclosing block.

js
{
  let blockVar = 'I am block-scoped!';
}

Data Types

In JavaScript, data types refer to the different kinds of data that can be manipulated within a program. JavaScript has a dynamic type system, meaning a variable can hold a value of any data type and can change its type during execution.

Primitive Data Types

Primitive data types in JavaScript include Number, String, Boolean, Null, Undefined, and Symbol.

  • Number: This data type represents both integer and floating-point numbers. For example:
js
let num1 = 25;  // an integer
let num2 = 80.5;  // a floating-point number
  • String: This data type represents a sequence of characters. Strings can be created by enclosing characters in single quotes (''), double quotes (""), or backticks (``). For example:
js
let str1 = 'hello';  // using single quotes
let str2 = "world";  // using double quotes
let str3 = `hello world`;  // using backticks
  • Boolean: This data type represents logical values. It can only take the values true or false. For example:
js
let isReading = true; // yes, I'm reading
let isSleeping = false; // no, I'm not sleeping
  • Null: This data type represents the intentional absence of any object value. It is often used to indicate "no value" or "unknown". For example:
js
let empty = null;
  • Undefined: A variable that has been declared but has not been assigned a value is undefined. For example:
js
let x;
console.log(x);  // output: undefined
  • Symbol: Introduced in ECMAScript 6, a Symbol is a unique and immutable primitive value and may be used as the key of an Object property. For example:
js
let symbol1 = Symbol();
let symbol2 = Symbol('sym2');

Complex Data Types

In addition to the primitive data types, JavaScript also has complex data types, which are Objects and Arrays.

  • Object: An object is a collection of properties where each property is a key-value pair. The keys in objects are strings, whereas the values can be any data type. For example:
js
let person = {
  name: 'John',
  age: 30
};
  • Array: An array is a special type of object that represents a collection of elements. The elements in an array can be of any data type. For example:
js
let fruits = ['apple', 'banana', 'cherry'];

Operators

Operators in JavaScript are symbols that tell the compiler to perform specific mathematical, relational, or logical operations. In this chapter, I'll explore the various types of operators available in JavaScript.

Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on numbers. They include:

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
  • Modulus (Remainder) (%)
  • Increment (++)
  • Decrement (--)

For example:

js
let a = 10;
let b = 20;

console.log(b + a);  // Output: 30
console.log(b - a);  // Output: 10
console.log(b * a);  // Output: 200
console.log(b / a);  // Output: 2
console.log(b % a);  // Output: 0

Assignment Operators

Assignment operators are used to assign values to variables. The simple assignment operator is =. There are also compound assignment operators that combine an arithmetic operation with assignment:

  • +=
  • -=
  • *=
  • /=
  • %=

For example:

js
let a = 10;

a += 5;  // Same as a = a + 5; a is now 15

Comparison Operators

Comparison operators are used to compare two values. They return a Boolean value, either true or false. They include:

  • Equal to (==)
  • Not equal to (!=)
  • Strictly equal (equal value and equal type) (===)
  • Strictly not equal (not equal value or not equal type) (!==)
  • Greater than (>)
  • Less than (<)
  • Greater than or equal to (>=)
  • Less than or equal to (<=)

For example:

js
let a = 10;
let b = '10';

console.log(a == b);  // Output: true
console.log(a === b);  // Output: false

Logical Operators

Logical operators are used to determine the logic between variables or values. They include:

  • Logical AND (&&)
  • Logical OR (||)
  • Logical NOT (!)

For example:

js
let a = true;
let b = false;

console.log(a && b);  // Output: false
console.log(a || b);  // Output: true
console.log(!a);  // Output: false

Other Operators

There are several other operators in JavaScript, including:

  • Conditional (Ternary) Operator (condition ? value_if_true : value_if_false)
  • Type Operator (typeof)
  • Instanceof Operator (instanceof)

For example:

js
let age = 15;

let canVote = (age >= 18) ? "Yes" : "No";
console.log(canVote);  // Output: No

console.log(typeof age);  // Output: number

let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits instanceof Array);  // Output: true

Control Structures

Control structures in JavaScript determine the flow of execution of the program based on certain conditions or loops. They help to make decisions, perform tasks multiple times, or iterate over a range of values. In this chapter, I'll explore conditional statements and loops.

Conditional Statements

Conditional statements are used to perform different actions based on different conditions. In JavaScript, we have several types of conditional statements:

  • if statement: Executes a block of code if a specified condition is true.
let age = 20
if (age >= 18) {
  console.log('You are eligible to vote.')
}
  • if...else statement: Executes a block of code if a specified condition is true. If the condition is false, another block of code will be executed.
js
let age = 15;
if (age >= 18) {
  console.log('You are eligible to vote.');
} else {
  console.log('You are not eligible to vote.');
}
  • if...else if...else statement: Executes different blocks of code for different conditions.
js
let score = 85;
if (score >= 90) {
  console.log('Grade A');
} else if (score >= 80) {
  console.log('Grade B');
} else {
  console.log('Grade C');
}
  • switch statement: Selects one of many code blocks to be executed.
js
let day = 3;
switch (day) {
  case 1:
    console.log('Monday');
    break;
  case 2:
    console.log('Tuesday');
    break;
  case 3:
    console.log('Wednesday');
    break;
  //...
  default:
    console.log('Invalid day');
}

Loops

Loops are used to execute a block of code a number of times. JavaScript supports different kinds of loops:

  • for loop: Loops through a block of code a number of times.
js
for (let i = 0; i < 5; i++) {
  console.log(i);
}
  • while loop: Loops through a block of code while a specified condition is true.
js
let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}
  • do...while loop: Also loops through a block of code while a specified condition is true. The difference from the while loop is that the do...while loop will execute the code block once before checking the condition.
js
let i = 0;
do {
  console.log(i);
  i++;
} while (i < 5);
  • for...in loop: Loops through the properties of an object.
js
let person = {fname:"John", lname:"Doe", age:25};
for (let x in person) {
  console.log(x);
}
  • for...of loop: Loops through the values of an iterable objects.
js
let cars = ['BMW', 'Volvo', 'Mini'];
for (let x of cars) {
  console.log(x);
}

Ryusei Kakujo

researchgatelinkedingithub

Focusing on data science for mobility

Bench Press 100kg!