DEV Community

Cover image for JavaScript: Code Snippets
Abayomi Ogunnusi
Abayomi Ogunnusi

Posted on

JavaScript: Code Snippets

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 🐰 bunny is a variable, "bunny" is the value of the variable, and "string" is the data type.

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

console.log(bunny, dog, cat);
Enter fullscreen mode Exit fullscreen mode

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 ✔️

var bunny = 'lucy';
var _bunny = 'lucy';
var $bunny = 'lucy';
Enter fullscreen mode Exit fullscreen mode

Unacceptable naming conventions ❌

var 1bunny = 'lucy';
var -bunny = 'lucy';
var @bunny = 'lucy';
Enter fullscreen mode Exit fullscreen mode

Variable Declarations

JavaScript has three types of variable declarations:

  • var
  • let
  • const

Code sample

function animalName() {
  var bunny = 'lucy'; // Local variable
  console.log(bunny);
}
Enter fullscreen mode Exit fullscreen mode

Data Types

  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
var bunny_height = 3.14; // A number with decimals
var bunny_height = 3; // A number without decimals
Enter fullscreen mode Exit fullscreen mode
String
var bunny_name = 'Lucy'; // Using double quotes
var bunny_name = 'Tom'; // Using single quotes
Enter fullscreen mode Exit fullscreen mode
Boolean
var isBunnyHappy = true;
var isBunnyHappy = false;
Enter fullscreen mode Exit fullscreen mode
Null
var bunny = null; // Value is null. Null means "non-existent"
Enter fullscreen mode Exit fullscreen mode
Undefined
var bunny; // Value is undefined. Undefined means a variable has been declared, but not defined
Enter fullscreen mode Exit fullscreen mode
Symbol
var bunny = Symbol('Lucy'); // Symbol is a primitive data type, whose instances are unique and immutable
Enter fullscreen mode Exit fullscreen mode

Examples of Non-Primitive Data Types

Object
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
Enter fullscreen mode Exit fullscreen mode
Array
var bunnies = ['Lucy', 'Tom', 'Molly'];
console.log(bunnies[0]); // Output: Lucy
console.log(bunnies[1]); // Output: Tom
Enter fullscreen mode Exit fullscreen mode
Function
function adoptBunny() {
  console.log('Adopted a bunny');
}
Enter fullscreen mode Exit fullscreen mode

Exercise

Declare a variable named 🐰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.


 

Functions

  • 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:

// sum up the total bunnies in a farm
function sumBunnies() {
  var blackBunnies = 10;
  var whiteBunnies = 20;
  var totalBunnies = blackBunnies + whiteBunnies;
  return totalBunnies;
}
Enter fullscreen mode Exit fullscreen mode
  • 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:

sumBunnies();
Enter fullscreen mode Exit fullscreen mode

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

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

sumBunnies();
// result: 30
Enter fullscreen mode Exit fullscreen mode
  • The function above will return the value of totalBunnies which is 30.

The above function can be rewritten as an anonymous function

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

sumBunnies();
Enter fullscreen mode Exit fullscreen mode

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
function sumBunnies(blackBunnies, whiteBunnies) {
  var totalBunnies = blackBunnies + whiteBunnies;
  return totalBunnies;
}

sumBunnies(10, 20);

// result: 30
Enter fullscreen mode Exit fullscreen mode
  • 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
var sumBunnies = (blackBunnies, whiteBunnies) => {
  // the => is called the fat arrow
  var totalBunnies = blackBunnies + whiteBunnies;
  return totalBunnies;
};

sumBunnies(10, 20);
// result: 30
Enter fullscreen mode Exit fullscreen mode

IIFE (Immediately Invoked Function Expression)

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

(function () {
  var blackBunnies = 10;
  var whiteBunnies = 20;
  var totalBunnies = blackBunnies + whiteBunnies;
  console.log(totalBunnies);
})();
Enter fullscreen mode Exit fullscreen mode

Type-casting

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
var a = '14';
var b = '2';
var c = a / b;
console.log(c); // 7
Enter fullscreen mode Exit fullscreen mode
Number to String
var a = 14;
var b = 2;
var c = a / b;
console.log(c); // '7'
Enter fullscreen mode Exit fullscreen mode

Arrays and Array methods

These are some of the most common array methods:

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']
Enter fullscreen mode Exit fullscreen mode

 

