JavaScript: Code Snippets
Tags: javascript, beginners, programming, tutorial
Published: 2022-10-08 08:21:01

This article has been compiled to demonstrate basic javascript syntax, concepts, and examples.
Without further ado, let's get started. 

---

#### Variables are containers for storing data values.

> In this example :rabbit: bunny is a variable, "bunny" is the value of the variable, and "string" is the data type.

```js
var bunny = 'lucy';
var dog = 'Tom';
var cat = 'Molly';

console.log(bunny, dog, cat);
```

---

### Variable Naming Rules

- JavaScript variables must be identified with unique names.

- JavaScript uses the keyword var to declare variables.

- The equal sign is used to assign values to variables.

- The semicolon ends the statement.

- JavaScript is case sensitive. This means that bunny and Bunny are different variables.

- JavaScript variables must begin with a letter, underscore, or dollar sign.

#### Acceptable naming conventions :heavy_check_mark:

```js
var bunny = 'lucy';
var _bunny = 'lucy';
var $bunny = 'lucy';
```

#### Unacceptable naming conventions :x:

```js
var 1bunny = 'lucy';
var -bunny = 'lucy';
var @bunny = 'lucy';
```

---

### Variable Declarations

#### JavaScript has three types of variable declarations:

- var
- let
- const



#### Code sample

```js
function animalName() {
  var bunny = 'lucy'; // Local variable
  console.log(bunny);
}
```

### Data Types <a name="data-types"></a>

1. Primitive Data Types
2. Non-Primitive Data Types

#### Primitive

1. Number
2. String
3. Boolean
4. Null
5. Undefined
6. Symbol

#### Non-Primitive

1. Object
2. Array
3. Function

#### Examples of Primitive Data Types

##### Number

```javascript
var bunny_height = 3.14; // A number with decimals
var bunny_height = 3; // A number without decimals
```

##### String

```javascript
var bunny_name = 'Lucy'; // Using double quotes
var bunny_name = 'Tom'; // Using single quotes
```

##### Boolean

```javascript
var isBunnyHappy = true;
var isBunnyHappy = false;
```

##### Null

```javascript
var bunny = null; // Value is null. Null means "non-existent"
```

##### Undefined

```javascript
var bunny; // Value is undefined. Undefined means a variable has been declared, but not defined
```

##### Symbol

```javascript
var bunny = Symbol('Lucy'); // Symbol is a primitive data type, whose instances are unique and immutable
```

---

#### Examples of Non-Primitive Data Types

##### Object

```javascript
var bunny = {
  name: 'Lucy',
  age: 3,
  isHappy: true,
};

console.log(bunny.name); // Output: Lucy
console.log(bunny.age); // Output: 3
console.log(bunny.isHappy); // Output: true
```

##### Array

```javascript
var bunnies = ['Lucy', 'Tom', 'Molly'];
console.log(bunnies[0]); // Output: Lucy
console.log(bunnies[1]); // Output: Tom
```

##### Function

```javascript
function adoptBunny() {
  console.log('Adopted a bunny');
}
```

---

##### Exercise

Declare a variable named :rabbit:`bunny` and assign it to an object with the following properties: `name`, `age`, and `isHappy`. Set the value of `name` to a string, `age` to a number, and `isHappy` to a boolean.

---

&nbsp;

#### Functions <a name="functions"></a>

- Functions are a set of statements that perform a task or calculates a value.

- Functions are executed when "something" invokes it (calls it).

Example of function declaration:

```javascript
// sum up the total bunnies in a farm
function sumBunnies() {
  var blackBunnies = 10;
  var whiteBunnies = 20;
  var totalBunnies = blackBunnies + whiteBunnies;
  return totalBunnies;
}
```

- The function above is called `sumBunnies` and it has no parameters.

- The function above returns the value of `totalBunnies`.

- The function above is called by using the function name followed by parentheses.

Example of function invocation:

```javascript
sumBunnies();
```

Let's write the function and invoke it in the console:

```javascript
function sumBunnies() {
  var blackBunnies = 10;
  var whiteBunnies = 20;
  var totalBunnies = blackBunnies + whiteBunnies;
  return totalBunnies;
}

sumBunnies();
// result: 30
```

- The function above will return the value of `totalBunnies` which is `30`.

The above function can be rewritten as an anonymous function

```javascript
var sumBunnies = function () {
  var blackBunnies = 10;
  var whiteBunnies = 20;
  var totalBunnies = blackBunnies + whiteBunnies;
  return totalBunnies;
};

sumBunnies();
```

---

#### Function Parameters

- Function parameters are listed inside the parentheses () in the function definition.

- Function arguments are the values received by the function when it is invoked.

##### Example

```javascript
function sumBunnies(blackBunnies, whiteBunnies) {
  var totalBunnies = blackBunnies + whiteBunnies;
  return totalBunnies;
}

sumBunnies(10, 20);

// result: 30
```

