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 th…


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Abayomi Ogunnusi

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);

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';

Unacceptable naming conventions ❌

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

Variable Declarations

JavaScript has three types of variable declarations:

  • var
  • let
  • const

Code sample

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

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

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

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
  • 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();

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

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);
})();

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

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']

 

Mixed Data Types - Array

You can store different data types in an array.

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

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'

Array Length

Get the length of an array.

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

bunnies.length; // 3

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.
 */

Nested Arrays

The elements of an array can be arrays themselves.

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

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'
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
}

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}

Convert JSON to JavaScript Object

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

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

 

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

 

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
}
Example
// check if bunny is healthy
let bunny = 'healthy';
if (bunny === 'healthy') {
  console.log('Bunny is healthy');
}

If Else Statement syntax

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

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
}
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');
}

 

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
}
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');
}

Ternary Operator syntax

condition ? expression1 : expression2;
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');

The above code is equivalent to:

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. Have fun coding


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Abayomi Ogunnusi


Print Share Comment Cite Upload Translate Updates
APA

Abayomi Ogunnusi | Sciencx (2022-10-08T08:21:01+00:00) JavaScript: Code Snippets. Retrieved from https://www.scien.cx/2022/10/08/javascript-code-snippets/

MLA
" » JavaScript: Code Snippets." Abayomi Ogunnusi | Sciencx - Saturday October 8, 2022, https://www.scien.cx/2022/10/08/javascript-code-snippets/
HARVARD
Abayomi Ogunnusi | Sciencx Saturday October 8, 2022 » JavaScript: Code Snippets., viewed ,<https://www.scien.cx/2022/10/08/javascript-code-snippets/>
VANCOUVER
Abayomi Ogunnusi | Sciencx - » JavaScript: Code Snippets. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/10/08/javascript-code-snippets/
CHICAGO
" » JavaScript: Code Snippets." Abayomi Ogunnusi | Sciencx - Accessed . https://www.scien.cx/2022/10/08/javascript-code-snippets/
IEEE
" » JavaScript: Code Snippets." Abayomi Ogunnusi | Sciencx [Online]. Available: https://www.scien.cx/2022/10/08/javascript-code-snippets/. [Accessed: ]
rf:citation
» JavaScript: Code Snippets | Abayomi Ogunnusi | Sciencx | https://www.scien.cx/2022/10/08/javascript-code-snippets/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.