Mixed Data Types - Array

You can store different data types in an array.

const mixedDataTypes = [true, 20, 'Lucy', null, undefined, { name: 'Lucy' }];
Enter fullscreen mode Exit fullscreen mode

Accessing Array Elements

You can access array elements by their index number.

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'
Enter fullscreen mode Exit fullscreen mode

Array Length

Get the length of an array.

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

bunnies.length; // 3
Enter fullscreen mode Exit fullscreen mode

Looping Through Arrays

You can loop through an array using a for loop.

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.
 */
Enter fullscreen mode Exit fullscreen mode

Nested Arrays

The elements of an array can be arrays themselves.

const nestedArrays = [
  ['Lucy', 'Tom'],
  ['Molly', 'Bella'],
];
Enter fullscreen mode Exit fullscreen mode

Accessing Nested Arrays

You can access nested arrays by chaining the index numbers.

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

// Access the first item in the first array
nestedArrays[0][0]; // 'Lucy'
Enter fullscreen mode Exit fullscreen mode

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.


 

JSON

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
{
  "name": "Lucy",
  "age": 3,
  "isHappy": true
}
Enter fullscreen mode Exit fullscreen mode

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

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

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

Convert JSON to JavaScript Object

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

console.log(bunny.name); // Lucy
Enter fullscreen mode Exit fullscreen mode

 

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

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
let bunny_age = 3;
let dog_age = 3;
console.log(bunny_age == dog_age); // true
Enter fullscreen mode Exit fullscreen mode
Strict equal to
let bunny_age = 3;
let dog_age = '3';
console.log(bunny_age === dog_age); // false
Enter fullscreen mode Exit fullscreen mode
Not equal to
let bunny_age = 3;
let dog_age = 4;
console.log(bunny_age != dog_age); // true
Enter fullscreen mode Exit fullscreen mode
Strict not equal to
let bunny_age = 3;
let dog_age = '3';
console.log(bunny_age !== dog_age); // true
Enter fullscreen mode Exit fullscreen mode
Greater than
let bunny_age = 3;
let dog_age = 4;
console.log(bunny_age > dog_age); // false
Enter fullscreen mode Exit fullscreen mode
Less than
let bunny_age = 3;
let dog_age = 4;
console.log(bunny_age < dog_age); // true
Enter fullscreen mode Exit fullscreen mode
Greater than or equal to
let bunny_age = 3;
let dog_age = 3;
console.log(bunny_age >= dog_age); // true
Enter fullscreen mode Exit fullscreen mode

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.


 

Conditional Statements

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

If Statement syntax

if (condition) {
  // code to be executed if condition is true
}
Enter fullscreen mode Exit fullscreen mode
Example
// check if bunny is healthy
let bunny = 'healthy';
if (bunny === 'healthy') {
  console.log('Bunny is healthy');
}
Enter fullscreen mode Exit fullscreen mode

If Else Statement syntax

if (condition) {
  // code to be executed if condition is true
} else {
  // code to be executed if condition is false
}
Enter fullscreen mode Exit fullscreen mode
Example
// 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');
}
Enter fullscreen mode Exit fullscreen mode

If Else If Statement syntax

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
}
Enter fullscreen mode Exit fullscreen mode
Example
// 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');
}
Enter fullscreen mode Exit fullscreen mode

 

Switch Statement syntax

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
}
Enter fullscreen mode Exit fullscreen mode
Example
// 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');
}
Enter fullscreen mode Exit fullscreen mode

Ternary Operator syntax

condition ? expression1 : expression2;
Enter fullscreen mode Exit fullscreen mode
Example
// check if bunny is healthy
let bunny = 'healthy';
bunny === 'healthy'
  ? console.log('Bunny is healthy')
  : console.log('Bunny is needs to see the vet');
Enter fullscreen mode Exit fullscreen mode

The above code is equivalent to:

if (bunny === 'healthy') {
  console.log('Bunny is healthy');
} else {
  console.log('Bunny is needs to see the vet');
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

To make a contribution to this repository. Make a Pull request to JS-simplified. Have fun coding

Top comments (3)

Collapse
 
mpinyaz profile image
Mpinyaz

very important

Collapse
 
nogou21 profile image
nogou21

nice one

Collapse
 
drsimplegraffiti profile image
Abayomi Ogunnusi

Thanks 🙏