- The function above is called `sumBunnies` and it has two parameters: `blackBunnies` and `whiteBunnies`.

- The function above returns the value of `totalBunnies`.

- The function above is called by using the function name followed by parentheses.

---

#### Function Return

- The `return` statement stops the execution of a function and returns a value from that function.

- The `return` value of the function is "returned" back to the "caller":

---

#### Arrow Functions

- Arrow functions are a shorter syntax for writing function expressions.

##### Example of arrow function

```javascript
var sumBunnies = (blackBunnies, whiteBunnies) => {
  // the => is called the fat arrow
  var totalBunnies = blackBunnies + whiteBunnies;
  return totalBunnies;
};

sumBunnies(10, 20);
// result: 30
```

---

#### IIFE (Immediately Invoked Function Expression)

These are functions that are executed as soon as they are defined.

```javascript
(function () {
  var blackBunnies = 10;
  var whiteBunnies = 20;
  var totalBunnies = blackBunnies + whiteBunnies;
  console.log(totalBunnies);
})();
```

---

#### Type-casting <a name="type-casting"></a>

Type casting is the process of converting a value from one data type to another (such as string to number, object to boolean, and so on).

##### Examples of Type Casting

##### String to Number

```js
var a = '14';
var b = '2';
var c = a / b;
console.log(c); // 7
```

##### Number to String

```js
var a = 14;
var b = 2;
var c = a / b;
console.log(c); // '7'
```

---

### Arrays and Array methods <a name="arrays"></a>

These are some of the most common array methods:

```js
const bunnies = ['Lucy', 'Tom', 'Molly'];

// Add an item to the end of an array
bunnies.push('Bella'); // ['Lucy', 'Tom', 'Molly', 'Bella']

// Remove an item from the end of an array
bunnies.pop(); // ['Lucy', 'Tom', 'Molly']

// Add an item to the beginning of an array
bunnies.unshift('Bella'); // ['Bella', 'Lucy', 'Tom', 'Molly']

// Remove an item from the beginning of an array
bunnies.shift(); // ['Lucy', 'Tom', 'Molly']

// Find the index of an item in the array
bunnies.indexOf('Tom'); // 1

// Remove an item by index position
bunnies.splice(1, 1); // ['Lucy', 'Molly']

// Copy an array
const newBunnies = bunnies.slice(); // ['Lucy', 'Molly']
```

&nbsp;

### Mixed Data Types - Array

You can store different data types in an array.

```js
const mixedDataTypes = [true, 20, 'Lucy', null, undefined, { name: 'Lucy' }];
```

---

### Accessing Array Elements

You can access array elements by their index number.

```js
const bunnies = ['Lucy', 'Tom', 'Molly'];

// Access the first item in the array
bunnies[0]; // 'Lucy'

// Access the second item in the array
bunnies[1]; // 'Tom'
```

---

#### Array Length

Get the length of an array.

```js
const bunnies = ['Lucy', 'Tom', 'Molly'];

bunnies.length; // 3
```

---

#### Looping Through Arrays

You can loop through an array using a `for` loop.

```js
const bunnies = ['Lucy', 'Tom', 'Molly'];

for (let i = 0; i < bunnies.length; i++) {
  console.log(`Bunny ${bunnies[i]} is scheduled for a checkup today.`);
}

/* Result:
Bunny Lucy is scheduled for a checkup today.
Bunny Tom is scheduled for a checkup today.
Bunny Molly is scheduled for a checkup today.
 */
```

---

#### Nested Arrays

The elements of an array can be arrays themselves.

```js
const nestedArrays = [
  ['Lucy', 'Tom'],
  ['Molly', 'Bella'],
];
```

---

#### Accessing Nested Arrays

You can access nested arrays by chaining the index numbers.

```js
const nestedArrays = [
  ['Lucy', 'Tom'],
  ['Molly', 'Bella'],
];

// Access the first item in the first array
nestedArrays[0][0]; // 'Lucy'
```

---

##### Exercises

1. Create an array called `bunnies` that contains the names of six bunnies.

2. Add a new bunny called `Mario` to the end of the array.

3. Remove the bunny called `Lucy` from the array.

4. Add a new bunny called `Luigi` to the beginning of the array.

---

&nbsp;

#### JSON <a name="json"></a>

`JSON` stands for JavaScript Object Notation. It is a lightweight data-interchange format. We can use `JSON` to store and exchange data. JSON is often used when data is sent from a server to a web page.

##### Example of JSON

```json
{
  "name": "Lucy",
  "age": 3,
  "isHappy": true
}
```

**Note**: The key distinction between `JSON` and JavaScript objects is that `JSON` keys must be wrapped in double quotes. In JavaScript, keys can be wrapped in either single or double quotes.

JSON uses the `.json` file extension name.

#### Convert JavaScript Object to JSON

```javascript
let bunny = {
  name: 'Lucy',
  age: 3,
  isHappy: true,
};

let bunnyJSON = JSON.stringify(bunny);
console.log(bunnyJSON);
// {"name":"Lucy","age":3,"isHappy":true}
```

#### Convert JSON to JavaScript Object

```javascript
let bunnyJSON = '{"name":"Lucy","age":3,"isHappy":true}';
let bunny = JSON.parse(bunnyJSON);

console.log(bunny.name); // Lucy
```

---

&nbsp;

#### Exercises

1. Create a JavaScript object called `bunny` with the following properties: `name`, `age`, and `isHappy`. Set the values of the properties to your own bunny's name, age, and happiness level.

2. Convert the `bunny` object to `JSON` and store it in a variable called `bunnyJSON`.

---

#### Comparison Operators <a name="comparison-operators"></a>

For comparison operators, we can use the following operators:

- `==` (equal to)
- `===` (strict equal to)
- `!=` (not equal to)
- `!==` (strict not equal to)
- `>` (greater than)
- `<` (less than)
- `>=` (greater than or equal to)
- `<=` (less than or equal to)

#### Examples of Comparison Operators

##### Equal to

```js
let bunny_age = 3;
let dog_age = 3;
console.log(bunny_age == dog_age); // true
```

##### Strict equal to

```js
let bunny_age = 3;
let dog_age = '3';
console.log(bunny_age === dog_age); // false
```

##### Not equal to

```js
let bunny_age = 3;
let dog_age = 4;
console.log(bunny_age != dog_age); // true
```

##### Strict not equal to

```js
let bunny_age = 3;
let dog_age = '3';
console.log(bunny_age !== dog_age); // true
```

##### Greater than

```js
let bunny_age = 3;
let dog_age = 4;
console.log(bunny_age > dog_age); // false
```

##### Less than

```js
let bunny_age = 3;
let dog_age = 4;
console.log(bunny_age < dog_age); // true
```

##### Greater than or equal to

```js
let bunny_age = 3;
let dog_age = 3;
console.log(bunny_age >= dog_age); // true
```

---

#### Exercise

Use a comparison operator to check (less than or equal to) if the number of bunnies in the `bunnies` array is less than or equal to the number of dogs in the `dogs` array. If it is, print `There are more dogs than bunnies` to the console. If it is not, print `There are more bunnies than dogs` to the console.

---

&nbsp;

### Conditional Statements <a name="conditional"></a>

These are ways of controlling the flow of your code. They allow you to make decisions based on certain conditions.

#### If Statement syntax

```js
if (condition) {
  // code to be executed if condition is true
}
```

##### Example

```js
// check if bunny is healthy
let bunny = 'healthy';
if (bunny === 'healthy') {
  console.log('Bunny is healthy');
}
```

#### If Else Statement syntax

```js
if (condition) {
  // code to be executed if condition is true
} else {
  // code to be executed if condition is false
}
```

##### Example

```js
// check if bunny is healthy
let bunny = 'healthy';
if (bunny === 'healthy') {
  console.log('Bunny is healthy');
} else {
  console.log('Bunny is needs to see the vet');
}
```

#### If Else If Statement syntax

```js
if (condition) {
  // code to be executed if condition is true
} else if (condition) {
  // code to be executed if condition is true
} else {
  // code to be executed if condition is false
}
```

##### Example

```js
// check if bunny is healthy
let bunny = 'healthy';
if (bunny === 'healthy') {
  console.log('Bunny is healthy');
} else if (bunny === 'sick') {
  console.log('Bunny is needs to see the vet');
} else {
  console.log('Bunny health status unknown');
}
```

## &nbsp;

#### Switch Statement syntax

```js
switch (expression) {
  case x:
    // code to be executed if expression === x
    break;
  case y:
    // code to be executed if expression === y
    break;
  default:
  // code to be executed if expression does not match any cases
}
```

##### Example

```js
// check if bunny is healthy
let bunny = 'healthy';
switch (bunny) {
  case 'healthy':
    console.log('Bunny is healthy');
    break;
  case 'sick':
    console.log('Bunny is needs to see the vet');
    break;
  default:
    console.log('Bunny health status unknown');
}
```

---

#### Ternary Operator syntax

```js
condition ? expression1 : expression2;
```

##### Example

```js
// check if bunny is healthy
let bunny = 'healthy';
bunny === 'healthy'
  ? console.log('Bunny is healthy')
  : console.log('Bunny is needs to see the vet');
```

The above code is equivalent to:

```js
if (bunny === 'healthy') {
  console.log('Bunny is healthy');
} else {
  console.log('Bunny is needs to see the vet');
}
```

### Conclusion
To make a contribution to this repository. Make a Pull request to [JS-simplified](https://github.com/drsimplegraffiti/js-simplified). Have fun coding